3-1非線性迴歸(TensorFlow例程)
阿新 • • 發佈:2018-12-19
非線性迴歸的TensorFlow例程
本例程程式設計思想:
- 產生隨機數x_data,構造y = x^2+噪聲的分佈,相當於已知輸入x_data和輸出y_data。
- 利用輸入x_data和輸出y_data,利用梯度下降法,使樣本值和預測值之間的損失函式(loss)最小,訓練出相應的模型
- 得到訓練後的模型,然後再根據輸入值x_data,得到預測後的輸出值
- 進行繪圖
本程式使用的啟用函式為y = tanh(x)
# 非線性迴歸的例程 import tensorflow as tf import numpy as np import matplotlib.pylab as plt # 使用numpy生成200個隨機點 # linspace生成在-0.5到0.5均勻分佈的200個點 # [:,np.newaxis]是把一維資料變換成二維資料 x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis] # 生成噪聲干擾點noise noise = np.random.normal(0, 0.02, x_data.shape) y_data = np.square(x_data) + noise # 模擬y =x**2 # 定義兩個placeholder # placeholder維數大小根據輸入資料大小確定 x = tf.placeholder(tf.float32, [None, 1]) y = tf.placeholder(tf.float32, [None, 1]) # 輸入層1個神經元 # 定義神經網路中間層 # 中間層使用10個神經元 # 輸出層1個神經元 Weight_L1 = tf.Variable(tf.random_normal([1, 10])) biases_L1 = tf.Variable(tf.zeros([1, 10])) Wx_plus_b_L1 = tf.matmul(x, Weight_L1) + biases_L1 # 啟用函式tanh L1 = tf.nn.tanh(Wx_plus_b_L1) # 定義神經網路輸出層 Weight_L2 = tf.Variable(tf.random_normal([10, 1])) biases_L2 = tf.Variable(tf.zeros([1, 1])) Wx_plus_b_L2 = tf.matmul(L1, Weight_L2) + biases_L2 prediction = tf.nn.tanh(Wx_plus_b_L2) # 二次代價函式 loss = tf.reduce_mean(tf.square(y - prediction)) # 使用梯度下降法訓練 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) with tf.Session() as sess: init = tf.initialize_all_variables() sess.run(init) for step in range(2000): sess.run(train_step, feed_dict={x: x_data, y: y_data}) # 傳入樣本值 # 獲得預測值 prediction_value = sess.run(prediction, feed_dict={x: x_data}) # 畫圖 plt.figure() plt.scatter(x_data, y_data) plt.plot(x_data, prediction_value, 'r-', lw=5) plt.show()
執行結果: 如圖1所示:
藍色點表示已知資料點 紅色線表示預測值