nn.Sequential()
时间: 2023-11-12 09:05:27 浏览: 80
pytorch构建网络模型的4种方法
nn.Sequential() is a PyTorch module that allows you to create a neural network by stacking up layers in a sequential manner. It is a container that holds modules (layers) in a specific order, where the output of one module is passed as input to the next one.
For example, let's say we want to create a simple neural network with two fully connected layers, a ReLU activation function, and a final softmax layer. We can do this using nn.Sequential() as follows:
```
import torch.nn as nn
model = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 10),
nn.Softmax(dim=1)
)
```
In this example, we first define a fully connected layer with 784 input features and 128 output features. We then apply a ReLU activation function to the output of this layer. The output of the ReLU layer is then passed to another fully connected layer with 128 input features and 10 output features. Finally, we apply a softmax function along the second dimension of the output tensor to get the probabilities for each of the 10 classes.
Note that we don't have to specify the input dimension of the first layer in the Sequential container. Instead, the input dimension is inferred from the size of the input tensor during training.
阅读全文