使用Tensor及Antograd实现机器学习——梯度下降

数组x,基于表达式:y = 3x^2+2    加上一些噪声数据得到y

然后学习表达式y = wx^2+b  中的w与b 两个参数,这里采用梯度下降法。

"""
使用Antograd包,以及对应的Tensor,来实现反向传播来求梯度
以下是具体实现的代码
"""
import torch
import torch as t
from matplotlib import pyplot as plt

t.manual_seed(100)
dtype = t.float

# 生成x坐标数据,x为tensor,需要把x的形状转换为100*1
x = t.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
# 生成y坐标数据,y为tensor,形状为100*1,另外加上一些噪声
y = 3 * x.pow(2) + 2 + 0.2 * torch.rand(x.size())
# 画图
plt.scatter(x.numpy(), y.numpy())
plt.show()

# 初始化权重参数 w b 为需要学习的,故需requires_grad = Ture
w = t.randn(1, 1, dtype=dtype, requires_grad=True)
b = t.zeros(1, 1, dtype=dtype, requires_grad=True)

# 训练模型
lr = 0.001

for ii in range(800):
    # 前向传播
    y_pred = x.pow(2).mm(w) + b
    loss = 0.5 * (y_pred - y) ** 2
    loss = loss.sum()

    # 自动计算梯度,梯度存放在grad属性中
    loss.backward()

    # 手动更新参数,需要用torch.no_grad(),使得上下文环境中切断自动求导的计算
    with t.no_grad():
        w -= lr * w.grad
        b -= lr * w.grad
        # 梯度清零
        w.grad.zero_()
        b.grad.zero_()

# 可视化训练结果
plt.plot(x.numpy(), y_pred.detach().numpy(), 'r-', label='predict')  # predict
plt.scatter(x.numpy(), y.numpy(), color='blue', marker='o', label='ture')  # ture data
plt.xlim(-1, 1)
plt.ylim(2, 6)
plt.legend()
plt.show()

print('w=',w,'b=',b)

数据分布图:

拟合效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值