【Keras】30 秒上手 Keras+实例对mnist手写数字进行识别准确率达99%以上

本文我们将学习使用Keras一步一步搭建一个卷积神经网络。具体来说,我们将使用卷积神经网络对手写数字(MNIST数据集)进行识别,并达到99%以上的正确率。

@为什么选择Keras呢?

主要是因为简单方便。更多细节请看:https://keras.io/

@什么卷积神经网络?

简单地说,卷积神经网络(CNNs)是一种多层神经网络,它可以有效地减少全连接神经网络参数量太大的问题。

下面就直接进入主题吧!

import keras 
keras.__version__

‘2.1.5’

from keras.models import Sequential
# 序贯模型
model = Sequential() 
from keras.layers import Dense 
import numpy as np 
import tensorflow as tf

配置keras模型

# units 矩阵运算输出的特征维度,input_dim 输入数据特征维度
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax')) 
model.add(Dense(units = 1024,activation='tanh')) 
model.output_shape

(None, 10)

model.output_shape

(None, 1024)

在完成了模型的构建后, 可以使用 .compile() 来配置学习过程

model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

训练

不需要写for循环

model.fit(x_train, y_train, epochs=5, batch_size=32)

一批批交给模型,需要自己写for循环

model.train_on_batch(x_batch, y_batch)

模型评估

loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)

模型预测

classes = model.predict(x_test, batch_size=128)



实例 mnist 手写数字进行识别

(外网下载数据可能很慢或者timeouts)

导包、定义变量

import keras
# 数据集
from keras.datasets import mnist
# 序贯模型
from keras.models import Sequential
# Dense:矩阵运算
# Dropout:防止过拟合
# Flatten:reshape(None,-1)
from keras.layers import Dense, Dropout, Flatten
# Conv2D:卷积运算
# MaxPooling2D:池化
from keras.layers import Conv2D, MaxPooling2D

# 后端,后台
# 默认Tensorflow
from keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

数据操作,转换

import tensorflow as tf 
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 四维的NHWC---->卷积运算需要
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)

# 类型转换
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

# 归一化 0 ~1
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

print(y_train.shape)
# convert class vectors to binary class matrices
# one-hot
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

模型构建

# 声明序贯模型
model = Sequential()
# 第一层卷积
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
# 第二层卷积
model.add(Conv2D(64, (3, 3), activation='relu'))
# 池化层
model.add(MaxPooling2D(pool_size=(2, 2)))
# dropout层
model.add(Dropout(0.25))
# reshape
model.add(Flatten())
# 全连接层,矩阵运算
model.add(Dense(1024, activation='relu'))
# dropout层
model.add(Dropout(0.5))
# 输出层
model.add(Dense(num_classes, activation='softmax'))

编译,最优化

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

训练

x_train.shape

(60000, 28, 28, 1)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

Train on 60000 samples, validate on 10000 samples
Epoch 1/12
26752/60000 [============>…] - ETA: 1:38 - loss: 0.3388 - acc: 0.8965

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

参考:
https://elitedatascience.com/keras-tutorial-deep-learning-in-python
http://adventuresinmachinelearning.com/keras-tutorial-cnn-11-lines/
https://keras.io/zh/#30-keras

发布了354 篇原创文章 · 获赞 163 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41856814/article/details/103605826