问题记录:使用nn.Softmax报错,F.softmax却不报错

搭建网络时,最后一步使用softmax归一化,原代码如下:

x=self.conv2d6(x)  
x= self.Dropout(x)
x=self.flatten(x)
x=self.linear1(x)
x=self.linear2(x)
y=nn.Softmax(x)

报错信息如下:

AttributeError: 'Softmax' object has no attribute 'shape'

将最后的nn.Softmax(x)换成y=F.softmax(x,dim=1),(其中import torch.nn.functional as F)

排错发现,因为直接使用nn.Softmax(x)的话返回值为<class 'torch.nn.modules.activation.Softmax'>类型,而F.softmax(x,dim=1)返回值为Tensor,因此,在使用nn.Softmax的时候,先定义一个函数,例如layer=nn.Softmax(),然后y=layer(x),得到的y类型为Tensor,错误消失~~~

猜你喜欢

转载自blog.csdn.net/weixin_50594261/article/details/128164593