Pytorch 之torch.nn进阶

目录

  • 第1关:正则化
  • 第2关:损失函数
  • 第3关:距离函数

第1关:正则化

本关任务:

本关提供了一个Variable 类型的变量input,要求利用BatchNorm1d创建一个4维的 带有学习参数的正则化量 m,并输出其weight和bias。


import torch
import torch.nn as nn
from torch.autograd import Variableinput = 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关:损失函数

掌握不同损失函数的计算方法和适用条件,根据不同的数据特征和学习算法选择最适宜的损失函数进行衡量。

本关任务:

本关提供了一个Variable 类型的变量input和变量target ,要求创建一个L1Loss损失函数,对 input 和 target应用该损失函数,从而掌握利用 L1Loss计算损失的方法。

import torch
import torch.nn as nn
from torch.autograd import Variableinput = 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关:距离函数

本关任务:

本关提供了一个Variable 类型的变量input和变量target ,要求创建一个范数的变量pdist,对 input 、 target应用该范数进行距离计算,要求同学们掌握不同距离函数的计算方式及应用方式。

import torch
import torch.nn as nn
from torch.autograd import Variableinput = 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 *********/


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部