1 fromkeras.datasets Import Cifar102 fromkeras.utils Import Np_utils3Import Matplotlib.pyplot asPLT4 fromkeras.models Import Load_model5Import NumPy asNP6Np.random.seed (Ten)7(X_img_train,y_label_train), (x_img_test,y_label_test) =Cifar10.load_data ()8Print'Train Data=', Len (x_img_train))9Print'Test Data=', Len (x_img_test))TenPrint'X_train_image:', X_img_train.shape) OnePrint'X_test_image:', X_img_test.shape) AX_img_train_4d=x_img_train.reshape (x_img_train.shape[0], +, +,3). Astype ('float32') -X_img_test_4d=x_img_test.reshape (x_img_test.shape[0], +, +,3). Astype ('float32') -x_img_train_normalize=x_img_train_4d/255.0 thex_img_test_normalize=x_img_test_4d/255.0 -Print (x_img_train_normalize[0][0][0]) -y_label_train_onehot=np_utils.to_categorical (Y_label_train) -y_label_test_onehot=np_utils.to_categorical (y_label_test) +Print (y_label_train_onehot[:5]) - fromkeras.models Import Sequential + fromkeras.layers Import dense,dropout,flatten,conv2d,maxpooling2d,zeropadding2d,activation AModel=Sequential () atModel.add (conv2d (filters= +, -Kernel_size= (3,3), -padding='same', -Input_shape= ( +, +,3), -activation='Relu')) -Model.add (Dropout (0.25)) inModel.add (Maxpooling2d (pool_size= (2,2))) -Model.add (conv2d (filters= -, toKernel_size= (3,3), +padding='same', -activation='Relu')) theModel.add (Dropout (0.25)) *Model.add (Maxpooling2d (pool_size= (2,2))) $ Model.add (Flatten ())Panax NotoginsengModel.add (Dropout (0.25)) -Model.add (Dense (1024x768, activation='Relu')) theModel.add (Dropout (0.25)) +Model.add (Dense (Ten, activation='Softmax')) A print (Model.summary ()) theModel.compile (loss='categorical_crossentropy', +Optimizer='Adam', metrics=['accuracy']) - Try: $Model=load_model ("Cnnmodel.h5") $Print"Load Model successfully! Continuous training Model!......") - except: -Print"Failure of loading model! Start training A new model ...") the -Train_history=model.fit (x=X_img_train_normalize,Wuyiy=y_label_train_onehot,validation_split=0.2, theepochs=5, batch_size= -, verbose=1) -Model.save ("Cnnmodel.h5") WuPrint"Saved model to disk") - def show_train_history (train_history,train,validation): About Plt.plot (Train_history.history[train]) $ Plt.plot (train_history.history[validation]) -Plt.title ('Train History') - Plt.ylabel (train) -Plt.xlabel ('Epoch') APlt.legend (['Train','Validation'],loc='Upper Left') #显示左上角标签 + plt.show () theShow_train_history (Train_history,'ACC','VAL_ACC') -Show_train_history (Train_history,'Loss','Val_loss') $scores=model.evaluate (x_img_test_normalize,y_label_test_onehot) the print () thePrint'accuracy', scores[1]) theprediction=model.predict_classes (x_img_test_normalize) thePrint"Prediction[:10]", prediction[:Ten]) -Import Matplotlib.pyplot asPLT inlabel_dict={0:"Airplane",1:"Automobile",2:"Bird",3:"Cat",4:"Deer",5:"Dog",6:"Frog",7:"Horse",8:" Ship",9:"Truck"} thedef plot_image_labels_prediction_1 (image,labels,prediction,idx,num=Ten): thefig=PLT.GCF () AboutFig.set_size_inches ( A, -) the ifNum> -: num= - the forIinchRange0, num): theAx=plt.subplot (5,5, i+1) +Ax.imshow (image[idx],cmap='binary') -Title=str (i) +','+label_dict[labels[i][0]] the ifLen (prediction) >0:Bayititle+="="+Label_dict[prediction[i]] theAx.set_title (title,fontsize=Ten) the ax.set_xticks ([]); Ax.set_yticks ([]) -idx+=1 - plt.show () thePlot_image_labels_prediction_1 (X_img_test,y_label_test,prediction,0,Ten) thepredicted_probability=model.predict (x_img_test_normalize) the def show_predicted_probability (y,prediction,x_img_test,predicted_probability,i): thePrint'Label:', label_dict[y[i][0]],'Predict:', Label_dict[prediction[i]]) -Plt.figure (Figsize= (2,2)) thePlt.imshow (Np.reshape (X_img_test[i], ( +, +,3))) the plt.show () the forJinchRangeTen):94Print (label_dict[j]+ the 'probability:%1.9f'%(Predicted_probability[i][j])) theShow_predicted_probability (Y_label_test,prediction,x_img_test,predicted_probability,0) theShow_predicted_probability (Y_label_test,prediction,x_img_test,predicted_probability,3)
################################
Neural network cnn-cifar_10 image recognition