Keras顺序模型拟合形状

时间:2020-06-14 07:38:49

标签: python keras

我可以在其他线程中找到类似的问题,但是我无法解决我的问题,因此我希望在这里得到解答。 我正在尝试使用以下代码训练模型:

''' split the sample '''
X_train, X_test, y_train, y_test = train_test_split(csvFile['Tweet'], csvFile['sent_score'], test_size= 0.20, shuffle=False)
'''add layers to define the input dimension of our feature vectors'''
input_dim = len(X_train)  # Number of features

model = Sequential()
model.add(layers.Dense(10, input_dim=input_dim, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

''' specifies the optimizer and the loss function '''
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())

X_train = np.asarray(X_train)
y_train = np.asarray(y_train)
X_test = np.asarray(X_test)
y_test = np.asarray(y_test)

''' fit the model '''
history = model.fit(X_train, y_train, epochs=100, verbose=False, validation_data=(X_test, y_test), batch_size=10)

我遇到以下错误:

Traceback (most recent call last):
  File "test.py", line 209, in <module>
    history = model.fit(X_train, y_train, epochs=100, verbose=False, validation_data=(X_test, y_test), batch_size=10)
  File "/Users/delalma/Library/Python/3.7/lib/python/site-packages/keras/engine/training.py", line 952, in fit
    batch_size=batch_size)
  File "/Users/delalma/Library/Python/3.7/lib/python/site-packages/keras/engine/training.py", line 751, in _standardize_user_data
    exception_prefix='input')
  File "/Users/delalma/Library/Python/3.7/lib/python/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data
    str(data_shape))
ValueError: Error when checking input: expected dense_1_input to have shape (23136,) but got array with shape (1,)

当我尝试按照错误要求重塑形状时(23136,)。我得到了相反的错误,如下所示。可能这里的关键是错误不在同一层上。任何帮助将不胜感激。

   ValueError: Error when checking input: expected dense_2_input to have shape (1,) but got array with shape (23136,)

2 个答案:

答案 0 :(得分:0)

input_dim = len(X_train)不是要素数量,而是样本数量...将其更改为input_dim = X_train.shape[-1]

这是一个虚拟的例子:

X = np.random.uniform(0,1, 23136)
y = np.random.uniform(0,1, 23136)

input_dim = 1 # or X.shape[-1] if more feature are present

model = Sequential()
model.add(layers.Dense(10, input_dim=input_dim, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,y, epochs=10)

答案 1 :(得分:0)

您可以尝试以下方法:

from tensorflow.keras.layers import Reshape    

model = Sequential()
model.add(Reshape((X_train.shape[1],1)))
model.add(layers.Dense(10, input_dim=(X_train.shape[1],1), activation='relu'))