头歌-Pytorch 之torch.nn进阶

本文介绍了使用PyTorch实现的正则化、L1Loss损失函数和一范数距离计算方法,展示了如何创建并应用这些概念在神经网络中的操作。

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

第1关:正则化

import torch
import torch.nn as nn
from torch.autograd import Variable

input = Variable(torch.Tensor([[1,2,3,4],[5,6,7,8]]))

#/********** Begin *********/
# 创建一个4维的 带有学习参数的正则化量 m
m = nn.BatchNorm1d(4)
#输出weight和bias
print(m.weight)
print(m.bias)
#在 input 上应用该正则化并输出
output=m(input)
print(output)
#/********** End *********/

第2关:损失函数

import torch
import torch.nn as nn
from torch.autograd import Variable

input = Variable(torch.Tensor([1.1,2.2,2.93,3.8]))
target = Variable(torch.Tensor([1,2,3,4]))

#/********** Begin *********/

#创建名为 loss 的 L1Loss损失函数
loss = nn.L1Loss()
#对 input 和 target应用 loss 并输出
output = loss(input,target)
print(output.data)

#/********** End *********/

第3关:距离函数

import torch
import torch.nn as nn
from torch.autograd import Variable

input = Variable(torch.Tensor([[1.1,2.2],[2.93,3.8]]))
target = Variable(torch.Tensor([[1,2],[3,4]]))

#/********** Begin *********/
#创建一范数的变量pdist
pdist = nn.PairwiseDistance(p=1)
#对 input 、 target应用该范数并输出
output = pdist(input,target)
print(output)
#/********** End *********/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值