pytorch如何显示mnist的image
时间: 2024-01-29 20:03:32 浏览: 20
您可以使用以下代码在PyTorch中显示MNIST图像:
```python
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms
# define the transformation to apply to the data
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
# load the MNIST dataset
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# get a batch of images and labels
images, labels = next(iter(trainloader))
# display the first image in the batch
plt.imshow(images[0].numpy().squeeze(), cmap='gray')
plt.show()
```
请确保已经安装了matplotlib、torch和torchvision库。此代码将显示MNIST数据集中的第一张图像。您可以修改数字0以显示批次中的其他图像。