检查目标时出错:预期density_6具有2维,但数组的形状为(60000,10,10,10,10)

时间:2019-10-27 20:08:38

标签: python-3.x tensorflow keras deep-learning

我正在尝试构建CNN。我被困在这里。

x_train shape: (60000, 28, 28, 1)
x_test shape: (10000, 28, 28, 1)
60000 train samples
10000 test samples
y_train dimensions (60000, 10, 10, 10, 10)
y_test dimensions (10000, 10, 10, 10, 10)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(28,28,1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_5 (Conv2D)            (None, 26, 26, 32)        320       
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 24, 24, 64)        18496     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
flatten_3 (Flatten)          (None, 9216)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 128)               1179776   
_________________________________________________________________
dropout_6 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 10)                1290      
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0
_________________________________________________________________
None
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=3,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-28-3b73f30a94ae> in <module>
      4 
      5 model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=3,
----> 6           validation_data=(x_test, y_test))
      7 score = model.evaluate(x_test, y_test, verbose=0)
      8 print('Test loss:', score[0])

~/.local/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
   1152             sample_weight=sample_weight,
   1153             class_weight=class_weight,
-> 1154             batch_size=batch_size)
   1155 
   1156         # Prepare validation data.

~/.local/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    619                 feed_output_shapes,
    620                 check_batch_axis=False,  # Don't enforce the batch size.
--> 621                 exception_prefix='target')
    622 
    623             # Generate sample-wise weight values given the `sample_weight` and

~/.local/lib/python3.7/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    133                         ': expected ' + names[i] + ' to have ' +
    134                         str(len(shape)) + ' dimensions, but got array '
--> 135                         'with shape ' + str(data_shape))
    136                 if not check_batch_axis:
    137                     data_shape = data_shape[1:]

ValueError: Error when checking target: expected dense_6 to have 2 dimensions, but got array with shape (60000, 10, 10, 10, 10)

请帮我一个忙,
如何在这些库中调试此类错误。
您还会建议如何开始构建CNN吗?像专业人士一样。
任何来源将不胜感激。
请为我提供一些有关如何构建自定义CNN和自定义损失函数以及自定义激活函数的见解。
预先感谢。

1 个答案:

答案 0 :(得分:0)

是否可以添加用于预处理标签的代码(y_trainy_test)?为什么标签是5维的?通常,使用一键编码时它们是二维的。

以下是有关卷积神经网络的介绍性博文:

https://medium.com/intuitive-deep-learning/build-your-first-convolutional-neural-network-to-recognize-images-84b9c78fe0ce

有很多类似这样的好博客,只是用谷歌搜索就可以了。如果您是认真的人,可以考虑购买一本书,这就是我开始学习神经网络时所做的。首先,不需要自定义丢失功能和自定义激活功能。