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


前言

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

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

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

還有一個tensorflow的API

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

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

環境

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

conda create -n keras python=3.6
pip install tensorflow # 如果有GPU改為pip install tensorflow-gpu
pip install keras

正題

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


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/

歡迎訪問我的Github:https://www.github.com/pprp/ star fork 感激不盡


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM