## Tensorflow for Line Regression

2,556次阅读
2条评论

1 #!/usr/bin/python
2 #-*- coding:utf-8 -*-
3 ############################
4 #File Name: LR_test1.py
5 #Author: yang
6 #Mail: milkyang2008@126.com
7 #Created Time: 2017-06-27 22:51:20
8 ############################
9
10 # import tensorflow lib
11 import numpy as np
12 import random
13 #sample point
14 x_sap = np.arange(-5,5,0.5)
15 y_sap = [4*i + 3 for i in x_sap]
16 x_a = [b1*(random.randint(90,120))/100 for b1 in x_sap]
17 y_a = [b2*(random.randint(90,120))/100 for b2 in y_sap]
18 #import matplotlib.pyplot as plt
19
20 import tensorflow as tf
21 #define variable
22 w = tf.Variable(tf.zeros([1]))
23 b = tf.Variable(tf.zeros([1]))
24 x = tf.placeholder(tf.float32)
25 y_ = tf.placeholder(tf.float32)
26
27 y = w * x + b
28
29 STEPS = 30000
30 step = 0.001
31
32 #sample point
33 #x_sap = np.arange(-5,5,0.5)
34 #y_sap = [4*i + 3 for i in x]
35 #x_a = [b1*(random.randint(90,120))/100 for b1 in x]
36 #y_a = [b2*(random.randint(90,120))/100 for b2 in y]
37
38 #cost_fuction
39 lost = tf.reduce_mean(tf.square(y_-y))
40 optimizer = tf.train.GradientDescentOptimizer(step)
41 train_step = optimizer.minimize(lost)
42
43 init_op = tf.initialize_all_variables()
44
45 with tf.Session() as sess:
46     sess.run(init_op)
47
48     for i in range(STEPS):
49         feed = {x: x_a, y_: y_a}
50         sess.run(train_step, feed_dict=feed)
51         if i % 100 ==0 :
52             print("After %d interation:" %i)
53             print("W: %f" % sess.run(w))
54             print("b: %f" % sess.run(b))
55             print("lost: %f" % sess.run(lost, feed_dict=feed))
56

After 29200 interation:
W: 3.980329
b: 3.189958
lost: 2.088752
After 29300 interation:
W: 3.980333
b: 3.190148
lost: 2.088748
After 29400 interation:
W: 3.980337
b: 3.190339
lost: 2.088745
After 29500 interation:
W: 3.980341
b: 3.190530
lost: 2.088742
After 29600 interation:
W: 3.980345
b: 3.190721
lost: 2.088738
After 29700 interation:
W: 3.980348
b: 3.190897
lost: 2.088736
After 29800 interation:
W: 3.980352
b: 3.191064
lost: 2.088732
After 29900 interation:
W: 3.980355
b: 3.191231
lost: 2.088729