通过生成人工数据集合,基于TensorFlow实现y=3*x+2线性回归

import numpy as np
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf

# tf.enable_eager_execution()  # 在TensorFlow1.X版本中启用Eager Execution模式
tf.disable_eager_execution()  # 在TensorFlow2.X版本关闭Eager Execution
tf.__version__

1、生成x_data,值为[0, 100]之间500个等差数列数据集合作为样本特征,根据目标线性方程y=3*x+2,生成相应的标签集合y_data

x_data = np.linspace(0, 100, 500)
y_data = 3* x_data + 2 + np.random.randn(500) * 0.5

2、画出随机生成数据的散点图和想要通过学习得到的目标线性函数y=3*x+2

x_data = np.linspace(0, 100, 500)
y_data = 3 * x_data + 2 + np.random.randn(500) * 0.5

plt.figure(figsize=[10, 5])
plt.plot(x_data, y_data, 'r.', markersize=3)
plt.plot(x_data, 3 * x_data + 2, 'b-')
plt.legend(['y_data', 'y=3*x+2'])

在这里插入图片描述
3、构建回归模型

x = tf.placeholder('float', name='x')
y = tf.placeholder('float', name='y')
w = tf.Variable(1.0, name='w0')
b = tf.Variable(1.0, name='b0')
def model(x, w, b):
    return x * w + b
pred = model(x, w, b)

4、训练模型,10轮,每训练50个样本显示损失值

train_epochs = 10
learning_rate = 0.0001
display_step = 50
loss_function = tf.reduce_mean(tf.square(y - pred))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss_function)
sess = tf.Session()
init = tf.global_variables_initializer()
loss_list = []
step = 0
sess.run(init)
for epoch in range(train_epochs):
    for xs, ys in zip(x_data, y_data):
        _, loss = sess.run([optimizer, loss_function], feed_dict={x: xs, y: ys})
        loss_list.append(loss)
        step += 1
        if step % display_step == 0:
            print(f'Train Epoch: {epoch+1:02d}, Step: {step:03d}, loss={loss:.9f}')

5、通过训练出的模型预测x=5.79 时y的值,并显示根据目标方程显示的 y 值

x_test = 5.79
y_hat = sess.run(model(x_test, w, b))
y_target = 3 * x_test + 2
print(f'当x=5.79时,目标值为{y_target},模型预测值为{y_hat}')

6、通过Tensorboard显示构建的计算图

logdir = './'
tf.summary.FileWriter(logdir, tf.get_default_graph()).close()

在这里插入图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值