TensorFlow-線程迴歸模型

實驗目的:

方程:y = Wx + bapp

經過大量的(x, y)座標值,模型能夠計算出接近W和b的值dom

實驗步驟:

第一步:生成線程迴歸方程模型所須要的數據優化

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# 隨機生成1000個點,圍繞在y=0.1x+0.3的直線周圍
num_points = 1000
vectors_set = []
for i in range(num_points):
    x1 = np.random.normal(0.0, 0.50)  # 正態分佈 0.0:均值,0.50:標準差
    y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
    vectors_set.append([x1, y1])
    
# 生成一些樣本數據
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
# print(x_data) 會有1000個數據
plt.scatter(x_data, y_data, c
='r') plt.show()

 

第二步:創建線性迴歸模型,將生成的數據(x_data,y_data)餵給模型,併產生結果。spa

# 生成1維的W矩陣, 取值是[-1,1]之間的隨機數
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
# 生成1維的b矩陣,初始值是0
b = tf.Variable(tf.zeros([1]), name='b')
# 記過計算得出預估值y
y = W * x_data + b

# 以預估值y和實際值y_data之間的均方偏差做爲損失
loss = tf.reduce_mean(tf.square(y - y_data, name='loss'))
# 採用梯度降低法來優化參數
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 訓練的過程就是最小化這個偏差值
train = optimizer.minimize(loss, name='train')

sess = tf.Session()
# 初始化sess
init = tf.global_variables_initializer()
sess.run(init)

# 初始化的W和b是多少
print("W = ", sess.run(W), "b = ", sess.run(b), "loss = ", sess.run(loss))
# 執行20次訓練
for step in range(20):
    sess.run(train)
    # 輸出尋來你好的W和b
    print("W = ", sess.run(W), "b = ", sess.run(b), "loss = ", sess.run(loss))

結果:線程

W =  [0.6756458] b =  [0.] loss =  0.16456214
W =  [0.53388023] b =  [0.2748111] loss =  0.050819542
W =  [0.4182969] b =  [0.28113642] loss =  0.027618099
W =  [0.33377516] b =  [0.28629357] loss =  0.015202045
W =  [0.2719439] b =  [0.2900648] loss =  0.0085575525
W =  [0.22671175] b =  [0.29282364] loss =  0.00500173
W =  [0.19362253] b =  [0.29484183] loss =  0.0030988192
W =  [0.16941638] b =  [0.2963182] loss =  0.0020804694
W =  [0.15170857] b =  [0.29739827] loss =  0.0015354961
W =  [0.13875458] b =  [0.29818836] loss =  0.0012438523
W =  [0.12927818] b =  [0.29876634] loss =  0.0010877779
W =  [0.12234581] b =  [0.29918915] loss =  0.0010042539
W =  [0.11727448] b =  [0.29949847] loss =  0.0009595558
W =  [0.11356459] b =  [0.29972476] loss =  0.0009356354
W =  [0.11085065] b =  [0.29989028] loss =  0.00092283427
W =  [0.10886529] b =  [0.30001137] loss =  0.0009159839
W =  [0.10741292] b =  [0.30009997] loss =  0.0009123176
W =  [0.10635044] b =  [0.30016476] loss =  0.00091035594
W =  [0.1055732] b =  [0.30021217] loss =  0.0009093059
W =  [0.10500462] b =  [0.30024683] loss =  0.00090874406
W =  [0.10458867] b =  [0.30027223] loss =  0.00090844336

咱們能夠看到W不斷趨近於0.1,b不斷趨近於0.3,loss不斷變小。code

說明模型是可用的。orm

相關文章
相關標籤/搜索