【Keras】30 秒上手 Keras+实例对mnist手写数字进行识别准确率达99%以上
本文我們將學(xué)習(xí)使用Keras一步一步搭建一個(gè)卷積神經(jīng)網(wǎng)絡(luò)。具體來(lái)說(shuō),我們將使用卷積神經(jīng)網(wǎng)絡(luò)對(duì)手寫數(shù)字(MNIST數(shù)據(jù)集)進(jìn)行識(shí)別,并達(dá)到99%以上的正確率。
@為什么選擇Keras呢?
主要是因?yàn)楹?jiǎn)單方便。更多細(xì)節(jié)請(qǐng)看:https://keras.io/
@什么卷積神經(jīng)網(wǎng)絡(luò)?
簡(jiǎn)單地說(shuō),卷積神經(jīng)網(wǎng)絡(luò)(CNNs)是一種多層神經(jīng)網(wǎng)絡(luò),它可以有效地減少全連接神經(jīng)網(wǎng)絡(luò)參數(shù)量太大的問(wèn)題。
下面就直接進(jìn)入主題吧!
import keras keras.__version__‘2.1.5’
from keras.models import Sequential # 序貫?zāi)P?/span> model = Sequential() from keras.layers import Dense import numpy as np import tensorflow as tf配置keras模型
# units 矩陣運(yùn)算輸出的特征維度,input_dim 輸入數(shù)據(jù)特征維度 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)
在完成了模型的構(gòu)建后, 可以使用 .compile() 來(lái)配置學(xué)習(xí)過(guò)程
model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])訓(xùn)練
不需要寫for循環(huán)
model.fit(x_train, y_train, epochs=5, batch_size=32)一批批交給模型,需要自己寫for循環(huán)
model.train_on_batch(x_batch, y_batch)模型評(píng)估
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)模型預(yù)測(cè)
classes = model.predict(x_test, batch_size=128)實(shí)例 mnist 手寫數(shù)字進(jìn)行識(shí)別
(外網(wǎng)下載數(shù)據(jù)可能很慢或者timeouts)
導(dǎo)包、定義變量
import keras # 數(shù)據(jù)集 from keras.datasets import mnist # 序貫?zāi)P?/span> from keras.models import Sequential # Dense:矩陣運(yùn)算 # Dropout:防止過(guò)擬合 # Flatten:reshape(None,-1) from keras.layers import Dense, Dropout, Flatten # Conv2D:卷積運(yùn)算 # MaxPooling2D:池化 from keras.layers import Conv2D, MaxPooling2D# 后端,后臺(tái) # 默認(rèn)Tensorflow from keras import backend as Kbatch_size = 128 num_classes = 10 epochs = 12# input image dimensions img_rows, img_cols = 28, 28數(shù)據(jù)操作,轉(zhuǎn)換
import tensorflow as tf # the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data()# 四維的NHWC---->卷積運(yùn)算需要 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)# 類型轉(zhuǎn)換 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)模型構(gòu)建
# 聲明序貫?zāi)P?/span> 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()) # 全連接層,矩陣運(yùn)算 model.add(Dense(1024, activation='relu')) # dropout層 model.add(Dropout(0.5)) # 輸出層 model.add(Dense(num_classes, activation='softmax'))編譯,最優(yōu)化
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])訓(xùn)練
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
參考:
https://elitedatascience.com/keras-tutorial-deep-learning-in-python
http://adventuresinmachinelearning.com/keras-tutorial-cnn-11-lines/
https://keras.io/zh/#30-keras
總結(jié)
以上是生活随笔為你收集整理的【Keras】30 秒上手 Keras+实例对mnist手写数字进行识别准确率达99%以上的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: himall微信支付
- 下一篇: Day10-时间