1. 程式人生 > >tensorflow學習筆記(北京大學) tf4_1.py 完全解析

tensorflow學習筆記(北京大學) tf4_1.py 完全解析

#coding:utf-8
#tensorflow學習筆記(北京大學) tf4_1.py 完全解析 
#QQ群:476842922(歡迎加群討論學習)
#預測多或預測少的影響一樣
#0匯入模組,生成資料集
import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
SEED = 23455

rdm = np.random.RandomState(SEED)#基於seed產生隨機數
X = rdm.rand(32,2)#隨機數返回300行2列的矩陣,表示300組座標點
Y_ = [[x1+x2+(rdm.rand()/10.0-0.05)] for
(x1, x2) in X]#判斷如果兩個座標的平方和小於2,給Y賦值1,其餘賦值0 #1定義神經網路的輸入、引數和輸出,定義前向傳播過程。 x = tf.placeholder(tf.float32, shape=(None, 2))#佔位 y_ = tf.placeholder(tf.float32, shape=(None, 1))#佔位 w1= tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1))#正態分佈 y = tf.matmul(x, w1)#點積 #2定義損失函式及反向傳播方法。 #定義損失函式為MSE,反向傳播方法為梯度下降。
loss_mse = tf.reduce_mean(tf.square(y_ - y)) train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss_mse) #3生成會話,訓練STEPS輪 with tf.Session() as sess: init_op = tf.global_variables_initializer()#初始化 sess.run(init_op)#初始化 STEPS = 20000#20000輪 for i in range(STEPS): start = (i*
BATCH_SIZE) % 32 end = (i*BATCH_SIZE) % 32 + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_: Y_[start:end]}) if i % 500 == 0: print ("After %d training steps, w1 is: " % (i)) print (sess.run(w1), "\n") print ("Final w1 is: \n", sess.run(w1)) #在本程式碼#2中嘗試其他反向傳播方法,看對收斂速度的影響,把體會寫到筆記中