TensorFlow 线性回归demo

在下面的demo中,
首先创建了使用 y = 0.1 x + 0.3 + r a n d 创建测试数据集。
创建tensorflow的变量,w和b,所谓变量就是能被优化的量。
建立计算图 y = w*x_data + b
计算误差,使用误差平方和。
创建优化器,并优化误差。

在下面的例子中, y ,loss,train之类都是计算图的一个节点。并非具体的值

初始化session变量
使用session与运行优化器(下文中为train节点)
使用session的运行w和b可以得到w和b 的具体值。
绘图

这里写图片描述


import tensorflow as tf
import numpy as np
from matplotlib import  pyplot as plt
import time
import os

#create data : y = 0.1*x + 0.3 + rand
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3 + np.random.rand(100)*0.01 - 0.005

plt.ion()

plt.show();

# tensorflow struct
w = tf.Variable(tf.random_uniform([1],-1.,1.))
b = tf.Variable(tf.zeros([1]))

y = w*x_data + b
loss = tf.reduce_mean(tf.square(y - y_data))
opt = tf.train.GradientDescentOptimizer(0.5)
train = opt.minimize(loss)

init = tf.global_variables_initializer()

# start to run
sess = tf.Session()
sess.run(init)

for step in range(201):
    sess.run(train)
    if step%20 == 0:
        w_pred = sess.run(w)
        b_pred = sess.run(b)
        print(
            step,
            w_pred,
            b_pred
        )
        # draw
        x_min = np.min(x_data)
        x_max = np.max(x_data)
        y_min = x_min * w_pred + b_pred
        y_max = x_max * w_pred + b_pred
        plt.clf()
        plt.xlim(x_min,x_max)
        plt.ylim(np.min(y_data),np.max(y_data))
        plt.ylim()
        plt.plot(x_data,y_data,'o')
        plt.plot([x_min, x_max], [y_min, y_max])
        plt.text(0.2,0.4,"iter %i" % step)
        plt.show()
        plt.savefig("fig/%i.png" % step)
        plt.pause(0.5)

sess.close()

plt.waitforbuttonpress()

猜你喜欢

转载自blog.csdn.net/taiji1985/article/details/79833147
今日推荐