📜  torchvision.transforms 展平 - Python (1)

📅  最后修改于: 2023-12-03 15:20:40.005000             🧑  作者: Mango

Torchvision Transforms: Flatten

Torchvision is a PyTorch library that consists of popular datasets, model architectures, and image transformation tools. Transforms are an essential part of image data preprocessing and augmentation.

One useful transform from torchvision.transforms is Flatten.

What is Flatten?

Flatten is a transform that converts a tensor of shape (C, H, W) to a tensor of shape (CHW,). It is useful for flattening an image into a 1D vector that can be fed into a fully connected neural network.

How to use Flatten?

Here is an example of how to use Flatten in a PyTorch dataset:

import torch
import torchvision.transforms as transforms

# Example data of shape (3, 28, 28)
data = torch.randn(3, 28, 28)

# Define the Flatten transform
flatten = transforms.Flatten()

# Apply the transform to the data
flattened_data = flatten(data)

# Check the shape of the flattened data
print(flattened_data.shape)  # Output: torch.Size([2352])
Conclusion

Flatten is a useful transform from torchvision.transforms that can be used to reshape image tensors to a 1D vector. It is a simple and effective way of converting an image into a format that is compatible with fully connected neural networks.