10.用三阶多项式拟合正弦函数-PyTorch 张量语法实现用三阶多项式拟合正弦函数(手动编写实现)

# -*- coding: utf-8 -*-

# 10.用三阶多项式拟合正弦函数-PyTorch 张量语法实现用三阶多项式拟合正弦函数(手动编写实现)


import torch
import math

dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0")

# 创建真实的数据对

x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)
y = torch.sin(x)


# 参数随机初始化

a = torch.randn((), device=device, dtype=dtype)
b = torch.randn((), device=device, dtype=dtype)
c = torch.randn((), device=device, dtype=dtype)
d = torch.randn((), device=device, dtype=dtype)


# 给出学习率的值

learning_rate = 1e-6


# 正反向迭代2000次

for t in range(2000):

    # 正向传播,计算y预测值
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

    # 打印损失值
    loss = (y_pred - y).pow(2).sum().item()
    if t % 100 == 99:
        print(t, loss)

    # 反向传播
    # 计算参数的梯度
    grad_y_pred = 2.0 * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # 参数更新
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d


print(f'Result: y = { a.item()} + { b.item()} x + { c.item()} x^2 + { d.item()} x^3')

''' 99 934.4574584960938 199 658.6241455078125 299 465.2002258300781 399 329.49346923828125 499 234.23414611816406 599 167.33529663085938 699 120.33251953125 799 87.29462432861328 899 64.06321716308594 999 47.72121047973633 1099 36.22148513793945 1199 28.12641143798828 1299 22.42620086669922 1399 18.411144256591797 1499 15.582232475280762 1599 13.588532447814941 1699 12.183076858520508 1799 11.192085266113281 1899 10.493168830871582 1999 10.00014591217041 Result: y = 0.03573035076260567 + 0.8503286242485046 x + -0.006164080463349819 x^2 + -0.09241830557584763 x^3 Process finished with exit code 0 '''
    原文作者:小时不识月123
    原文地址: https://blog.csdn.net/leitouguan8655/article/details/120128402
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞