Usage of () and ()
The function of the flatten() function is to flatten the tensor into one dimension
(input, start_dim=0, end_dim=- 1) → Tensor
-
input (Tensor)
– the input tensor. -
start_dim (int)
– the first dim to flatten -
end_dim (int)
– the last dim to flatten
start_dim and end_dim form the entire range of dimensions you want to choose to pave.
The following examples are given
x = ([[1,2], [3,4], [5,6]]) x = (0) x ------------------------ tensor([1, 2, 3, 4, 5, 6])
For image data, we often expect the dimensions entering the fc layer to be (channels, N)
x = ([[[1,2],[3,4]], [[5,6],[7,8]]]) x = (1) x ------------------------- tensor([[1, 2], [3, 4], [5, 6]])
Note:
(start_dim=1, end_dim=- 1)
start_dim defaults to 1
So when building a network, the following two are equivalent
class Classifier(): def __init__(self): super(Classifier, self).__init__() # The arguments for commonly used modules: # .Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0) # .MaxPool2d(kernel_size, stride=None, padding=0) # input image size: [3, 128, 128] self.cnn_layers = ( nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), (), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128), (), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256), (), nn.MaxPool2d(kernel_size=4, stride=4, padding=0), ) self.fc_layers = ( (256 * 8 * 8, 256), (), (256, 256), (), (256, 11) ) def forward(self, x): # input (x): [batch_size, 3, 128, 128] # output: [batch_size, 11] # Extract features by convolutional layers. x = self.cnn_layers(x) # The extracted feature map must be flatten before going to fully-connected layers. x = (1) # The features are transformed by fully-connected layers to obtain the final logits. x = self.fc_layers(x) return x
class Classifier(): def __init__(self): super(Classifier, self).__init__() = ( nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), (), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128), (), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256), (), nn.MaxPool2d(kernel_size=4, stride=4, padding=0), (), (256 * 8 * 8, 256), (), (256, 256), (), (256, 11) ) def forward(self, x): x = (x) return x
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.