1. 程式人生 > >keras CNN對CIFAR10影象分類

keras CNN對CIFAR10影象分類

from keras.datasets import cifar10
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D, Dense, AveragePooling2D, Flatten, BatchNormalization
from keras.optimizers import Adam
import numpy as np
import tensorflow as tf

(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()
X_train = X_train.astype('float32')/255
X_test = X_test.astype('float32')/255
print(Y_train.shape[0])
Y_train = Y_train.reshape(Y_train.shape[0])
Y_test = Y_test.reshape(Y_test.shape[0])
Y_train = np_utils.to_categorical(Y_train, 10)
Y_test = np_utils.to_categorical(Y_test, 10)

model = Sequential()
model.add(Conv2D(32, 5, strides=1, padding='same', input_shape=(32, 32, 3), activation=tf.nn.relu))
model.add(AveragePooling2D(3, 2, padding='same'))
model.add(BatchNormalization())

model.add(Conv2D(65, 5, strides=1, padding='same', activation=tf.nn.relu))
model.add(BatchNormalization())
model.add(AveragePooling2D(3, 2, padding='same'))
model.add(Flatten())

model.add(Dense(384, activation=tf.nn.relu))
model.add(Dense(192, activation=tf.nn.relu))
model.add(Dense(10, activation=tf.nn.softmax))

adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])
print('Training')
result = model.fit(X_train, Y_train, epochs=20, batch_size=64)

print('Testing')
loss, accuracy = model.evaluate(X_test, Y_test)
print('loss, accuracy', loss, accuracy)

訓練結果:

163s 3ms/step - loss: 0.0641 - acc: 0.9790

測試結果:

loss, accuracy 2.004339290237427 0.6988