菜鳥學人工智慧,簡單神經網絡train&test程序,python源碼

簡單神經網絡train and test詳解(雙層)

【 The latest data : 2018/05/01 】Yuchen

1. NN模型如下

神經網絡整體架構內容可參考之前的雲筆記《06_神經網絡整體架構》

http://note.youdao.com/noteshare?id=2c27bbf6625d75e4173d9fcbeea5e8c1&sub=7F4BC70112524F9289531EC6AE435E14

其中,

n是指的樣本數

Mnist數據集 784是28×28×1 灰度圖 channel = 1

wb是指的權重參數

輸出的是10分類的得分值,也可以接softmax分類器

out是L2層和輸出層之間的關係

256 128 10是指的神經元數量

2. 構造參數

菜鳥學人工智能,簡單神經網絡train&test程序,python源碼

函數構造

3. Code

1. 網絡模型架構搭建

導入相應數據

  1. import numpy as np

  2. import tensorflow as tf

  3. import matplotlib.pyplot as plt

  4. import input_data

  5. mnist = input_data.read_data_sets('data/', one_hot=True)

network topologies

  1. # 網絡拓撲 network topologies

  2. # layer中神經元數量

  3. n_hidden_1 =256

  4. n_hidden_2 =128

  5. # 輸入數據的像素點 28x28x1

  6. n_input =784

  7. # 10分類

  8. n_classes =10

input and output

  1. x = tf.placeholder("float",[None,n_input])

  2. y = tf.placeholder("float",[None,n_classes])

network parameters

  1. # network parameters

  2. # 方差

  3. stddev =0.1

  4. # random_normal 高斯初始化

  5. weights ={

  6. 'w1': tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev=stddev)),

  7. 'w2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)),

  8. 'out': tf.Variable(tf.random_normal([n_hidden_2,n_classes],stddev=stddev))

  9. }

  10. # 對於 b 零值初始化也可以

  11. biases ={

  12. 'b1': tf.Variable(tf.random_normal([n_hidden_1])),

  13. 'b2': tf.Variable(tf.random_normal([n_hidden_2])),

  14. 'out': tf.Variable(tf.random_normal([n_classes]))

  15. }

  16. print("Network Ready")

output

  1. NetworkReady

可以看到網絡模型架構搭建成功

2.訓練網絡模型

定義前向傳播函數

  1. # 定義前向傳播函數

  2. def multilayer_perceptron(_X, _weights, _biases):

  3. # 之所以加 sigmoid 是因為每一個 hidden layer 都有一個非線性函數

  4. layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1']))

  5. layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))

  6. return(tf.matmul(layer_2, _weights['out'])+ _biases['out'])

反向傳播

(1)將前向傳播預測值

  1. # prediction

  2. pred = multilayer_perceptron(x, weights, biases)

(2)定義損失函數

  1. # 首先定義損失函數 softmax_cross_entropy_with_logits 交叉熵函數

  2. # 交叉熵函數的輸入有 pred : 網絡的預測值 (前向傳播的結果)

  3. # y : 實際的label值

  4. # 將兩參數的一系列的比較結果,除以 batch 求平均之後的 loss 返回給 cost 損失值

  5. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))

(3)梯度下降最優化

  1. optm = tf.train.GradientDescentOptimizer(learning_rate =0.001).minimize(cost)

(4)精確值

具體解釋詳見上一篇筆記《06_迭代完成邏輯迴歸模型》

  1. corr = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))

  2. accr = tf.reduce_mean(tf.cast(corr,"float"))

(5)初始化

  1. # initializer

  2. init = tf.global_variables_initializer()

  3. print("Function ready")

output

  1. Function ready

可以看出傳播中的參數和優化模型搭建成功

3. Train and Test

  1. training_epochs =20

  2. # 每次 iteration 的樣本

  3. batch_size =100

  4. # 每四個 epoch 打印一次結果

  5. display_step =4

  6. # lanch the graph

  7. sess = tf.Session()

  8. sess.run(init)

  9. # optimize

  10. for epoch in range(training_epochs):

  11. # 初始,平均 loss = 0

  12. avg_cost =0

  13. total_batch =int(mnist.train.num_examples/batch_size)

  14. # iteration

  15. for i in range(total_batch):

  16. # 通過 next_batch 返回相應的 batch_xs,batch_ys

  17. batch_xs, batch_ys = mnist.train.next_batch(batch_size)

  18. feeds ={x: batch_xs, y: batch_ys}

  19. sess.run(optm, feed_dict = feeds)

  20. avg_cost += sess.run(cost, feed_dict = feeds)

  21. avg_cost = avg_cost / total_batch

  22. # display

  23. if(epoch+1)% display_step ==0:

  24. print("Epoch: %03d/%03d cost: %.9f "%(epoch, training_epochs, avg_cost))

  25. feeds ={x: batch_xs, y: batch_ys}

  26. train_acc = sess.run(accr, feed_dict = feeds)

  27. print("train accuracy: %.3f"%(train_acc))

  28. feeds ={x: mnist.test.images, y: mnist.test.labels}

  29. test_acc = sess.run(accr, feed_dict = feeds)

  30. print("test accuracy: %.3f"%(test_acc))

  31. print("optimization finished")

output

  1. Epoch:003/020 cost:2.273774184

  2. train accuracy:0.250

  3. test accuracy:0.197

  4. Epoch:007/020 cost:2.240329206

  5. train accuracy:0.270

  6. test accuracy:0.311

  7. Epoch:011/020 cost:2.203503076

  8. train accuracy:0.370

  9. test accuracy:0.404

  10. Epoch:015/020 cost:2.161286944

  11. train accuracy:0.490

  12. test accuracy:0.492

  13. Epoch:019/020 cost:2.111541148

  14. train accuracy:0.410

  15. test accuracy:0.534

  16. optimization finished

20個batch每個batch 100個樣本,每隔4個batch打印一次

處理器:Intel Core i5-6200U CPU @ 2.30GHz 2.04GHz

04 epoch:train+test, cost_time: 25’40”

08 epoch:train+test, cost_time: 50’29”

12 epoch:train+test, cost_time: 74’42”

16 epoch:train+test, cost_time: 98’63”

20 epoch:train+test, cost_time: 121’49”

想要更完整代碼或者跟作者交流,請留言頭條號。加入我們的社群。

菜鳥學人工智能,簡單神經網絡train&test程序,python源碼


分享到:


相關文章: