TensorFlow 實現簡單線性回歸

2021-10-08 12:01:14 字數 2235 閱讀 4367

import tensorflow as tf

import numpy as np

import random

#create data

x_data = np.random.rand(

100)

.astype(np.float32)

# 使用numpy生成100個隨機點

noise = np.random.normal(loc=

0, scale=

0.005

, size=x_data.shape)

# 生成標準正態分佈

y_data = x_data*

0.1+

0.3+ noise

# 搭建模型

weights = tf.variable(tf.random_uniform([1

],-1.0

,1.0))

#[1]表示張量形狀

bias = tf.variable(tf.zeros([1

]))# [1]表示張量形狀

y = weights*x_data + bias

# 計算誤差

loss = tf.reduce_mean(tf.square(y-y_data)

)# 均方誤差mse

# 傳播誤差

# 反向傳播由optimizer完成,可以用梯度下降進行引數更新

optimizer = tf.train.gradientdescentoptimizer(

0.5)

train = optimizer.minimize(loss)

# 訓練

# 首先初始化所有變數

init = tf.global_variables_initializer(

)# 建立會話session

sess = tf.session(

)sess.run(init)

# 用session來執行init初始化步驟

for step in

range

(201):

# 201是迭代次數

sess.run(train)

# 用session來run每次training的資料

if step%

20==0:

# 每20步列印一下訓練資訊

print

(step, sess.run(weights)

, sess.run(bias)

)

0 [0.5786313] [0.04093613]

20 [0.22345346] [0.23119761]

40 [0.13341352] [0.28108537]

60 [0.11040851] [0.2938316]

80 [0.10453079] [0.2970882]

100 [0.10302906] [0.2979203]

120 [0.10264537] [0.29813287]

140 [0.1025473] [0.2981872]

160 [0.10252227] [0.29820108]

180 [0.10251586] [0.29820463]

200 [0.10251423] [0.29820552]

import matplotlib.pyplot as plt

# 把隨機在座標軸中列印出來

plt.xlabel(

"x")

plt.ylabel(

"y")

plt.title(

"linear regression"

)plt.scatter(x_data, y_data)

# 用最終訓練的模型輸出結果,在圖上顯示

plt.plot(x_data, sess.run(weights)

* x_data + sess.run(bias)

,'r--'

, label=

'擬合資料'

用TensorFlow實現簡單線性回歸

使用tensorflow 構造乙個神經元,簡單的線性回歸網路。問題 現有一組有雜訊的樣本資料,共2000個,每乙個樣本 x 有 3 個特徵,對應乙個標籤 y 值。從資料樣本中學習 y w x b y w times x b y w x b 中的引數 首先我們來生成樣本資料,w real 和 b re...

TensorFlow實現乙個簡單線性回歸的例子

1 author wsx 2import tensorflow as tf 3import numpy as np 4import matplotlib.pyplot as plt 56 x data np.linspace 0.5,0.5,200 np.newaxis 0.5 0.5 之間產生20...

基於tensorflow的簡單線性回歸模型

usr local bin python3 ljj 1 linear regression model import tensorflow as tf import matplotlib.pyplot as plt 訓練樣本,隨手寫的 x 11,14,22,29,32,40,44,55,59,60,...