簡體   English   中英

張量流的線性回歸

[英]linear regression using tensorflow

import tensorflow as tf

M = tf.Variable([0.01],tf.float32)
b = tf.Variable([1.0],tf.float32)

#inputs and outputs

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32) # actual value of y which we already know

Yp = M * x + b # y predicted value

#loss

squareR = tf.square(Yp - y)
loss =  tf.reduce_sum(squareR)

#optimize

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(1000):
    sess.run(train,{x:[1,2,3,4,5],y:[1.9,2.4,3.7,4.9,5.1]})
print(sess.run([M,b]))

輸出

[array([ 0.88999945], dtype=float32), array([ 0.93000191], dtype=float32)]

問題:當我將x和y的值更改為

x:[100,200,300,400,500],y:[19,24,37,49,51]

那么輸出是:

[array([ nan], dtype=float32), array([ nan], dtype=float32)]

請幫助我獲得線性模型的斜率和y截距。

在訓練循環中添加一些打印語句,我們可以看到訓練過程中發生了什么:

for i in range(1000):
    _, mm, bb = sess.run([train,M,b],{x:[100,200,300,400,500],y:[19,24,37,49,51]})
    print(mm, bb)
    if np.isnan(mm):
      break
print(sess.run([M,b]))

輸出:

[ 1118.01000977] [ 4.19999981]
[-12295860.] [-33532.921875]
[  1.35243170e+11] [  3.68845632e+08]
[ -1.48755065e+15] [ -4.05696309e+12]
[  1.63616896e+19] [  4.46228634e+16]
[ -1.79963571e+23] [ -4.90810521e+20]
[  1.97943407e+27] [  5.39846559e+24]
[ -2.17719537e+31] [ -5.93781625e+28]
[  2.39471499e+35] [  6.53105210e+32]
[-inf] [-inf]
[ nan] [ nan]

該輸出意味着您的培訓有所不同。 在這種情況下,降低學習率是解決問題的可能方法之一。

將學習率降低到0.000001作品,這是經過1000次迭代的學習到的M和b:

[array([ 0.11159456], dtype=float32), array([ 1.01534212], dtype=float32)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM