tensorflow2.0实现一元线性回归

参考:https://cloud.tencent.com/developer/article/1538680
看看就明白了

from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


# 学习率
learning_rate = 0.01

# 迭代次数
training_steps = 1000

display_step = 50

# 训练数据
X = np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
              7.042,10.791,5.313,7.997,5.654,9.27,3.1])
Y = np.array([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
              2.827,3.465,1.65,2.904,2.42,2.94,1.3])

#  取出数组X的长度
n_samples = X.shape[0]

# 随机初始化权重,偏置
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")


# 线性回归(Wx+b)
def linear_regression(x):
    return W * x + b


# 均方差
def mean_square(y_pred,y_true):
    return tf.reduce_sum(tf.pow(y_pred - y_true, 2)) / (2 * n_samples)


# 随机梯度下降优化器
optimizer = tf.optimizers.SGD(learning_rate)


# 优化过程
def run_optimization():
    # 将计算封装在GradientTape中以实现自动微分
    with tf.GradientTape() as g:
        pred = linear_regression(X)
        loss = mean_square(pred, Y)

    # 计算梯度
    # print("loss is ", loss)
    gradients = g.gradient(loss, [W, b])

    # 按gradients更新 W 和 b
    optimizer.apply_gradients(zip(gradients, [W, b]))


# 针对给定训练步骤数开始训练
for step in range(1, training_steps + 1):
    # 运行优化以更新W和b值
    run_optimization()

    if step % display_step == 0:
        pred = linear_regression(X)
        loss = mean_square(pred, Y)
        print("step: %i, loss: %f, W: %f, b: %f" % (step, loss, W.numpy(), b.numpy()))

# 绘制图
plt.plot(X, Y, 'ro', label='Original data')
plt.plot(X, np.array(W * X + b), label='Fitted line')
plt.legend()
plt.show()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值