實作Number Detection

本篇介紹簡易的number detection

實作資料庫:mnist

1
2
3
4
5
6
7
8
import numpy as np
from keras.models import Sequential
from keras.datasets import mnist
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.utils import np_utils #用來後續將label標籤轉換為one-hot-encoding
from matplotlib import pyplot as plt
#載入mnist 資料庫訓練資料,並自動分為 訓練組 以及 測試組
(X_train, y_train), (X_test, y_test) = mnist.load_data()

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step 11501568/11490434 [==============================] - 0s 0us/step

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from keras import models 
from keras import layers

#建立簡單的建模
model = Sequential()
#add input layer, 隱藏層(hidden layer)(通常超過兩層的hidden layers就是深度學習)有256個變數
#model.add(layers.Dense(512, activation = 'relu', imput_shape=(28*28,)))
model.add(Dense(units = 256, input_dim=784, kernel_initializer='normal', activation='relu'))

#Add output layer
#model.add(layer.Dense(10, activation = 'softmax))
model.add(Dense(units=10, kernel_initializer='normal', activation='softmax'))
#activation function: 非線性函數(像是sigmoid適合使用二分法在[0,1]之間 中間只有一小段模糊地帶適用於二分法
#activation function: softmax 可以將Y轉為機率值 且所有類別機率值為1,

#選擇loss function優化方法跟成效衡量方式 #以上已經有兩層Dense layers, 還需再加上以下進行編譯complilation
#optimizer = 'rmsprop', 'adam'
model.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])

#將training的label進行 one-hot-encoding, convert number to one-hot-encoding(像是7轉化one-hot-encofing會變成0000001000, 第7個數字會是1)
y_TrainOneHot = np_utils.to_categorical(y_train)
y_TestOneHot = np_utils.to_categorical(y_test)

#將training的input轉為2維(28,28)->(28*28)
X_train_2D = X_train.reshape(60000, 28*28).astype('float32')
X_test_2D = X_test.reshape(10000, 28*28).astype('float32')

X_train_norm = X_train_2D/255
X_test_norm = X_test_2D/255

#進行訓練,訓練過程會存在train history變數中
train_history = model.fit(x=X_train_norm, y=y_TrainOneHot, validation_split = 0.2, epochs = 10, batch_size=800, verbose=2)

#訓練成果(分數)
scores = model.evaluate(X_test_norm, y_TestOneHot)
print("\t[info]Accuracy of testing data = {:2.1f}%".format(scores[1]*100.0))

#Scores(測試集的準確率)比訓練資料準確率低一點,中間的差距就是過度配適(overfitting)

#預測
X = X_test_norm[0:10,:]
predictions = model.predict(X)

#get prediction result
print(predictions)
1
2
plt.imshow(X_test[1])
plt.show()
© 2022 Tiffany's Blog All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero