本文主要是介绍c语言 拟合三角函数,使用Tensor拟合三角函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
numpy是一个很不错的库,但是在如今需要大量计算的深度学习中则显得力不从心。而pytorch所提供的张量Tensor能够很好的利用GPU的计算单元,在复杂的计算任务中能达到比GPU高几十甚至上千的算力。
对于Tensor,pytorch提供了许多方便的操作使其能进行科学计算。需要注意的是,使用GPU计算时要指定相应的设备。这里将使用tensor将三次多项式拟合为三角函数,话不多说,贴代码:
import torch
import math
dtype = torch.float # 类型必须是浮点数才能进行求导
device = torch.device("cuda:0") # 指定运行设备为GPU
# 为输入输出声明张量
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
for t in range(2000):
y_pred = a + b * x + c * x ** 2 + d * x ** 3
# 计算和打印loss
loss = (y_pred - y).pow(2).sum().item()
if t % 100 == 100:
print(t, loss)
# 反向传播计算abcd关于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')
output.png
用这段代码看看是不是使用了GPU:
use_gpu = torch.cuda.is_available()
use_gpu
这篇关于c语言 拟合三角函数,使用Tensor拟合三角函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!