import torch
import math
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU
# Create random input and output data
x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)
y = torch.sin(x)
# Randomly initialize weights
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):
# Forward pass: compute predicted y
y_pred = a + b * x + c * x ** 2 + d * x ** 3
# Compute and print loss
loss = (y_pred - y).pow(2).sum().item()
if t % 100 == 99:
print(t, loss)
# Backprop to compute gradients of a, b, c, d with respect to 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()
# Update weights using gradient descent
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')
pytorch 反向求导
原创luoganttcc 博主文章分类:pytorch ©著作权
©著作权归作者所有:来自51CTO博客作者luoganttcc的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:将进酒 html
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
pytorch查看cuda显存
pytorch,CUDA是否可用,查看显卡显存剩余容量
CUDA pytorch -
PyTorch自动求导:反向传播的一切
在之前的介绍中,我们看到了一个简单的反向传播的例子:通过使用链式规则反向传播导数,我们计算了模型和损失的复合函
pytorch 深度学习 python 数据 过拟合 -
android opencv cuda
如果懒得自己配,可以直接下载,包括使用Cmake作为工具的 OpenCV2.4x for Android(支持Java 和 NDK C++,不需要额外配置,不需要OpenCV Manager),提供一个简单的相机Preview demo (注意,只包含armeabi-v7a,如果需要其他类型可以参考教程自行配置)按照本教程配置大约需要10分钟 说明自从Android Studio 2.2稳定版发
android opencv cuda android opencv android studio OpenCV