在python中,如何使用像素数作为xaxis和灰度颜色作为yaxis来绘制图形?

2024-05-23 14:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我下载了MNIST数据集,并使用imshow函数以灰度绘制数据集的第一幅图像。 这是我的密码

import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms

# MNIST dataset 
transform = transforms.Compose([transforms.ToTensor()])
train_dataset = torchvision.datasets.MNIST(root='./data', 
                                           train=True, 
                                           download=True,
                                           transform=transform)

# Change data type : torch.Tensor -> numpy array
X = train_dataset.train_data.numpy()
y = train_dataset.train_labels.numpy()
print('Data size: ' + str(X.shape))

num_samples, height, width = X.shape 
dim = height * width

# Visualize MNIST data (1st digit)
plt.figure(1)
plt.imshow(X[0],cmap='gray_r')
plt.colorbar()
plt.title('1st image label: 5')

我得到了这个数字

enter image description here

在将二维图像向量重塑为一维向量后,我想进行绘图 这个数字是这样的

enter image description here

x轴表示像素数,y轴表示其灰度颜色的像素值,以及 情节是这样的,有点像光谱。 我知道如何重塑向量,但我不知道如何绘制图。 我可以用matplotlib模块中的函数使绘图与第二个类似吗?还是在什么地方


1条回答
网友
1楼 · 发布于 2024-05-23 14:32:15

您正在寻找类似以下代码的内容。我把mnist的数字想象成麻木

#load digits using the module load_digits()
digits = datasets.load_digits()

#visualize digits : 25 in 2D visualization
plt.figure()
plt.imshow(digits.images[25], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.show()

输出为 enter image description here

相关问题 更多 >