from keras.utils import np_utils
import numpy as np
np.random.seed(10);
from keras.datasets import mnist
(x_train_image,y_train_label),(x_test_image,y_test_label)=mnist.load_data();
# 特征值进行reshape
x_Train=x_train_image.reshape(60000,784).astype('float32');
x_Test=x_test_image.reshape(10000,784).astype('float32');
# 将特征值进行标准化
x_Train_normalize=x_Train/255;
x_Test_normalize=x_Test/255;
# 将标签进行onehot编码
y_Train_Onehot=np_utils.to_categorical(y_train_label);
y_Test_Onehot=np_utils.to_categorical(y_test_label);
# 建立模型
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
model=Sequential();
model.add(Dense(units=1000,input_dim=784,kernel_initializer='normal',activation='relu'));
model.add(Dropout(0.5));
model.add(Dense(units=10,kernel_initializer='normal',activation='softmax'));
# 建立模型的摘要
print(model.summary());
# 建立训练
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']);
# train_history=model.fit(x=x_Train_normalize,y=y_Train_Onehot,validation_split=0,epochs=10,batch_size=200,verbose=1,validation_data=[x_Test_normalize,y_Test_Onehot],shuffle=True);
train_history=model.fit(x=x_Train_normalize,y=y_Train_Onehot,validation_split=0.2,epochs=10,batch_size=200,verbose=1,shuffle=True);
# 建立show_train_history显示过程
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();
# show_train_history(train_history,'acc','val_acc');
# 测试数据评估模型准确率
scores=model.evaluate(x_Test_normalize,y_Test_Onehot);
print("accuracy=",scores[1]);
# 进行预测
prediction=model.predict_classes(x_Test)
# 可视化
def plot_images_labels_prediction(images,labels,prediction,idx,num=10):
# 设置显示图形大小
fig=plt.gcf();
fig.set_size_inches(12,14);
# 如果显示项数参数大于25,就设置为25
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="label="+str(labels[idx]);
if len(prediction)>0:
title+=",predict="+str(prediction[idx]);
ax.set_title(title,fontsize=10);
# 设置不显示刻度
ax.set_xticks([]);
ax.set_yticks([]);
idx+=1;
plt.show();
plot_images_labels_prediction(x_test_image,y_test_label,prediction,idx=340);
# 利用pandas建立混淆矩阵
import pandas as pd
error_metric=pd.crosstab(y_test_label,prediction,rownames=['label'],colnames=['predict']);
print(error_metric);
df=pd.DataFrame({'label':y_test_label,'predict':prediction});
print(df[(df.label==5)&(df.predict==3)]);
Keras多层感知器识别手写数字
最新推荐文章于 2022-02-11 15:47:36 发布