【问题标题】:Padding sequence with numpy and combining a feature array with the number of sequence array用 numpy 填充序列并将特征数组与序列数组的数量相结合
【发布时间】:2020-04-30 05:04:26
【问题描述】:

我有一些序列存储在二维数组[[first_seq,first_seq],[first_seq,first_seq],[sec_seq,sec_seq]],.. 中。

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

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

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

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

因此,我尝试填写structured_seq 执行以下操作:

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

但我卡住了..

所以准确地说:第一个序列是二维数组的前 55 行(features),所有重复的 145 都应该用零填充。等等……

【问题讨论】:

    标签: python pandas numpy padding


    【解决方案1】:

    这是您可以通过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]]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 2019-12-28
      • 2016-12-01
      • 2019-04-06
      • 1970-01-01
      • 2021-12-18
      • 2020-03-03
      相关资源
      最近更新 更多