# 輸入一個 x 會計算出 y 值 y 是預測值,若是與 真的 y 值(y_data)接近就成功了 import tensorflow as tf import numpy as np # py 的畫圖工具 import matplotlib.pyplot as plt # 用 numpy 生成個 200 個屬性點 從 -0.5 到 0.5 間平均生成 200 個點 #x_data = np.linspace(-0.5, 0.5, 200) # 這只是生成了一維的數組 # 用下邊這句能夠生成二維數組 x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis] # 生成隨機值,和 x_data 的形狀是同樣的 ( 噪點 ) noise = np.random.normal(0, 0.02, x_data.shape) # x_data 的平方+隨機數 y_data = np.square( x_data ) + noise # 定義二個佔位符 x = tf.placeholder( tf.float32, [None, 1] ) # [None, 1] 行不定,列只有一列 y = tf.placeholder( tf.float32, [None, 1] ) # 構建神經網絡中間層 一行十列 Weights_L1 = tf.Variable( tf.random_normal([1, 10])) biases_L1 = tf.Variable( tf.zeros([1, 10]) ) # 求出信號的總和 矩陣相乘, Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1 # 中間層的輸出 L1 = tf.nn.tanh( Wx_plus_b_L1 ) # 輸出層 十行一列 Weights_L2 = tf.Variable( tf.random.normal([10, 1])) biases_L2 = tf.Variable( tf.zeros([1, 1]) ) # 求出信號的總和 矩陣相乘, Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2 # 得出最後的預測結果 pred = tf.nn.tanh( Wx_plus_b_L2 ) # 二次代價函數 loss = tf.reduce_mean( tf.square(y - pred) ) # 梯度降低法的優化器 最小化代價函數 train = tf.train.GradientDescentOptimizer( 0.2 ).minimize( loss ) with tf.Session() as sess: # 初始化變量 sess.run( tf.global_variables_initializer() ) # 訓練 2000 次 for _ in range( 2000 ): sess.run( train, feed_dict={x:x_data, y:y_data} ) # 獲得預測值 value = sess.run( pred, feed_dict={x:x_data} ) # 用畫圖形式展示 plt.figure() plt.scatter(x_data, y_data) plt.plot(x_data, value, 'r-', lw=5) plt.show()