keras卷积神经网络识别手写体

本文介绍了一种使用Keras库构建的深度学习模型,该模型利用卷积神经网络(CNN)对MNIST数据集的手写数字进行识别。模型包含多个卷积层、池化层和全连接层,并使用了Dropout防止过拟合。经过训练,模型在测试集上取得了良好的准确率。
from keras.datasets import mnist
from keras.utils import np_utils
import numpy as np
np.random.seed(10);

(x_Train,y_Train),(x_Test,y_Test)=mnist.load_data();
print("done");
x_Train4D=x_Train.reshape(x_Train.shape[0],28,28,1).astype('float32');
x_Test4D=x_Test.reshape(x_Test.shape[0],28,28,-1).astype('float32');

x_Train4D_normalize=x_Train4D/255;
x_Test4D_normalize=x_Test4D/255;

y_TrainOneHot=np_utils.to_categorical(y_Train);
y_TestOneHot=np_utils.to_categorical(y_Test);

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

model=Sequential();
model.add(Conv2D(filters=16,kernel_size=(5,5),padding='same',input_shape=(28,28,1),activation='relu'));
model.add(MaxPooling2D(pool_size=(2,2)));
model.add(Conv2D(filters=36,kernel_size=(5,5),padding="same",activation='relu'));
model.add(MaxPooling2D(pool_size=(2,2)));
model.add(Dropout(0.25));
model.add(Flatten());
model.add(Dense(128,activation='relu'));
model.add(Dropout(0.5));
model.add(Dense(10,activation='softmax'));

print(model.summary());

model.compile(loss="categorical_crossentropy",optimizer="adam",metrics=['accuracy']);
train_history=model.fit(x=x_Train4D_normalize,y=y_TrainOneHot,batch_size=300,validation_split=0.2,epochs=10,verbose=1);

scores=model.evaluate(x_Test4D_normalize,y_TestOneHot);
print(scores[1]);

prediction=model.predict_classes(x_Test4D_normalize);
print(prediction);

# 显示混淆矩阵
import pandas as pd
crosstab=pd.crosstab(y_Test,prediction,rownames=['label'],colnames=['prediction']);
print(crosstab);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值