我无法理解我在这段代码中收到的错误信息。其中x_train
部分来自于一个展示如何在Keras中使用LSTM的工作示例。
mytrain
部分只是我为了理解各种函数而尝试的一个示例。
从消息中可以看出,x_train
和mytrain
具有相同的类型和形状。
from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb
import numpy as np
max_features = 80
maxlen = 5
# from the example
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print('x_train type: ', type(x_train))
print('x_train shape:', x_train.shape)
sequence.pad_sequences(x_train, maxlen=maxlen)
# my test code
mytrain = np.ones_like(x_train)
print('mytrain type:', type(mytrain))
print('mytrain shape:', mytrain.shape)
mytrain2 = sequence.pad_sequences(mytrain, maxlen=maxlen)
输出:
D:\python\python.exe D:/workspace/YYYY/test/test_sequences.py
Using TensorFlow backend.
x_train type: <class 'numpy.ndarray'>
x_train shape: (25000,)
Traceback (most recent call last):
File "D:/workspace/YYYY/test/test_sequences.py", line 22, in <module>
mytrain2 = sequence.pad_sequences(mytrain, maxlen=10)
File "D:\python\lib\site-packages\keras\preprocessing\sequence.py", line 42, in pad_sequences
'Found non-iterable: ' + str(x))
mytrain type: <class 'numpy.ndarray'>
ValueError: `sequences` must be a list of iterables. Found non-iterable: 1
mytrain shape: (25000,)
如果我使用像mytrain = np.asarray([[1, 2, 3]])
(可迭代列表)这样的内容,它可以工作,但我无法理解在先前代码中x_train
和mytrain
之间的区别。
mytrain = np.asarray([[1, 2, 3]])
是可以的。然而,print('mytrain shape:', mytrain.shape)
会输出mytrain shape: (1, 3)
,而x_train
是(N,)
。我仍然感到困惑。 - Antonio Sesto