#載入cifar10,預處理資料
from keras.datasets import cifar10
import numpy as np
np.random.seed(10)
(x_img_train,y_label_train),(x_img_test,y_label_test)=cifar10.load_data()
print("train data:",'images:',x_img_train.shape,"labels",y_label_train.shape)
print("test data:",'images:',x_img_test.shape,"labels",y_label_test.shape)
x_img_train_normalize=x_img_train.astype('float32')/255.0
x_img_test_normalize=x_img_test.astype('float32')/255.0
from keras.utils import np_utils
y_label_train_OneHot=np_utils.to_categorical(y_label_train)
y_label_test_OneHot=np_utils.to_categorical(y_label_test)
#建立模型
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation,Flatten
from keras.layers import Conv2D,MaxPooling2D,ZeroPadding2D
model=Sequential()
#第一次
model.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=(32,32,3),activation='relu',padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
#第二次
model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu',padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
#第三次
model.add(Conv2D(filters=128,kernel_size=
(3,3),activation='relu',padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(filters=128,kernel_size=(3,3),activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dropout(0.3))
model.add(Dense(2500,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(1500,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
#開始訓練
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
train_history=model.fit(x=x_img_train_normalize,y=y_label_train_OneHot,validation_split=0.2,epochs=50,batch_size=300,verbose=1)
#會花很多時間所以我沒讓他跑完,但書上說準確率是0.788,比之前高。
#改良程式碼:減少訓練次數和仔入權重。
try:
model.load_weights("SaveModel/cifarCnnModel.h5")
print("載入模型成功")
except:
print("載入模型失敗")
output:
載入模型失敗
因為尚未儲存模型
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
train_history=model.fit(x=x_img_train_normalize,y=y_label_train_OneHot,validation_split=0.2,epochs=5,batch_size=128,verbose=1)
#跑完之後儲存weights
model.save_weights("SaveModel/cifarCnnModel.h5")
print("save model to disk")