Object has no attribute ‘weight’
程序员文章站
2022-07-13 10:51:24
...
今天在进行torch模型的初始化的时候,发现报错:
Object has no attribute ‘weight’
回顾模型,发现在模型权重初始化函数,定义的带有conv
的层的初始化是这样的。
def weights_init(m):
"""init the weight for a network"""
classname=m.__class__.__name__
# print(classname)
if classname.find("conv")!=-1:
nn.init.kaiming_normal_(
m.weight.data,
a=0,
mode="fan_out"
)
elif classname.find("BatchNorm")!=-1:
m.weight.data.fill_(1)
m.bias.data.fill_(0)
然后回去看了一下模型的命名,发现定义的一个层,名字是conv_block
,那么匹配到这个名字的时候,就会把conv_block
当做卷积层进行初始化。
class conv_block(nn.Module):
"""
Convolution Block
"""
def __init__(self, input_nc, output_nc):
super(conv_block, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(input_nc, output_nc, kernel_size=3, stride=1, padding=1, bias=True),
nn.BatchNorm2d(output_nc),
nn.ReLU(inplace=True),
nn.Conv2d(output_nc, output_nc, kernel_size=3, stride=1, padding=1, bias=True),
nn.BatchNorm2d(output_nc),
nn.ReLU(inplace=True))
def forward(self, x):
x = self.conv(x)
return x
解决方法:,将conv
具*定为conv2d
,问题解决。
def weights_init(m):
"""init the weight for a network"""
classname=m.__class__.__name__
# print(classname)
if classname.find("conv2d")!=-1:
nn.init.kaiming_normal_(
m.weight.data,
a=0,
mode="fan_out"
)
elif classname.find("BatchNorm")!=-1:
m.weight.data.fill_(1)
m.bias.data.fill_(0)
类似问题参考:
AttributeError: ‘Sequential’ object has no attribute ‘weight’
推荐阅读
-
module ‘seaborn‘ has no attribute ‘scatterplot‘解决方案
-
AttributeError: module ‘community‘ has no attribute ‘best_partition‘ 问题解决方法
-
module ‘community‘ has no attribute ‘best_partition‘ [已解决]
-
【python】解决AttributeError: module ‘scipy.misc‘ has no attribute ‘toimage‘问题
-
【Tensorflow】Linux下Tensorflow报错:AttributeError: module ‘tensorflow‘ has no attribute ‘xxxx‘
-
AttributeError: 'module' object has no attribute 'main'
-
mongdb "errmsg" : "exception: 'out' has to be a string or an object"
-
AttributeError: module 'sklearn' has no attribute 'linear_model'
-
解决Keras报错AttributeError: 'NoneType' object has no attribute 'inbound_nodes'
-
解决'DataFrame' object has no attribute 'sort'