我不说多余的话,直接看看代码吧~
import torch.nn as nn
import torch.nn.functional as F
import torch.nn as nn
classalexnet_1(nn.module ) :
def_init_(self,num_classes=n ) :
super(Alexnet,self ).__init__ () )
self.features=nn.Sequential (
nn.conv 2d (3,64,kernel_size=3,stride=2,padding=1),
nn.BatchNorm2d(64 )、
nn.Relu(inplace=true )、
)
defforward(self,x ) :
x=self.features(x )
classalexnet_2(nn.module ) :
def_init_(self,num_classes=n ) :
super(Alexnet,self ).__init__ () )
self.features=nn.Sequential (
nn.conv 2d (3,64,kernel_size=3,stride=2,padding=1),
nn.BatchNorm2d(64 )、
)
defforward(self,x ) :
x=self.features(x )
x=f.Relu(x ) )
在上面的网络中,AlexNet_1和AlexNet_2的实现结果一致,但可以看到,有两种实现方法可以将ReLU层添加到网络中: nn.ReLU和F.ReLU。
其中,nn.ReLU作为分层结构,必须添加到nn.Module容器中才能使用,但F.ReLU作为函数调用,作为函数调用显得更方便、更简洁。 具体使用哪种方式,取决于编程风格。
在PyTorch中,有与nn.X对应的函数版本F.X,但并不是所有的F.X都可以在forward和其他代码段中使用。 这是因为,如果在网络模型培训完成时保存模型,则不会保存forward f.x函数的参数。
这意味着在forward中使用的F.X函数通常没有状态参数。 例如,F.ReLU、F.avg_pool2d等没有参数,可以用在任何代码片段中。
补充知识: pytorch的小知识点――in-place operation
一.什么是在位
虽然在pytorch的许多函数中经常看到in-place选项,但我一直知道具体是什么意思。 这次特别学习一下吧。 in-place operation是指在pytorch中改变一个tensor的值时,不经过复制操作,直接在原内存上改变该值。 可以把这称为当场的操作员。
在pytorch中,经常会加上表示当场放置操作的后缀“_”。 例如, add_ ()或. scatter ()。 in_place操作可以简单理解为python的'='、'-='等操作。
举一个例子,以下是通常的加法操作,执行结束后x的值不变
导入种子
x=Torch.rand(2) )。
x
out [3] : tensor ([ 0.3486,0.2924 ] # )
y=Torch.rand(2) )。
y
out [5] : tensor ([ 0.6301,0.0101 ] #
x.add(y ) )。
out [6] : tensor ([ 0.9788,0.3026 ] #
x
out [7] : tensor ([ 0.3486,0.2924 ] # )
y
out [8] : tensor ([ 0.6301,0.0101 ] # )
可以看出,在正常操作后,原始操作数的值不会改变。
让我们来看看in_place操作
导入种子
x=Torch.rand(2) )。
x
out [3] : tensor ([ 0.3486,0.2924 ] # )
y=Torch.rand(2) )。
y
out [5] : tensor ([ 0.6301,0.0101 ] #
x.add_(y )
out [9] : tensor ([ 0.9788,0.3026 ] #
x
out [ 10 ] : tensor ([ 0.9788,0.3026 ] #
y
out [ 11 ] : tensor ([ 0.6301,0.0101 ] # )
通过比较可以看出,in_place操作后,原始操作数等于表达式的计算结果。 即,将计算结果分配给了原始操作数。
二.不能使用合放的情况
requires_grad=True中的“inplace operation”不适用于叶子喜欢的cookie
“inplace operation”不可用于确定坡度阶段所需的高兴cookie
介绍以上PyTorch的nn.ReLU和F.ReLU的区别,编辑分享给大家的内容就是全部。 希望能作为参考。 云海天教程也请多关照。
原文链接: https://blog.csdn.net/u 011501388/article/details/86602275