【pytorch】拟合sin函数

我们使用指数函数
y = a + b x + c x 3 + d x 5 y=a+bx+cx^3+dx^5 y=a+bx+cx3+dx5
来拟合三角函数sin函数
y = s i n ( x ) y=sin(x) y=sin(x)

由泰勒公式也可知,sin可以展开为指数形式的多项式
在这里插入图片描述

代码如下:

dtype = torch.float
device = torch.device("cpu")

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

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

learning_rate = 1e-6
for t in range(4000):
    y_pred = a * x + b * (x ** 3) + c * (x ** 5) + d * (x ** 7)

    loss = (y_pred - y).pow(2).mean()
    if t % 100 == 99:
        print(t, loss.item())

    loss.backward()

    with torch.no_grad():
        a -= learning_rate * a.grad
        b -= learning_rate * b.grad
        c -= learning_rate * c.grad
        d -= learning_rate * d.grad

        a.grad = None
        b.grad = None
        c.grad = None
        d.grad = None

print(f'Result: y = {a.item()} x + {b.item()} x^3 + {c.item()} x^5 + {d.item()} x^7')
print('1/1! = {}'.format(1./1))
print('1/3! = {}'.format(1./(1*2*3)))
print('1/5! = {}'.format(1./(1*2*3*4*5)))
print('1/7! = {}'.format(1./(1*2*3*4*5*6*7)))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值