import torch
from torch import nn
import torch.nn.functional as F
class BasicConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,padding=0):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_channels,out_channels,kernel_size,padding=padding)
self.bn = nn.BatchNorm2d(out_channels,eps=0.001)
def _slow_forward(self,x):
x = self.conv(x)
y = self.bn(x)
return F.relu(y,inplace=True)
class Inception_v2(nn.Module):
def __init__(self):
super(Inception_v2, self).__init__()
#对应1 x 1卷积分支
self.branch1 = BasicConv2d(192,96,1,0)
#对应1 x 1卷积与3 x 3卷积分支
self.branch2 = nn.Sequential(
BasicConv2d(192, 48, 1, 0),
BasicConv2d(48 , 64, 3, 1)
)
#对应1 x 1卷积、3 x 3卷积与3 x 3卷积分支
self.branch3 = nn.Sequential(
BasicConv2d(192,64,1,0),
BasicConv2d(64, 96, 3, 1),
BasicConv2d(96, 96, 3, 1)
)
#对应3 x 3 POOLING
self.branch4 = nn.Sequential(
nn.AvgPool2d(3,stride=1,padding=1,count_include_pad=False),
BasicConv2d(192,64,1,0)
)
#前向过程,将4个分支进行torch.cat()拼接起来
def forward(self,x):
x1 = self.branch1(x)
x2 = self.branch2(x)
x3 = self.branch3(x)
x4 = self.branch4(x)
out = torch.cat((x1,x2,x3,x4),1)
return out
#测试
net_inceptionv2 = Inception_v2()
# print(net_inceptionv2)
input = torch.randn([1,192,32,32])
print(input.shape)
output = net_inceptionv2(input)
print(output.shape)
一直出现下面的错误:
问题:
在继承父类,需要重写父类的forward()函数,然而我写成了_slow_forward()函数:
def forward(self,x):
x = self.conv(x)
x = self.bn(x)
return F.relu(x,inplace=True)
总结:
一般出现 raise NotImplementedError 的错误的时候,都是子类没有重写父类中的成员成员函数,然后子类对象调用该函数时,会提示这个错误!
(俺就是记录一下,学习中…/狗头.jpg)