我有一个包含标记化单词列表的二维 numpy 数组。我想用 keras.processing.sequence-pad_sequences 填充这些列表。
我的二维数组的第一个维度对应于日期。对于每个日期,我都有 25 个(二维)标记化单词列表(我想填充这些列表)。
我的数组示例:
>>>tokenized_news_seq_trunc[0]
array([list([915, 3691, 53, 48, 3692, 361, 579, 2432, 20]),
list([453, 2433, 309, 1094, 133, 3, 228, 2433, 133, 3, 145, 133, 113]),
list([2434, 3693, 251, 10, 16, 3694, 1731, 3695, 229, 1353, 580]),
..., list([865, 913, 555, 17, 8086]),
list([3057, 1237, 121, 8087, 811, 2233, 497, 8088, 1, 8089, 8090, 44, 199, 8, 1771, 1072, 8091, 24, 72, 1280]),
list([8092, 10, 16, 63, 151, 76, 622, 980, 1758, 3690, 174, 207, 840, 3279, 8093, 8094, 8095, 12, 1650, 735, 8096])],
dtype=object)
我试过:
for i in range(tokenized_news_seq_trunc.shape[0]):
for j in range(tokenized_news_seq_trunc.shape[1]):
#print(tokenized_news_seq_trunc[i][j])
tokenized_news_seq_trunc[i[j]=pad_sequences(tokenized_news_seq_trunc[i][j], maxlen=MAX_LEN)
但我得到一个错误:ValueError: sequences must be a list of iterables。发现不可迭代:915。
我们可以看到它试图遍历列表中的每个元素,但没有成功。
我也试过:
for i in range(tokenized_news_seq_trunc.shape[0]):
#print(tokenized_news_seq_trunc[i][j])
tokenized_news_seq_trunc[i]=pad_sequences(tokenized_news_seq_trunc[i], maxlen=MAX_LEN)
但它返回:
ValueError:无法将输入数组从形状 (1989,27) 广播到形状 (1989)
(1989为日期数,27为MAX_LEN)
感谢您的帮助!
PS:或者,如果有更好的方法来使用列表,我有一个包含我标记化单词的列表列表
请您参考如下方法:
我从 pypi anago 文档中找到了填充嵌套序列的解决方案,但它不会将我的句子截断为 MAX_WORDS (27)。如果句子太长,我添加了最后一个 if 语句来实现截断
This function transforms a list of list sequences
into a 3D Numpy array of shape `(num_samples, max_sent_len, max_word_len)`.
Args:
sequences: List of lists of lists.
dtype: Type of the output sequences.
# Returns
x: Numpy array.
def pad_nested_sequences(sequences, dtype='int32'):
max_sent_len = 25
max_word_len = 27
for sent in sequences:
max_sent_len = max(len(sent), max_sent_len)
for word in sent:
max_word_len = max(len(word), max_word_len)
x = np.zeros((len(sequences), max_sent_len, max_word_len)).astype(dtype)
for i, sent in enumerate(sequences):
for j, word in enumerate(sent):
if j<max_word_len:
x[i, j, :len(word)] = word
return x
