python - 如何修复“torch.nn.Linear”的权重?
问题描述
我想知道为什么参数列表中有两个张量
nn.linear
??我尝试设置参数,但没有成功。我该如何解决?
XX=torch.from_numpy(X)
YY=torch.from_numpy(Y)
Ytt=torch.from_numpy(Yt)
XX=XX.view(100,1)
YY=YY.view(100,1)
Ytt=Ytt.view(100,1)
class model(torch.nn.Module):
def __init__(self):
super(model,self).__init__()
self.linear1 = torch.nn.Linear(1,2).double()
self.linear2 = torch.nn.Linear(2,2).double()
self.linear3 = torch.nn.Linear(2,1).double()
def forward(self,x):
x=F.relu(self.linear1(x))
x=F.relu(self.linear2(x))
x=self.linear3(x)
return x
M=model()
L=nn.MSELoss()
print(list(M.linear1.parameters()))
list(M.linear1.parameters())[0]=torch.Tensor([[-0.1],
[ 0.2]])
print(list(M.linear1.parameters()))
然后
[Parameter containing:
tensor([[-0.2288],
[ 0.2211]], dtype=torch.float64, requires_grad=True), Parameter containing:
tensor([-0.9185, -0.2458], dtype=torch.float64, requires_grad=True)]
[Parameter containing:
tensor([[-0.2288],
[ 0.2211]], dtype=torch.float64, requires_grad=True), Parameter containing:
tensor([-0.9185, -0.2458], dtype=torch.float64, requires_grad=True)]
解决方案
每个都有两个参数张量nn.Linear
:一个用于权重矩阵,另一个用于偏差。该层实现的功能是
y = Wx + b
您可以通过访问它来设置参数张量的值data
:
with torch.no_grad():
M.linear1.weight.data[...] = torch.Tensor([[-0.1], [0.2]])
推荐阅读
- typescript - 尽管一切都是正确的,但从 Firebase 云中获取 null
- c# - 通过 user32.dll 在 Listbox 中选择 CheckBoxes?(
- c++ - OpenGL:将动态分配的矩阵传递给统一
- stripe-payments - Stripe 通过格子验证收集经常性 ACH 付款
- android - 在 InstrumentedTest 上使用 SSL 和 MockWebServer
- oop - 抽象数据类型与非抽象数据类型(Java 中)
- javascript - Ajax 调用加载的 Javascript 不执行?
- java - 奇怪的Java并发修改异常示例
- ios - 如何在 Swift 中组合 2 个 CoreData 谓词?
- c# - 筛选 2 个条件,包括不使用 Microsoft Graph SDK 的日期