torch.nn.parameter.Parameter
时间: 2024-06-15 09:06:44 浏览: 18
torch.nn.parameter.Parameter是PyTorch中的一个类,用于定义模型中的可学习参数。它是torch.Tensor的子类,具有与Tensor相同的属性和方法,但它会自动被注册为模型的参数,可以通过模型的parameters()方法进行访问。
以下是一个使用torch.nn.parameter.Parameter的示例[^1]:
```python
import torch
import torch.nn as nn
# 定义一个简单的线性模型
class LinearModel(nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.weight = nn.Parameter(torch.randn(3, 3)) # 定义一个可学习的权重参数
self.bias = nn.Parameter(torch.zeros(3)) # 定义一个可学习的偏置参数
def forward(self, x):
return torch.matmul(x, self.weight) + self.bias
# 创建模型实例
model = LinearModel()
# 打印模型的参数
for name, param in model.named_parameters():
print(name, param.size())
# 输出:
# weight torch.Size([3, 3])
# bias torch.Size([3])
```
在上面的示例中,我们定义了一个简单的线性模型LinearModel,其中weight和bias都是nn.Parameter类型的参数。这些参数会自动被注册为模型的参数,并可以通过模型的named_parameters()方法进行访问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)