gpt4 book ai didi

python - 使用numpy填充序列并将特征数组与序列数组的数量组合

转载 作者:行者123 更新时间:2023-12-01 06:35:01 25 4
gpt4 key购买 nike

我有许多序列存储在二维数组中[[first_seq,first_seq],[first_seq,first_seq],[sec_seq,sec_seq]],..

每个向量序列的长度各不相同。有些是 55 行长,有些是 68 行长。

序列 2D 数组(features) 的形状为 (427,227) (, features),我有另一个 1D 数组(num_seq ) (5,) 其中包含每个序列的长度 [55,68,200,42,62] (例如,第一个 seq 长 55 行,第二个 seq 长 68 行) ETC。)。 len(1D-array) = seq 数

现在,我需要每个序列都等长 - 即每个序列为 200。由于本例中有 5 个序列,因此生成的数组应为 structural_seq = np.zeros(5,200,227)

如果序列短于 200,则该序列的所有其他值都应为零。

因此,我尝试填充 structural_seq 执行以下操作:

for counter, sent in enumerate(num_seq):
for j, feat in enumerate(features):
if num_sent[counter] < 200:
structured_seq[counter,feat,]

但我卡住了..

准确地说:第一个序列是 2D 数组(features)的前 55 行,所有 145 行都应该用零填充。等等..

最佳答案

这是使用 np.insert 实现此目的的一种方法:

import numpy as np

# Sizes of sequences
sizes = np.array([5, 2, 4, 6])
# Number of sequences
n = len(sizes)
# Number of elements in the second dimension
m = 3
# Sequence data
data = np.arange(sizes.sum() * m).reshape(-1, m)
# Size to which the sequences need to be padded
min_size = 6
# Number of zeros to add per sequence
num_pads = min_size - sizes
# Zeros
pad = np.zeros((num_pads.sum(), m), data.dtype)
# Position of the new zeros
pad_pos = np.repeat(np.cumsum(sizes), num_pads)
# Insert zeros
out = np.insert(data, pad_pos, pad, axis=0)
# Reshape
out = out.reshape(n, min_size, m)
print(out)

输出:

[[[ 0  1  2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[ 0 0 0]]

[[15 16 17]
[18 19 20]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

[[21 22 23]
[24 25 26]
[27 28 29]
[30 31 32]
[ 0 0 0]
[ 0 0 0]]

[[33 34 35]
[36 37 38]
[39 40 41]
[42 43 44]
[45 46 47]
[48 49 50]]]

关于python - 使用numpy填充序列并将特征数组与序列数组的数量组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59717384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com