我正在尝试编码数字识别器。我有一个数据集,其中包含尺寸为60000 * 28 * 28的图像的像素数据,其中60000是图像数,28是宽度和高度(以像素为单位)。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train= x_train.reshape(60000, 28, 28, 1).astype('float32')
x_test= x_test.reshape(10000, 28, 28, 1).astype('float32')
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
classifier= Sequential()
classifier.add(Convolution2D(32, 3, 3, input_shape= (28, 28, 1), activation= 'relu'))
classifier.add(MaxPooling2D(pool_size= (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(output_dim = 128, activation= 'relu'))
classifier.add(Dense(output_dim = 10, activation= 'softmax'))
classifier.compile(optimizer= 'adam', loss='binary_crossentropy', metrics = ['accuracy'])
classifier.fit(x_train, y_train, validation_data= (x_test, y_test), nb_epoch= 15, verbose= 2, batch_size= 100)


我收到以下错误。

classifier.fit(x_train, y_train, validation_data= (x_test, y_test), nb_epoch= 15, verbose= 2, batch_size= 100)
Traceback (most recent call last):
  File "<ipython-input-4-9425b6d029dc>", line 1, in <module>
    classifier.fit(x_train, y_train, validation_data= (x_test, y_test), nb_epoch= 15, verbose= 2, batch_size= 100)
  File "C:\Users\SHUBHAM\Anaconda3\lib\site-packages\keras\models.py", line 672, in fit
    initial_epoch=initial_epoch)
  File "C:\Users\SHUBHAM\Anaconda3\lib\site-packages\keras\engine\training.py", line 1117, in fit
    batch_size=batch_size)
  File "C:\Users\SHUBHAM\Anaconda3\lib\site-packages\keras\engine\training.py", line 1034, in _standardize_user_data
    exception_prefix='model target')
  File "C:\Users\SHUBHAM\Anaconda3\lib\site-packages\keras\engine\training.py", line 124, in standardize_input_data
    str(array.shape))
ValueError: Error when checking model target: expected dense_2 to have shape (None, 10) but got array with shape (60000, 1)


我没有什么问题。请帮忙。

最佳答案

似乎与输出形状有关的误差。
正如我通过NN代码看到的
classifier.add(Dense(output_dim = 10, activation= 'softmax'))
输出必须具有形状[recordCount, 10]
但是当我运行python控制台并键入下一步时-我看到错误的y_train形状

>>> from keras.datasets import mnist
Using Theano backend.
Using gpu device 0: GeForce GT 730 (CNMeM is enabled with initial size: 70.0% of memory, cuDNN not available)
>>> (x_train, y_train), (x_test, y_test) = mnist.load_data()
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.pkl.gz
15253504/15296311 [============================>.] - ETA: 0s>>>
>>> x_train.shape
(60000, 28, 28)
>>> y_train.shape
(60000,)


且y_train的值在0..9范围内。因此,似乎我可以建议您进行下一次转换:

>>> import numpy
>>> y_train_new = numpy.zeros([60000, 10])
>>> for i in range(0, 10):
...     y_train_new[:, i] = (y_train == i).astype(numpy.int32)

关于python - 拟合模型时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41920834/

10-12 23:29