1. 程式人生 > 實用技巧 >基於tensorflow的手寫數字識別程式碼

基於tensorflow的手寫數字識別程式碼

基於tensorflow的手寫數字識別程式碼

from keras.utils import to_categorical
from keras import models, layers, regularizers
from keras.optimizers import RMSprop
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


train_images = train_images.reshape((60000, 28 * 28)).astype("float")
test_images = test_images.reshape((10000, 28 *28)).astype("float")
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

network = models.Sequential()
network.add(layers.Dense(units=128, activation='relu', input_shape=(28*28,),
                         kernel_regularizer=regularizers.l1(0.0001)))

# 百分之1使得神經元喪失效能
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=32, activation='relu', kernel_regularizer=regularizers.l1(0.0001)))
network.add(layers.Dropout(0.001))
network.add(layers.Dense(units=10, activation='softmax'))


# 檢視當前神經網路結構
print(network.summary())

# 編譯步驟
network.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

# 訓練網路,使用fit 函式,epochs 表示訓練多少回合,batch_size表示每次訓練給多大的資料。
network.fit(train_images, train_labels, epochs=20, batch_size=128, verbose=2)

# 使用測試集來測試效能
y_pre = network.predict(test_images[:5])
print(y_pre, test_labels[:5])
test_loss, text_accuracy = network.evaluate(test_images,test_labels)
print("test_loss",test_loss,".  ","test_accuracy: ", text_accuracy)

執行結果如下:

從結果可以看出,有一定程度的過擬合,優化程式碼可以解決