基於Keras實現mnist-官方例子理解

前言

久聞keras大名,最近正好實訓,藉着這個機會好好學一下。python

首先推薦一個API,可能稍微有點舊,可是寫的是真的好git

https://keras-cn.readthedocs.io/en/latest/github

還有一個tensorflow的API網絡

https://www.w3cschool.cn/tensorflow_python/?lua

還有強烈推薦使用vscode+anaconda 配置環境spa

環境

安裝anaconda和vscode,在conda中新建keras的環境。code

conda create -n keras python=3.6
pip install tensorflow # 若是有GPU改成pip install tensorflow-gpu
pip install keras

正題

mnist是入門級別的數據集,是一個基本的分類數據集。此次嘗試構造深度神經網絡來構造一個圖像分類器。blog

import keras
from keras.datasets import mnist
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense,Conv2D,MaxPooling2D,Flatten
import cv2
import matplotlib
matplotlib.use('TkAgg')

batch_size=32
num_classes=10

(train_images,train_labels),(test_images,test_labels) = mnist.load_data()

print(train_images.shape,train_labels.shape)
print(test_images.shape,test_labels.shape)

"""
將數據集中圖片展現出來
"""

def show_mnist(train_image,train_labels):
    n = 3
    m = 3
    fig = plt.figure()
    for i in range(n):
        for j in range(m):
            plt.subplot(n,m,i*n+j+1)
            #plt.subplots_adjust(wspace=0.2, hspace=0.8)
            index = i * n + j #當前圖片的標號
            img_array = train_image[index]
            img = Image.fromarray(img_array)
            plt.title(train_labels[index])
            plt.imshow(img,cmap='Greys')
    plt.show()

img_row,img_col,channel = 28,28,1

mnist_input_shape = (img_row,img_col,1)

#將數據維度進行處理
train_images = train_images.reshape(train_images.shape[0],img_row,img_col,channel)
test_images = test_images.reshape(test_images.shape[0],img_row,img_col,channel)

train_images = train_images.astype("float32")
test_images = test_images.astype("float32")

## 進行歸一化處理
train_images  /= 255
test_images /= 255

# 將類向量,轉化爲類矩陣
# 從 5 轉換爲 0 0 0 0 1 0 0 0 0 0 矩陣
train_labels = keras.utils.to_categorical(train_labels,num_classes)
test_labels = keras.utils.to_categorical(test_labels,num_classes)



"""
構造網絡結構
"""
model = Sequential()
model.add(Conv2D(32,kernel_size=(3,3),
                    activation="relu",
                    input_shape=mnist_input_shape))
                    # kernalsize = 3*3 並無改變數據維度
model.add(Conv2D(16,kernel_size=(3,3),
                    activation="relu"
                    ))
model.add(MaxPooling2D(pool_size=(2,2)))
                    # 進行數據降維操做
model.add(Flatten())#Flatten層用來將輸入「壓平」,即把多維的輸入一維化,
                    #經常使用在從卷積層到全鏈接層的過渡。Flatten不影響batch的大小。
model.add(Dense(32,activation="relu"))
                    #全鏈接層
model.add(Dense(num_classes,activation='softmax'))

"""
編譯網絡模型,添加一些超參數
"""

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

model.fit(train_images,
            train_labels,
            batch_size=batch_size,
            epochs=5,
            verbose=1,
            validation_data=(test_images,test_labels),
            shuffle=True
            )

score = model.evaluate(test_images,test_labels,verbose=1)

print('test loss:',score[0])
print('test accuracy:',score[1])

其中涉及到幾個keras中的點,感受看完之後很透徹,可是這只是初步應用,以後還會繼續再寫的。圖片

jupyter notebook 版本的請訪問:https://github.com/pprp/keras-example/tree/master/implement/mnist_keras/ip

歡迎訪問個人Github:https://www.github.com/pprp/ star fork 感激涕零

相關文章
相關標籤/搜索