# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
__author__ = 'BrownWong'
# 产生数据
number_of_points = 200
x_point = []
y_point = []
a = 0.22
b = 0.78
for i in range(number_of_points):
x = np.random.normal(0.0, 0.5)
y = a * x + b + np.random.normal(0.0, 0.1)
x_point.append([x])
y_point.append([y])
# 拟合模型
A = tf.Variable(tf.random_uniform([1], -1., 1.))
B = tf.Variable(tf.zeros([1]))
y = A * x_point + B
cost_func = tf.reduce_mean(tf.square(y - y_point))
optimizer = tf.train.GradientDescentOptimizer(.5)
train = optimizer.minimize(cost_func)
init_op = tf.initialize_all_variables()
with tf.Session() as session:
session.run(init_op)
for step in xrange(100):
session.run(train)
if step % 5 == 0:
print('Current, Step: %s, A=%s, B=%s' % (step, session.run(A), session.run(B)))
plt.plot(x_point, y_point, 'o', label='step = {}'.format(step))
plt.plot(x_point, session.run(A) * x_point + session.run(B))
plt.legend()
plt.show()
tensorflow线性回归
最新推荐文章于 2018-01-30 21:14:25 发布