拟合模型时出错

时间:2017-01-29 12:21:26

标签: python machine-learning keras

我正在尝试编码数字识别器。我的数据集包含尺寸为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)

我没有得到什么问题。请帮助。

1 个答案:

答案 0 :(得分:1)

似乎与输出形状相关的错误。 我可以通过NN代码看到 classifier.add(Dense(output_dim = 10, activation= 'softmax')) 输出必须具有形状[recordCount, 10]。 但是当我运行python控制台并输入next时 - 我看到错误的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)