PyTorch学习笔记(二)——torch.nn解析

本文通过逐步添加PyTorch的模块,如torch.nn和torch.optim,展示了如何从手动搭建神经网络过渡到使用高级API的过程。通过重构代码,提高了模型训练的效率和代码的简洁性。

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

PyTorch提供了方便漂亮的类和模块,来帮助我们创建和训练神经网络,例如 torch.nn, torch.optim 等。
为了更好地理解这些模块的功能和原理,我们在手动搭建的神经网络上,逐步添加这些模块,以显示每部分模块的功能,以及每部分是如何让代码更加灵活简洁的。

1、手动搭建神经网络

使用MNIST数据集,该数据集共有50000个图片,每一图片大小为2828,储存在长度为2828=784的扁平行。

#定义权重和偏执值,需要requires_grad=True,以便自动计算梯度,完成反馈
weights = torch.randn(784, 10,requires_grad=True)
bias = torch.zeros(10, requires_grad=True)

#定义激活函数
def log_softmax(x):
    return x - x.exp().sum(-1).log().unsqueeze(-1)
    
#定义神经网络运算过程,其中@表示点乘
def model(xb):
    return log_softmax(xb @ weights + bias)

#定义代价函数
def nll(input, target):
    return -input[range(target.shape[0]), target].mean()
loss_func = nll

#验证结果的准确性
def accuracy(out, yb):
    preds = torch.argmax(out, dim=1)
    return (preds == yb).float().mean()

#获取一批数据,验证预测的结果:
bs = 64                  # batch size
xb = x_train[0:bs]       # a mini-batch from x
yb = y_train[0:bs]
preds = model(xb)        # predictions
print(preds[0], preds.shape)
print(loss_func(preds, yb))
print(accuracy(preds, yb))
输出:
tensor([-1.7022, -3.0342, -2.4138, -2.6452, -2.7764, -2.0892, -
torch.nn.LeakyReLU是PyTorch中的一个激活函数,用于在神经网络中引入非线性。它与ReLU函数类似,但在输入为负数时具有一个小的斜率,以避免死亡神经元的问题。LeakyReLU函数的参数包括negative_slope和inplace。negative_slope控制负斜率的角度,默认值为0.01。inplace参数用于选择是否就地执行操作,默认值为False。 下面是一个使用LeakyReLU函数的例子: ```python import torch.nn as nn import torch LeakyReLU = nn.LeakyReLU(negative_slope=0.1) x = torch.randn(2) output = LeakyReLU(x) print(x) print(output) ``` 在这个例子中,我们先创建了一个LeakyReLU函数,然后将输入x应用于该函数,输出结果为output。可以看到,LeakyReLU函数会将负数部分乘以一个小的斜率,而正数部分则保持不变。 更多关于torch.nn.LeakyReLU的详细信息可以在PyTorch的官方文档中找到。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [PyTorch学习笔记nn.LeakyReLU——LeakyReLU激活函数](https://blog.csdn.net/qq_50001789/article/details/128973901)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [【Pytorchtorch.nn.LeakyReLU()](https://blog.csdn.net/weixin_44225182/article/details/126655246)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值