Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras密集层形状误差_Python_Tensorflow_Machine Learning_Keras - Fatal编程技术网

Python Keras密集层形状误差

Python Keras密集层形状误差,python,tensorflow,machine-learning,keras,Python,Tensorflow,Machine Learning,Keras,我正在使用keras创建一个LSTM模型。在训练中,我遇到了这个错误 ValueError:检查目标时出错:预期密集_4具有形状(1),但获得具有形状(34)的数组。 这是我的模型 model = Sequential() model.add(Embedding(max_words, embedding_dim, input_length=maxlen)) model.add(LSTM(128, activation='relu')) model.add(Dense(64, activ

我正在使用keras创建一个LSTM模型。在训练中,我遇到了这个错误

ValueError:检查目标时出错:预期密集_4具有形状(1),但获得具有形状(34)的数组。

这是我的模型

model = Sequential()

model.add(Embedding(max_words, embedding_dim, input_length=maxlen))    
model.add(LSTM(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(units = 34 ,activation='softmax'))

model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False

model.compile(optimizer='rmsprop',loss='sparse_categorical_crossentropy',metrics=['acc'])
型号摘要:

Layer (type)                 Output Shape              Param #   
=================================================================
embedding_2 (Embedding)      (None, 15, 50)            500000    
_________________________________________________________________
lstm_2 (LSTM)                (None, 128)               91648     
_________________________________________________________________
dense_3 (Dense)              (None, 64)                8256      
_________________________________________________________________
dropout_2 (Dropout)          (None, 64)                0         
_________________________________________________________________
dense_4 (Dense)              (None, 34)                2210      
=================================================================
Total params: 602,114
Trainable params: 102,114
Non-trainable params: 500,000
_________________________________________________________________
我打电话给fit使用

history = model.fit(X_train, y_train,epochs=100,batch_size=128)
y\u train
是一个热编码标签,形状
(299,34)
X\u列车
的形状是
(299,15)


我不确定模型为什么要寻找形状(1),因为我可以看到,
densed\u4(densed)
的输出形状为`(None,34)。好的,我发现了问题。我将此作为答案发布,以帮助其他同样面临同样问题的人

这不是层配置,而是错误的损失函数

我使用了
sparse\u categorical\u crossentropy
作为丢失,其中标签必须具有形状
[batch\u size]
和数据类型int32或int64。我改为
categorical\u crossentropy
,期望标签为[batch\u size,num\u classes]


keras抛出的错误消息具有误导性。

不过,您试图针对多少类?目前我使用34类(稍后将减少)。X_train和y_train的形状是什么?@krishna,用形状细节更新了问题。@Gp错误消息多么愚蠢!