Keras Sequential - ValueError:检查目标时出错:期望dense_3有形状(None,45)但是有形状的数组(2868700,1)

时间:2018-05-02 11:54:33

标签: python tensorflow keras

我正在尝试使用keras API创建一个简单的深度神经网络但是我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/Ali J/PycharmProjects/SPECOM/1dcnn_experiment.py", line 86, in <module>
    model.fit(trainX, trainY)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\models.py", line 960, in fit
    validation_steps=validation_steps)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1574, in fit
    batch_size=batch_size)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1411, in _standardize_user_data
    exception_prefix='target')
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 153, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target: expected dense_3 to have shape (None, 45) but got array with shape (2868700, 1)

这是我的Python代码:

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=trainX.shape[1:]))
model.add(Dropout(0.25))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(set(trainY)), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=1e-4), metrics=["accuracy"])
model.fit(trainX, trainY)

#trainX.shape = (2868700, 57)
#trainY.shape = (2868700,)

1 个答案:

答案 0 :(得分:0)

您需要将目标(trainY)转换为分类形状,这意味着一个热门形状。

您可以使用此keras功能:

keras.utils.to_categorical(y, num_classes=None)
  

将类向量(整数)转换为二进制类矩阵。

     

E.g。用于categorical_crossentropy。

     

<强>参数

     
      
  • y:要转换为矩阵的类向量(从0到num_classes的整数)。
  •   
  • num_classes:类的总数。
  •   
     

<强>返回

     

输入的二进制矩阵表示。

Link to the respective part of the Keras Documentation.