手写数字识别mnist
手写数字识别mnist
手写数字识别mnist
文章目录
- 手写数字识别mnist
- 一、前言
- 二、环境配置
- 三、代码如下
- 四、配置环境过程
- 1、打开Anaconda Prompt
- a、创建一个叫MNIST4的环境
- b、创建成功后激活环境并下载keras包:
- c、下载matplotlib包
- d、下载tensorflow包
- 2、打开Pycharm配置
- 五、运行程序
一、前言
在实现手写数字识别的时候,我看到csdn上检索的手写数字识别有一些繁杂,可是作为AL世界的Hello World,这是不合理的,代码本来就不复杂。
繁杂的操作和图片有点让人生畏,所以我决定有必要重写一下程序、记录一下过程。
下面是一些国内的pip源,有需要可自取
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/
二、环境配置
软件:ANACONDA3+Pycharm2019
keras>=2.7;
tensorflow>=1.7
注:一定关掉科学上网
三、代码如下
#第一步:加载keras中的mnist集
from keras.datasets import mnist
(train_images, train_labels),(test_images, test_labels) = mnist.load_data()print(train_images.shape)#查看效果的,这两步可以忽略
print(test_images.shape)#第二步:建立网络架构,
from keras import models
from keras import layers
#层layer就像数据处理的筛子
#本例子含有两个Dense层,最后是一个10路的激活层softmax层,返回一个由10个概率值组成的数组,表示10个数字类别中某一个的概率
network=models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))#第三步:编译
#optimizer 优化器,loss损失函数,metrics代码级数据监控
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])#第四步:准备图像数据和标签
train_images = train_images.reshape((60000, 28 * 28))#图像处理
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255#通过二维关系矩阵的方式,生成一个对应关系
from keras.utils.all_utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)#第五步:拟合(FIT)模型
network.fit(train_images,train_labels,batch_size=64,epochs=5)#第六步:评估(EVALUATE)模型
test_loss,test_acc=network.evaluate(test_images,test_labels)#第七步:查看测试集的精度
print('test_acc',test_acc)
#训练精度和测试精度之间的这种差距是过拟合(overfit)造成的
以下是跑通这个程序的过程。如果清楚这些步骤的过程可以略过下面
四、配置环境过程
1、打开Anaconda Prompt
a、创建一个叫MNIST4的环境
conda create -n MNIST4 python=3.8
注:记得python=3.8,大了就下载不了tensorflow包了
b、创建成功后激活环境并下载keras包:
conda activate MNIST4
为了提高下载速度,在国内清华源中下载keras包
pip install keras -i https://pypi.tuna.tsinghua.edu.cn/simple/
c、下载matplotlib包
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple/
d、下载tensorflow包
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple/
2、打开Pycharm配置
配置代码运行环境
注:这里刷新出来的时候比较长,需要等等
之后一路点击确认下去
五、运行程序
将开头的程序copy进pycharm的程序中
这样就训练成功了。