Tensorflow 搭建簡單神經網路 | Python
阿新 • • 發佈:2019-02-09
本案例為迴歸問題,採用了一層隱層,隱層和輸出層的啟用函式都為 relu,損失函式MSE。
import tensorflow as tf from numpy.random import RandomState w1 = tf.Variable(tf.truncated_normal([2,3],seed=1)) w2 = tf.Variable(tf.truncated_normal([3,1],seed=1)) x = tf.placeholder(dtype=tf.float32,shape=[None,2]) #placeholder 存放 x:features ,y_real:labels y_real = tf.placeholder(dtype=tf.float32,shape=[None,1]) a = tf.nn.relu(tf.matmul(x,w1)) #神經元的啟用函式為 relu;隱層 y_pre = tf.nn.relu(tf.matmul(a,w2)) #輸出層 sample_size = 20000 #訓練樣本數量 rds = RandomState(0) #隨機種子 X = rds.rand(sample_size,2) Y = [[int(20*x1+30*x2)]+rds.rand(1) for (x1,x2) in X] # y_label=20*x1+30*x2+noise MSE = tf.reduce_mean(abs(y_real-y_pre)) # 使用均方誤差(MSE)作為損失函式 train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(MSE) # 反向傳播演算法為:GradientDescentOptimizer,learing rate = 1e-3 step = 20000 #訓練迭代次數 batch = 500 #批大小為 500 start = 0 # 每個batch 的開始和結束指標 end = batch sess = tf.Session() sess.run(tf.global_variables_initializer()) for i in range(step): sess.run(train_step,feed_dict={x:X[start:end],y_real:Y[start:end]}) if not i%20: H = sess.run(MSE,feed_dict={x:X[start:end],y_real:Y[start:end]}) print ("MSE:",H) if H<0.4: #採用stop early 的方法防止過擬合,節省訓練時間。 break strat = end if end<sample_size else 0 end = start+batch y1 = sess.run(y_pre,feed_dict={x:X[start:end]}) y2 = Y[start:end] sess.close() #訓練結果的部分展示 for i in range(100): print(y1[i],y2[i])