欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

keras实战cifar10数据集

程序员文章站 2022-06-21 15:07:07
...
from keras.datasets import cifar10
import numpy as np
np.random.seed(10);

(x_Train,y_Train),(x_Test,y_Test)=cifar10.load_data();
print("train data:","images:",x_Train.shape,"labels:",y_Train.shape);
print("test data:","images:",x_Test.shape,"labels:",y_Test.shape);
x_Train_normalize=x_Train.astype("float32")/255.0;
x_Test_normalize=x_Test.astype("float32")/255.0;

from keras.utils import np_utils
y_Train_OneHot=np_utils.to_categorical(y_Train);
y_Test_OneHot=np_utils.to_categorical(y_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.25));
model.add(MaxPooling2D(pool_size=(2,2)));
model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu',padding='same'));
model.add(Dropout(0.25));
model.add(MaxPooling2D(pool_size=(2,2)));
model.add(Flatten());
model.add(Dropout(0.25));
model.add(Dense(1024,activation='relu'));
model.add(Dropout(0.25));
model.add(Dense(10,activation='softmax'));

print(model.summary());

model.compile(loss="categorical_crossentropy",optimizer="adam",metrics=['accuracy']);
train_history=model.fit(x_Train_normalize,y_Train_OneHot,validation_split=0.2,epochs=10,batch_size=128,verbose=1);

prediction=model.predict_classes(x_Test_normalize);
prediction_classes={0:"飞机",1:"自动手机",2:"鸟",3:"猫",4:"鹿",5:"狗",6:"青蛙",7:"马",8:"船",9:"卡车"};
# for i in prediction:
#     print(prediction_classes[i]);
print(prediction);

import matplotlib.pyplot as plt
def plot_images_labels_prediction(images,labels,prediction,idx,num=10):
    fig=plt.gcf();
    fig.set_size_inches(12,14);
    if num>25:
        num=25;
    for i in range(0,num):
        ax=plt.subplot(5,5,i+1);
        ax.imshow(images[idx],cmap='binary');
        title=str(i)+","+prediction_classes[labels[i][0]];
        if len(prediction)>0:
            title+='=>'+prediction_classes[prediction[i]];
        ax.set_title(title,fontsize=10);
        ax.set_xticks([]);
        ax.set_yticks([]);
        idx+=1;
    plt.show();

plot_images_labels_prediction(x_Test,y_Test,prediction,100);

model.save_weights("model/cifar.h5");
print("save success");

try:
    model.load_weights("model/cifar.h5");
    print("load success");
except:
    print("load failed");
相关标签: 代码