nn.Sequential.parameters中包含所有参数吗
时间: 2023-11-12 17:55:46 浏览: 83
不是的,nn.Sequential.parameters() 方法返回的是一个迭代器,包含该 Sequential 模型中所有需要求导的参数。也就是说,它只包含那些需要更新的参数。
下面是一个例子来说明这个问题:
```python
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
return x
model = MyModel()
parameters = model.parameters()
print(list(parameters))
```
输出结果为:
```
[Parameter containing:
tensor([[ 0.1367, -0.1520, -0.0944, 0.2329, 0.2024, -0.2928, 0.0491, -0.2570,
-0.1979, -0.2368],
[ 0.2011, -0.1153, -0.2079, -0.0974, -0.0035, -0.0678, 0.0027, -0.1837,
-0.0707, -0.2789],
[ 0.0334, 0.1613, -0.1554, -0.0992, 0.1989, -0.0741, -0.2149, 0.2528,
0.1382, -0.1898],
[-0.2043, 0.2305, -0.0033, 0.0022, -0.0575, 0.0173, -0.0146, 0.0319,
0.0908, -0.1867],
[ 0.0196, 0.0233, -0.1228, 0.2973, -0.1712, -0.1972, -0.2779, 0.2422,
-0.2791, -0.1155]], requires_grad=True), Parameter containing:
tensor([-0.0811, -0.0356, -0.0876, -0.0708, 0.2083], requires_grad=True), Parameter containing:
tensor([[ 0.1267, -0.3424, -0.3776, 0.2399, 0.0728],
[-0.3187, -0.1893, -0.1025, 0.1142, 0.1251]], requires_grad=True), Parameter containing:
tensor([0.0316, 0.0554], requires_grad=True)]
```
可以看到,返回的是一个包含四个参数的列表,对应于两个线性层的权重和偏置。
阅读全文