1. 程式人生 > >神經網路總結(tensorflow)

神經網路總結(tensorflow)

import tensorflow as tf      
from tensorflow.examples.tutorials.mnist import input_data #匯入mnist資料集
minst=input_data.read_data_sets('MNIST_data',one_hot=True)

def add_layer(inputs,in_size,out_size,activation_function=None):#新增一層隱藏層
#with tf.name_scope('layer'):
# with tf.name_scope('Weights'):
Weights=tf.Variable(tf.random_normal([in_size,out_size]))#定義變數weights
#with tf.name_scope('biase'):
biases=tf.Variable(tf.zeros([1,out_size])+0.1,name='b')#定義變數biases
Wx_plus_b=tf.matmul(inputs,Weights)+biases#運算WX+b
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return outputs
xs=tf.placeholder(tf.float32,[None,784])#placeholder在後面輸入
ys=tf.placeholder(tf.float32,[None,10])

prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)#呼叫函式,激勵函式是softmax

cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))#交叉熵運算,相當於loss 下面還會有介紹
train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)#定義優化器來優化loss


sess=tf.Session()#例項化Session
sess.run(tf.initialize_all_variables())#只有進行這一步所有的變數才會起作用

def compute_accuracy(v_xs,v_ys):#計算準確率的函式
global prediction
y_pre=sess.run(prediction,feed_dict={xs:v_xs})#對應上邊的palceholder
correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))#比較你預測的y和真實y那個1所在的位置。是一個布林型量
print(sess.run(correct_prediction))
float=tf.cast(correct_prediction,tf.float32)#轉化為float32型別
print(sess.run(float))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#轉化為float32格式然後求其正確率 tf.cast轉換格式
result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
return result



for i in range(1000):
batch_xs,batch_ys=minst.train.next_batch(100)
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
if i %100==0:
print(compute_accuracy(
minst.test.images,minst.test.labels
))


tensorflow定義一個變數的函式Varible
tf.Variable.init(initial_value, trainable=True, collections=None, validate_shape=True, name=None)

 Weights=tf.Variable(tf.random_normal([in_size,out_size]))   tf.random_normal正態分佈
e.g. weights=tf.Varible(tf.random_normal([2,3],stddev=2,mean=0,seed=1)) 服從正態分佈的 2×3的矩陣 標準差為2 均值為0 ,隨機種子為1
tf.zeros全0陣列 tf.ones全1陣列 tf.constant 直接給值 tf.truncated_normal()去掉過大偏離點的正態分佈
tf.random_uniform()平均分佈

tf.placeholder(dtype, shape=None, name=None)

此函式可以理解為形參,用於定義過程,在執行的時候再賦具體的值

 啟用函式:

交叉熵:

學習率

 

 

 

滑動平均