Python Keras:预期为 3 维,但得到了具有形状的数组 - 密集模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48674881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keras: Expected 3 dimensions, but got array with shape - dense model
提问by ldragicevic
I want to do multi label classification (20 distinct output labels), based on vectorized words using TfidfVectorizer. I have set of 39974 rows each one containing 2739 items (zeros or ones).
我想基于使用 TfidfVectorizer 的矢量化词进行多标签分类(20 个不同的输出标签)。我有 39974 行,每行包含 2739 个项目(零或一)。
I would like to classify this data using Keras model which will contain 1 hidden layer (~20 nodes with activation='relu') and output layer equal 20 possible output values (with activation='softmax' to choose best fit).
我想使用 Keras 模型对这些数据进行分类,该模型将包含 1 个隐藏层(约 20 个节点,激活 =“relu”)和输出层等于 20 个可能的输出值(激活 =“softmax”以选择最佳拟合)。
Here's my code so far:
到目前为止,这是我的代码:
model = Sequential()
model.add(Dense(units=20, activation='relu', input_shape=tfidf_matrix.shape))
model.add(Dense(units=20, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(tfidf_matrix, train_data['cuisine_id'], epochs=10)
But got error:
但得到错误:
ValueError: Error when checking input: expected dense_1_input to have 3 dimensions, but got array with shape (39774, 2739)
ValueError:检查输入时出错:预期dense_1_input有3维,但得到了形状为(39774, 2739)的数组
How can I specify this NN to fit using this matrix?
如何指定此 NN 以使用此矩阵进行拟合?
回答by Denis Zubo
The number of rows (number of training samples) is not the part of the input shape of the network because the training process feeds the network one sample per batch (or, more precisely, batch_size samples per batch).
行数(训练样本的数量)不是网络输入形状的一部分,因为训练过程为网络提供每批一个样本(或者更准确地说,每批 batch_size 个样本)。
So in your case, input shape of the network is (2739, )
and the right code should be like this:
所以在你的情况下,网络的输入形状是(2739, )
,正确的代码应该是这样的:
model = Sequential()
# the shape of one training example is
input_shape = tfidf_matrix[0].shape
model.add(Dense(units=20, activation='relu', input_shape=input_shape))
model.add(Dense(units=20, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(tfidf_matrix, train_data['cuisine_id'], epochs=10)