用keras训练CIFAR10时候,报以下错误:
ValueError: Error when checking target: expected dense_2 to have 2dimensions, but got array with shape (10000, 1, 10)
将y的shape打印出来后发现:
(前两行为原始的CIFAR10的尺寸,后两行为转为one-hot
编码后的尺寸)
貌似原因在这里,将y转换为one-hot
编码后,y都是三维的。
但是dense_2得到的输出是二维的。
维度信息不匹配。
将程序放到同学的电脑上跑时,得到的却是二维的。
((50000, 32, 32, 3), (50000, 1))
((10000, 32, 32, 3), (10000, 1))
((50000, 32, 32, 3), (50000, 10))
((10000, 32, 32, 3), (10000, 10))
说明程序没有问题,可能是我的环境存在小问题。
解决办法一:
在转换为one-hot
编码之前,添加以下代码
y_train = y_train.reshape(y_train.shape[0])
y_test = y_test.reshape(y_test.shape[0])
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
问题得到解决。
解决办法二:
我的 kereas 版本是 2.1.0 ,版本太低,所以不支持直接转为one-hot
,升级为2.1.2后,可以直接转为one-hot
。
升级版本命令,
sudo pip install --upgrade keras==2.1.2
以下为程序全部代码:
import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
(x_train,y_train),(x_test,y_test) = cifar10.load_data()
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
import matplotlib.pyplot as plt
y_train = y_train.reshape(y_train.shape[0])
y_test = y_test.reshape(y_test.shape[0])
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
model = Sequential()
model.add(Conv2D(filters=32,kernel_size=(3,3),
input_shape=(32, 32,3),
activation='relu',
padding='same'))
model.add(Dropout(rate=0.25))
model.add(MaxPooling2D(pool_size=(2, 2))) # 16* 16y_test
model.add(Conv2D(filters=64, kernel_size=(3, 3),
activation='relu', padding='same'))
model.add(Dropout(0.25))
model.add(MaxPooling2D(pool_size=(2, 2))) # 8 * 8
model.add(Flatten()) # FC1,64个8*8转化为1维向量
model.add(Dropout(rate=0.25))
model.add(Dense(1024, activation='relu')) # FC2 1024
model.add(Dropout(rate=0.25))
model.add(Dense(10, activation='softmax')) # Output 10
model.summary()
opt = keras.optimizers.rmsprop(lr=0.0001,decay=1e-6)
model.compile(loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy'])
datagen = ImageDataGenerator(
rotation_range = 20,
zoom_range = 0.15,
horizontal_flip = True,
)
model.fit_generator(datagen.flow(x_train,y_train,batch_size=64),steps_per_epoch = 1000,epochs = 2,validation_data=(x_test,y_test),workers=4,verbose=1)
model.save('cifar10_trained_model.h5')
scores = model.evaluate(x_test,y_test,verbose=1)
print('Test loss:',scores[0])
print('Test accuracy:',scores[1])