2. 用PyTorch tensors来创建前向神经网络,计算损失,以及反向传播。

这篇博客介绍了如何使用PyTorch进行神经网络的前向传播、损失计算和反向传播。通过使用PyTorch的tensors,autograd自动求导功能以及nn库构建网络,简化了模型训练过程。还提到了optim包的应用和自定义nn Modules的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用numpy来计算前向神经网络,loss,和反向传播。
import torch
import numpy as np

N,D_in, H, D_out = 64,1000,100,10
x = np.random.randn(N, D_in)
y = np.random.randn(N, D_out)

w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H, D_out)

leaning_rate = 1e-6
for t in range(500):
    # forward pass
    h = x.dot(w1) # N*D_in   点乘 D_in*H  -->  N*H
    h_relu = np.maximum(h, 0)    #N*H
    y_pred = h_relu.dot(w2)  # N * D_out

    # loss
    loss = np.square(y_pred - y).sum()
    print(t, loss)

    # backword pass
    # compute the gradient
    grad_y_pred = 2.0*(y_pred - y) #loss的导数  # loss = (y_pred - y) ** 2
    grad_w2 = h_relu.T.dot(grad_y_pred)
    grad_h_relu = grad_y_pred.dot(w2.T)
    grad_h = grad_h_relu.copy()
    grad_h[h<0] = 0
    grad_w1 = x.T.dot(grad_h)

    # update weights of w1 and w2
    w1 -= leaning_rate*grad_w1
    w2 -= leaning_rate*grad_w2

用PyTorch tensors来创建前向神经网络,计算损失,以及反向传播。

import torch
import numpy as np

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

N, D_in, H, D_out = 64, 1000, 100, 10

x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out,device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.mm(w1)
    h_relu = h.clamp(min=0)
    y_pred = h_relu.mm(w2)

    # Compute and print loss
    loss = (y_pred - y).pow(2).sum().item
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值