keras—神经网络CNN—CIFAR_10图像识别


1
from keras.datasets import cifar10 2 from keras.utils import np_utils 3 import matplotlib.pyplot as plt 4 from keras.models import load_model 5 import numpy as np 6 np.random.seed(10) 7 (x_img_train,y_label_train),(x_img_test,y_label_test)=cifar10.load_data() 8 print(\'train data=\',len(x_img_train)) 9 print(\'test data=\',len(x_img_test)) 10 print(\'x_train_image:\',x_img_train.shape) 11 print(\'x_test_image:\',x_img_test.shape) 12 x_img_train_4D=x_img_train.reshape(x_img_train.shape[0],32,32,3).astype(\'float32\') 13 x_img_test_4D=x_img_test.reshape(x_img_test.shape[0],32,32,3).astype(\'float32\') 14 x_img_train_normalize=x_img_train_4D/255.0 15 x_img_test_normalize=x_img_test_4D/255.0 16 print(x_img_train_normalize[0][0][0]) 17 y_label_train_OneHot=np_utils.to_categorical(y_label_train) 18 y_label_test_OneHot=np_utils.to_categorical(y_label_test) 19 print(y_label_train_OneHot[:5]) 20 from keras.models import Sequential 21 from keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D,ZeroPadding2D,Activation 22 model=Sequential() 23 model.add(Conv2D(filters=32, 24 kernel_size=(3,3), 25 padding=\'same\', 26 input_shape=(32,32,3), 27 activation=\'relu\')) 28 model.add(Dropout(0.25)) 29 model.add(MaxPooling2D(pool_size=(2,2))) 30 model.add(Conv2D(filters=64, 31 kernel_size=(3,3), 32 padding=\'same\', 33 activation=\'relu\')) 34 model.add(Dropout(0.25)) 35 model.add(MaxPooling2D(pool_size=(2,2))) 36 model.add(Flatten()) 37 model.add(Dropout(0.25)) 38 model.add(Dense(1024,activation=\'relu\')) 39 model.add(Dropout(0.25)) 40 model.add(Dense(10,activation=\'softmax\')) 41 print(model.summary()) 42 model.compile(loss=\'categorical_crossentropy\', 43 optimizer=\'adam\',metrics=[\'accuracy\']) 44 try: 45 model=load_model("CnnModel.h5") 46 print("Load model successfully!Continuous training model!......") 47 except : 48 print("Failure of loading model!Start training a new model......") 49 50 train_history=model.fit(x=x_img_train_normalize, 51 y=y_label_train_OneHot,validation_split=0.2, 52 epochs=5,batch_size=128,verbose=1) 53 model.save("CnnModel.h5") 54 print("Saved model to disk") 55 def show_train_history(train_history,train,validation): 56 plt.plot(train_history.history[train]) 57 plt.plot(train_history.history[validation]) 58 plt.title(\'Train History\') 59 plt.ylabel(train) 60 plt.xlabel(\'Epoch\') 61 plt.legend([\'train\',\'validation\'],loc=\'upper left\') #显示左上角标签 62 plt.show() 63 show_train_history(train_history,\'acc\',\'val_acc\') 64 show_train_history(train_history,\'loss\',\'val_loss\') 65 scores=model.evaluate(x_img_test_normalize,y_label_test_OneHot) 66 print() 67 print(\'accuracy\',scores[1]) 68 prediction=model.predict_classes(x_img_test_normalize) 69 print("prediction[:10]",prediction[:10]) 70 import matplotlib.pyplot as plt 71 label_dict={0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog",6:"frog",7:"horse",8:"ship",9:"truck"} 72 def plot_image_labels_prediction_1(image,labels,prediction,idx,num=10): 73 fig=plt.gcf() 74 fig.set_size_inches(12,14) 75 if num>25:num=25 76 for i in range(0,num): 77 ax=plt.subplot(5,5,i+1) 78 ax.imshow(image[idx],cmap=\'binary\') 79 title=str(i)+\',\'+label_dict[labels[i][0]] 80 if len(prediction)>0: 81 title+="=>"+label_dict[prediction[i]] 82 ax.set_title(title,fontsize=10) 83 ax.set_xticks([]);ax.set_yticks([]) 84 idx+=1 85 plt.show() 86 plot_image_labels_prediction_1(x_img_test,y_label_test,prediction,0,10) 87 Predicted_Probability=model.predict(x_img_test_normalize) 88 def show_Predicted_Probability(y,prediction,x_img_test,Predicted_Probability,i): 89 print(\'label:\',label_dict[y[i][0]],\'predict:\',label_dict[prediction[i]]) 90 plt.figure(figsize=(2,2)) 91 plt.imshow(np.reshape(x_img_test[i],(32,32,3))) 92 plt.show() 93 for j in range(10): 94 print(label_dict[j]+ 95 \'Probability:%1.9f\'%(Predicted_Probability[i][j])) 96 show_Predicted_Probability(y_label_test,prediction,x_img_test,Predicted_Probability,0) 97 show_Predicted_Probability(y_label_test,prediction,x_img_test,Predicted_Probability,3)
################################

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理

keras—神经网络CNN—CIFAR_10图像识别 - AI大道理