数据集: https://pan.baidu.com/s/1mHQBPlRRv7phhxy25DUA9w 提取码: 419y
使用 CNN 卷积神经网络,直接放代码了
from keras.datasets import cifar10
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten
from PIL import Image
import numpy as np#导入各种库
(train_image, train_label), (test_image, test_label) = cifar10.load_data()#导入数据集
print('train = ', len(train_image))#看一下训练数据集有多少
print('test = ', len(test_image))
train_image_normalize = train_image.reshape(50000, 32, 32, 3).astype(float) / 255#数据标准化
test_image_normalize = test_image.reshape(10000, 32, 32, 3).astype(float) / 255
train_label_onehotencoding = np_utils.to_categorical(train_label)#标签一位有效编码
test_label_onehotencoding = np_utils.to_categorical(test_label)
model = Sequential()#创建模型
model.add(Conv2D(filters=32,kernel_size=(3,3), padding='same', input_shape=(32,32,3), activation='relu'))#卷积层
model.add(MaxPooling2D(pool_size=(2,2)))#池化层
model.add(Conv2D(filters=64,kernel_size=(3,3), padding='same', activation='relu'))#卷积层
model.add(MaxPooling2D(pool_size=(2,2)))#池化层
model.add(Dropout(0.25))#防止过度拟合
model.add(Flatten())#平坦层
model.add(Dense(1024, kernel_initializer='normal', activation='relu'))#添加隐藏层
model.add(Dropout(0.5))#防止过度拟合
model.add(Dense(units=10, kernel_initializer='normal', activation='softmax'))#建立隐藏层与输出层之间的关系
print(model.summary())#看一下模型的概况
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])#配置训练模型
train_history = model.fit(train_image_normalize, train_label_onehotencoding, validation_split=0.2, epochs=10, batch_size=200, verbose=2)#开始训练
scores = model.evaluate(test_image_normalize, test_label_onehotencoding)#用测试数据来验证准确率
print(scores)
#验证部分
img = Image.open('17_horse.png')
image_data = img.getdata()
image_data_array = np.array(image_data)
image_test = image_data_array.reshape(1, 32, 32, 3).astype(float) / 255
prediction = model.predict(image_test)
np.argmax(prediction)