nn.Linear()函数的用法
时间: 2023-10-14 12:02:30 浏览: 211
`nn.Linear()`函数是 PyTorch 中用于创建线性层的函数。线性层也称为全连接层或仿射层,是深度学习中常用的一种基本层类型。
`nn.Linear()`函数的用法如下:
```python
torch.nn.Linear(in_features, out_features, bias=True)
```
其中参数的含义如下:
- `in_features`:输入特征的数量。它是一个正整数,表示输入张量的最后一个维度的大小。例如,如果输入张量的形状是 `(batch_size, in_features)`,则 `in_features` 就是 `in_features`。
- `out_features`:输出特征的数量。它是一个正整数,表示输出张量的最后一个维度的大小。例如,如果输出张量的形状是 `(batch_size, out_features)`,则 `out_features` 就是 `out_features`。
- `bias`:是否使用偏置,默认为 `True`。如果设置为 `False`,则线性层没有偏置项。
`nn.Linear()`函数返回一个线性层对象,可以将其作为模型的一部分使用。例如,在构建神经网络模型时,可以使用`nn.Linear()`函数来定义模型的线性层。
下面是一个示例,展示了如何使用`nn.Linear()`函数构建一个简单的神经网络模型:
```python
import torch
import torch.nn as nn
# 定义输入特征和输出特征的数量
in_features = 10
out_features = 5
# 创建线性层对象
linear_layer = nn.Linear(in_features, out_features)
# 打印线性层的权重和偏置
print(linear_layer.weight)
print(linear_layer.bias)
```
在上述代码中,我们首先导入了 `torch` 和 `torch.nn` 模块。然后,定义了输入特征的数量 `in_features` 和输出特征的数量 `out_features`。
接下来,使用 `nn.Linear(in_features, out_features)` 创建了一个线性层对象 `linear_layer`。
最后,我们打印了线性层的权重和偏置项。注意,权重和偏置项是线性层的可学习参数,它们在模型训练过程中会被更新。
通过使用 `nn.Linear()` 函数,您可以方便地创建线性层,并将其应用于神经网络模型中。
阅读全文
相关推荐

















