生活随笔
收集整理的這篇文章主要介紹了
Tensorflow实现MLP
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
??多層感知機(jī)(MLP)作為最典型的神經(jīng)網(wǎng)絡(luò),結(jié)構(gòu)簡單且規(guī)則,并且在隱層設(shè)計(jì)的足夠完善時(shí),可以擬合任意連續(xù)函數(shù)。本文將利用 MLP 實(shí)現(xiàn)手寫數(shù)字分類的任務(wù)。
結(jié)構(gòu):
??784個(gè)輸入層神經(jīng)元 – 200個(gè)隱層神經(jīng)元 – 10個(gè)輸出層神經(jīng)元。其中,設(shè)置 relu為隱層的激活函數(shù),輸出層用 SoftMax 進(jìn)行處理
Dropout:
??將神經(jīng)網(wǎng)絡(luò)某一層的輸出節(jié)點(diǎn)數(shù)據(jù)隨機(jī)丟棄一部分,即令這部分被隨機(jī)選中的節(jié)點(diǎn)輸出值令為0,這樣做等價(jià)于創(chuàng)造出很多新樣本,通過增大樣本量,減少特征數(shù)量來防止過擬合。
學(xué)習(xí)效率:
??因?yàn)樯窠?jīng)網(wǎng)絡(luò)的訓(xùn)練通常不是一個(gè)凸優(yōu)化問題,它充滿了很多局部最優(yōu),因此我們通常不會(huì)采用標(biāo)準(zhǔn)的梯度下降算法,而是采用一些有更大可能跳出局部最優(yōu)的算法,常用的如SGD,而SGD本身也不穩(wěn)定,其結(jié)果也會(huì)在最優(yōu)解附近波動(dòng),且設(shè)置不同的學(xué)習(xí)效率可能會(huì)導(dǎo)致我們的網(wǎng)絡(luò)落入截然不同的局部最優(yōu)之中,對(duì)于SGD,我們希望開始訓(xùn)練時(shí)學(xué)習(xí)率大一些,以加速收斂的過程,而后期學(xué)習(xí)率低一些,以更穩(wěn)定地落入局部最優(yōu)解,因此常使用Adagrad、Adam等自適應(yīng)的優(yōu)化方法,可以在其默認(rèn)參數(shù)上取得較好的效果。
import tensorflow
as tf
from tensorflow
.examples
.tutorials
.mnist
import input_data
'''導(dǎo)入MNIST手寫數(shù)據(jù)'''
mnist
= input_data
.read_data_sets
('MNIST_data/', one_hot
=True)'''自定義神經(jīng)層添加函數(shù)'''
def add_layer(inputs
, in_size
, out_size
, activation_function
=None):Weights
= tf
.Variable
(tf
.truncated_normal
([in_size
, out_size
], mean
=0, stddev
=0.2)) biases
= tf
.Variable
(tf
.zeros
([1, out_size
]) + 0.1) Wx_plus_b
= tf
.matmul
(inputs
, Weights
) + biases
if activation_function
is None: outputs
= Wx_plus_b
else:outputs
= activation_function
(Wx_plus_b
)return outputs
'''創(chuàng)建樣本數(shù)據(jù)'''
x
= tf
.placeholder
(tf
.float32
, [None, 784])
y
= tf
.placeholder
(tf
.float32
, [None, 10])
keep_prob
= tf
.placeholder
(tf
.float32
)'''構(gòu)建MLP'''
l1
= add_layer
(x
, 784, 300, activation_function
=tf
.nn
.relu
)
l1_dropout
= tf
.nn
.dropout
(l1
, keep_prob
)
prediction
= add_layer
(l1_dropout
, 300, 10, activation_function
=tf
.nn
.softmax
) '''損失函數(shù)'''
loss
= tf
.reduce_mean
(tf
.reduce_sum
((prediction
- y
) ** 2, reduction_indices
=[1]))'''優(yōu)化器'''
train_step
= tf
.train
.AdagradOptimizer
(0.3).minimize
(loss
)'''創(chuàng)建會(huì)話并激活部件'''
init
= tf
.global_variables_initializer
()
sess
= tf
.Session
()
sess
.run
(init
)'''訓(xùn)練'''
for i
in range(10001):x_batch
, y_batch
= mnist
.train
.next_batch
(200) sess
.run
(train_step
, feed_dict
={x
: x_batch
, y
: y_batch
, keep_prob
: 0.75})if i
% 200 == 0:print('第', i
, '輪迭代后:')whether_correct
= tf
.equal
(tf
.argmax
(y
, 1), tf
.argmax
(prediction
, 1))accuracy
= tf
.reduce_mean
(tf
.cast
(whether_correct
, tf
.float32
))print(sess
.run
(accuracy
, feed_dict
={x
: mnist
.test
.images
, y
: mnist
.test
.labels
, keep_prob
: 1.0}))
參考:數(shù)據(jù)科學(xué)學(xué)習(xí)手札36–tensorflow實(shí)現(xiàn)MLP
總結(jié)
以上是生活随笔為你收集整理的Tensorflow实现MLP的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。