如何解决获得层的重量
我一直在使用PyTorch处理MNIST数据集,但是在访问代码中产生的权重和偏差时遇到了麻烦。
这是我的代码
from torch import nn
import torch.nn.functional as F
class Neural(nn.Module):
def __init__(self):
super().__init__()
self.hidden1 = nn.Linear(784,128)
self.hidden2 = nn.Linear(128,64)
self.output = nn.Linear(64,10)
def forward(self,x):
x=F.relu(self.hidden1(x))
x=F.relu(self.hidden2(x))
x=F.softmax(self.output(x))
return x
model= Neural()
并在使用时访问体重
print(model.fc1.weight)
print(model.fc1.bias)
这是我得到的错误
AttributeError Traceback (most recent call last)
<ipython-input-58-e92de631c798> in <module>()
----> 1 model.fc1.weight
2 print(model.fc1.bias)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __getattr__(self,name)
530 return modules[name]
531 raise AttributeError("'{}' object has no attribute '{}'".format(
--> 532 type(self).__name__,name))
533
534 def __setattr__(self,name,value):
AttributeError: 'Neural' object has no attribute 'fc1'
解决方法
您应该通过其名称访问图层的权重,这样就可以了
print (model.hidden1.weight,model.hidden1.bias)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。