Tensorflow 线性回归

196 阅读1分钟
import numpy as np
data_x = np.linspace(0, 10, 100)
data_y = data_x *3 + 7 + np.random.normal(0, 1, 100)
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(data_x, data_y)
<matplotlib.collections.PathCollection at 0x10dbfe908>

import tensorflow as tf
/anaconda3/envs/py35/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5
  return f(*args, **kwds)
/anaconda3/envs/py35/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
w = tf.Variable(1., name='quanzhong')
b = tf.Variable(0., name='pianzhi')
x = tf.placeholder(tf.float32, shape=None)
y = tf.placeholder(tf.float32, shape=[None])
pred = tf.multiply(x, w) + b
loss = tf.reduce_sum(tf.squared_difference(pred, y))
learn_rate = 0.0001
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10000):
    sess.run(train_step, feed_dict={x:data_x, y:data_y})
    if i%1000 == 0:
        print(sess.run([loss, w ,b], feed_dict={x:data_x, y:data_y}))
    
[4275.1426, 3.0419059, 0.34032884]
[92.10727, 3.007915, 6.965689]
[92.055786, 3.0011888, 7.010422]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]