Keras框架下使用CNN进行CIFAR-10的识别测试

 


# coding: utf-8

# In[1]:


from keras.datasets import cifar10
import numpy as np
np.random.seed(10)


# In[2]:


(x_train_image,y_train_label),(x_test_image,y_test_label) = cifar10.load_data()


# In[3]:


x_train_image.shape


# In[4]:


x_test_image.shape


# In[5]:


x_train_image[0][0][0]


# In[6]:


label_dict = {0:"airplane",1:"automobile",2:"bird",3:"cat",4:"deer",5:"dog",6:"frog",7:"horse",8:"ship",9:"truck"}


# In[7]:


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


# In[8]:


plot_image_labels_prediction(x_train_image,y_train_label,[],0)


# In[9]:


x_train_normalize = x_train_image.astype('float32')/255.0
x_test_normalize = x_test_image.astype('float32')/255.0


# In[10]:


x_train_normalize[0][0][0:5]


# In[11]:


y_train_label[0:5]


# In[12]:


from keras.utils import np_utils
y_train_oneHot = np_utils.to_categorical(y_train_label)
y_test_oneHot = np_utils.to_categorical(y_test_label)


# In[13]:


y_train_oneHot[0:5]


# In[14]:


from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, ZeroPadding2D


# In[15]:


model = Sequential()


# In[16]:


model.add(Conv2D(filters=32,
                 kernel_size = (3,3),
                input_shape = (32,32,3),
                activation='relu',
                padding='same'))


# In[17]:


model.add(Dropout(rate=0.25))


# In[18]:


model.add(MaxPooling2D(pool_size=(2,2)))


# In[19]:


model.add(Conv2D(filters=64,
                 kernel_size = (3,3),
                activation='relu',
                padding='same'))


# In[20]:


model.add(Dropout(rate=0.25))


# In[21]:


model.add(MaxPooling2D(pool_size=(2,2)))


# In[22]:


model.add(Flatten())
model.add(Dropout(rate=0.25))


# In[23]:


model.add(Dense(1024,activation='relu'))
model.add(Dropout(rate=0.25))


# In[24]:


model.add(Dense(10,activation='softmax'))


# In[25]:


print(model.summary())


# In[26]:


model.compile(loss='categorical_crossentropy',
             optimizer = 'adam',
             metrics = ['accuracy'])


# In[27]:


try:
    model.load.weights("my_model.h5")
    print("加载了模型")
except:
    print("未加载模型")


# In[28]:


train_history = model.fit(x = x_train_normalize,
                         y = y_train_oneHot,
                         validation_split = 0.2,
                         epochs = 10,
                         batch_size = 256,
                         verbose = 1)


# In[29]:


model.save_weights("my_model.h5")
print("保存了模型")


# In[30]:


scores = model.evaluate(x_test_normalize,y_test_oneHot)
scores[1]


# In[31]:


import matplotlib.pyplot as plt
def show_train_history(train_history,train,validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train_History')
    plt.ylabel(train)
    plt.xlabel('Epoch')
    plt.legend(['train','validation'], loc = 'upper left')
    plt.show()


# In[32]:


show_train_history(train_history,'acc','val_acc')


# In[33]:


show_train_history(train_history,'loss','val_loss')


# In[34]:


prediction = model.predict_classes(x_test_normalize)


# In[35]:


prediction[:10]


# In[36]:


plot_image_labels_prediction(x_test_image,y_test_label,prediction,0,50)


# In[37]:


Predicted_probability = model.predict(x_test_normalize)


# In[38]:


def show_Predicted_probability(y,prediction,
                              x_img,Predicted_probability,i):
    print('label:',label_dict[y[i][0]],
         'predict:',label_dict[prediction[i]])
    plt.figure(figsize=(2,2))
    plt.imshow(np.reshape(x_test_image[i],(32,32,3)))
    plt.show()
    for j in range(10):
        print(label_dict[j]+'  P:%1.9f'%(Predicted_probability[i][j]))


# In[39]:


show_Predicted_probability(y_test_label,prediction,x_test_image,Predicted_probability,47)


# In[40]:


import pandas as pd
pd.crosstab(y_test_label.reshape(-1),
            prediction,
           rownames=['label'],
           colnames=['predict'])


# In[41]:




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值