-- 環(huán)境:win10, jupyter notebook/pycharm, python3.x, tensorflow1.3.0-gpu
上章我們學(xué)習(xí)了tensorflow怎樣運(yùn)用算法太實(shí)現(xiàn)MNIST手寫字的照片識別,這一節(jié)來建立一個(gè)簡單模型,使得識別精度更高。
Import Numpy ,Tensorflow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
Retrieve the training and test data
x_train, y_train, x_test, y_test = mnist.load_data(one_hot = True)

首先講講這句話的作用,matplotlib是最著名的Python圖表繪制擴(kuò)展庫,它支持輸出多種格式的圖形圖像,并且可以使用多種GUI界面庫交互式地顯示圖表。使用%matplotlib命令可以將matplotlib的圖表直接嵌入到Notebook之中,或者使用指定的界面庫顯示圖表,它有一個(gè)參數(shù)指定matplotlib圖表的顯示方式。inline表示將圖表嵌入到Notebook中。
其次,這個(gè)問題是說沒有合理的GUI請求,所以要安裝以下任何一種都可以,ipython-qtconsole就行。
IPython提供了許多魔法命令,使得在IPython環(huán)境中的操作更加得心應(yīng)手。魔法命令都以%或者%%開頭,以%開頭的成為行命令,%%開頭的稱為單元命令。行命令只對命令所在的行有效,而單元命令則必須出現(xiàn)在單元的第一行,對整個(gè)單元的代碼進(jìn)行處理。
執(zhí)行%magic可以查看關(guān)于各個(gè)命令的說明,而在命令之后添加?可以查看該命令的詳細(xì)說明。
#Visualiziing the data
import matplotlib.pyplot as plt
%matplotlib inline
#Function for displaying a training image by it's index in the MNIST set
def show_digit(index):
label = y_train[index].argmax(axis=0)
#Reshape 784 array into 28x28 image
image = x_train[index].reshape([28,28])
plt.title('Training data, indx:%d, Label:%d'%(index, label))
plt.imshow(image, cmap='gray_r')
plt.show()
#Display the first (index 0) training image
show_digit(0)

Define the meural network
def build_model():
#This resets all parameters and variables
tf.reset_default_graph()
#input layer ,Hidder layer(s),and set how you want to train the model
#input
net = tflearn.input_data([None, 784])
#hidder layer
net = tflearn.fully_connected(net,128, activation = 'ReLU')
#net = tflearn.fully_connected(net, 64, activation = 'ReLU')
#net = tflearn.fully_connected(net, 32, activation = 'ReLU')
net = tflearn.fully_connected(net, 20, activation = 'ReLU')
#Output layer
net = tflearn.fully_connected(net, 10, activation = 'softmax')
net = tflearn.regression(net, optimizer='sgd',learning_rate = 0.1,\
loss = 'categorical_crossentropy')
#This model assumes that your network is named 'net'
model = tflearn.DNN(net)
return model
此神經(jīng)網(wǎng)絡(luò)模型包含一個(gè)輸入層,兩個(gè)全連接層激活函數(shù)為ReLu,一個(gè)輸出層激活函數(shù)為softmax
Build the model
model = build_model()
training network
此處參數(shù)為調(diào)試后的最佳參數(shù),可以修改了觀察得到結(jié)果的不同,epoch不能太小,也不能太大,對自己網(wǎng)絡(luò)訓(xùn)練效果好就得適當(dāng)
model.fit(x_train,y_train, validation_set = 0.1, show_metric = True,batch_size =10,n_epoch = 11)


Testting
# Compare the labels that our model predicts with the actual labels
# Find the indices of the most confident prediction for each item. That tells us the predicted digit for that sample.
predictions = np.array(model.predict(testX)).argmax(axis=1)
# Calculate the accuracy, which is the percentage of times the predicated labels matched the actual labels
actual = testY.argmax(axis=1)
test_accuracy = np.mean(predictions == actual, axis=0)
# Print out the result
print("Test accuracy: ", test_accuracy)
