初识神经网络——利用keras进行手写数字识别
from keras import backend as K
import numpy as np
import tensorflow as tf
import matplotlib.image as mpimg
import cv2
from os.path import splitext
from os import listdir
from glob import glob
from PIL import Image
from keras.datasets import mnist
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();
#搭建网络
network=models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
#配置网络
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['acc'])
#数据预处理
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)
#训练
network.fit(train_images,train_labels,epochs=5,batch_size=128)
#测试
test_loss,test_acc=network.evaluate(test_images,test_labels)
print('test_accuary:',test_acc)
控制台输出:
在训练集上的准确率为98.9%
在测试集上的准确率为97.8%
训练精度与测试精度之间的差距是过拟合造成的