nn.sequential
时间: 2023-09-25 09:15:49 浏览: 67
对Pytorch中nn.ModuleList 和 nn.Sequential详解
nn.Sequential is a module in PyTorch that allows users to create a neural network by sequentially adding layers to it. It simplifies the process of creating a neural network by providing a way to define the architecture of the network in a single line of code.
The nn.Sequential module takes a list of layers as input and creates a neural network by stacking these layers one after the other. Each layer in the list is called in the order that it appears in the list.
Here is an example of how to use nn.Sequential to create a simple neural network:
```
import torch.nn as nn
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
nn.LogSoftmax(dim=1)
)
```
In this example, we create a neural network with two linear layers and two activation functions. The first linear layer has 784 input features and 256 output features, while the second linear layer has 256 input features and 10 output features. We apply a ReLU activation function after the first linear layer and a LogSoftmax activation function after the second linear layer.
Overall, nn.Sequential is a useful tool for building simple neural networks quickly and efficiently. However, for more complex architectures, it may be necessary to use other PyTorch modules such as nn.Module or nn.Functional.
阅读全文