无法绘制 MNIST 数字

Trouble plotting MNIST digits

我正在尝试加载和可视化 MNIST 数字,但我得到的数字具有移位的像素

import matplotlib.pyplot as plt
import numpy as np

mnist_data  = open('data/mnist/train-images-idx3-ubyte', 'rb')

image_size = 28
num_images = 4

buf = mnist_data.read(num_images * image_size * image_size)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data.reshape(num_images, image_size, image_size)

_, axarr1 = plt.subplots(2,2)
axarr1[0, 0].imshow(data[0])
axarr1[0, 1].imshow(data[1])
axarr1[1, 0].imshow(data[2])
axarr1[1, 1].imshow(data[3])

任何人都可以告诉我为什么它发生代码看起来很好,谢谢

你没有说你从哪里获得了 MNIST 数据,但是,if it is formatted like the original data set,你似乎忘记了在尝试访问数据之前提取 header:

image_size = 28
num_images = 4

mnist_data = open('train-images-idx3-ubyte', 'rb')

mnist_data.seek(16) # skip over the first 16 bytes that correspond to the header
buf = mnist_data.read(num_images * image_size * image_size)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data.reshape(num_images, image_size, image_size)

_, axarr1 = plt.subplots(2,2)
axarr1[0, 0].imshow(data[0])
axarr1[0, 1].imshow(data[1])
axarr1[1, 0].imshow(data[2])
axarr1[1, 1].imshow(data[3])