需要的包为keras,
环境搭建:
- conda create -n keras python=3.8 使用conda命令创建新环境,前提是有anaconda这个软件。
- activate keras 激活环境
- conda install tensorflow 因为keras是基于tensorflow的,所以需要先下载tansorflow 默认最新CPU版本
- conda install keras 安装keras
如果报各种环境错误,建议新建环境运行。因为有时用pip安装,有时用conda安装,很容易出现包版本冲突,建议都用conda安装
完整代码:
from keras.datasets import mnist ##从keras中导入mnist数据集,图片像素是28*28
from keras import models
from keras import layers
from keras.utils import to_categorical ##用于标签
#导入数据集
(train_images,train_labels),(test_images,test_labels)=mnist.load_data()##得到的是numpy数组
print(train_images.shape)##60000张图片,28*28像素大小
#定义网络
network=models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))##Dense为全连接层
network.add(layers.Dense(10,activation='softmax'))
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
#设置标签
train_labels=to_categorical(train_labels)
test_labels=to_categorical(test_labels)
##训练网络,使用fit函数
network.fit(train_images,train_labels,epochs=5,batch_size=128)
##查看在测试集上的效果
test_loss,test_acc=network.evaluate(test_images,test_labels)
print('test_acc',test_acc)##输出在测试集上的精度
输出结果:
Epoch 1/5
469/469 [==============================] - 2s 4ms/step - loss: 0.2569 - accuracy: 0.9259
Epoch 2/5
469/469 [==============================] - 2s 4ms/step - loss: 0.1031 - accuracy: 0.9694
Epoch 3/5
469/469 [==============================] - 2s 4ms/step - loss: 0.0685 - accuracy: 0.9797
Epoch 4/5
469/469 [==============================] - 2s 4ms/step - loss: 0.0486 - accuracy: 0.9850
Epoch 5/5
469/469 [==============================] - 2s 4ms/step - loss: 0.0368 - accuracy: 0.9892
313/313 [==============================] - 0s 968us/step - loss: 0.0709 - accuracy: 0.9788
test_acc 0.9787999987602234
在测试集上的精度为0.9787999987602234