keras 序列填充

keras 使用pad_sequences 对序列进行填充,参考代码:

pad_sequences函数的签名为:

def pad_sequences(sequences, maxlen=None, dtype='int32',
                  padding='pre', truncating='pre', value=0.):
    """Pads sequences to the same length.

示例代码:

import numpy as np
from keras.preprocessing.sequence import pad_sequences

data = np.array([[1, 2], [3, 4, 5], [6, 7, 8, 9]])
max_len = max(map(len, data))
# 对长度小于max_len的元素进行左填充
data1 = pad_sequences(data, max_len, value=-1)
print(data1)
# [[-1 -1  1  2]
#  [-1  3  4  5]
#  [ 6  7  8  9]]

# 对超过max_len的进行左截断
max_len = 3
data2 = pad_sequences(data, max_len, value=-1)
print(data2)
# [[-1  1  2]
#  [ 3  4  5]
#  [ 7  8  9]]






标签: sequences、pad、len、max、keras、面试
猜你感兴趣的圈子:
NLP
  • 回复
隐藏