學會使用tensorflow搭建神經網路
阿新 • • 發佈:2018-11-07
搭建神經網路基本流程
定義新增神經層的函式
1.訓練的資料
2.定義節點準備接收資料
3.定義神經層:隱藏層和預測層
4.定義 loss 表示式
5.選擇 optimizer 使 loss 達到最小
然後對所有變數進行初始化,通過 sess.run optimizer,迭代 1000 次進行學習:
import tensorflow as tf import numpy as np # 新增層 def add_layer(inputs, in_size, out_size, activation_function=None): # add one more layer and return the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) 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 # 1.訓練的資料 # Make up some real data x_data = np.linspace(-1,1,300)[:, np.newaxis] noise = np.random.normal(0, 0.05, x_data.shape) y_data = np.square(x_data) - 0.5 + noise # 2.定義節點準備接收資料 # define placeholder for inputs to network xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1]) # 3.定義神經層:隱藏層和預測層 # add hidden layer 輸入值是 xs,在隱藏層有 10 個神經元 l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) # add output layer 輸入值是隱藏層 l1,在預測層輸出 1 個結果 prediction = add_layer(l1, 10, 1, activation_function=None) # 4.定義 loss 表示式 # the error between prediciton and real data loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1])) # 5.選擇 optimizer 使 loss 達到最小 # 這一行定義了用什麼方式去減少 loss,學習率是 0.1 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # important step 對所有變數進行初始化 init = tf.initialize_all_variables() sess = tf.Session() # 上面定義的都沒有運算,直到 sess.run 才會開始運算 sess.run(init) # 迭代 1000 次學習,sess.run optimizer for i in range(1000): # training train_step 和 loss 都是由 placeholder 定義的運算,所以這裡要用 feed 傳入引數 sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) if i % 50 == 0: # to see the step improvement print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))