0

例如,我从 mat 文件加载的 background-Mnist 为训练集提供了 50,000x784。

应该有 50,000 个 28x28 图像

我用

    f_train = scio.loadmat('mnist_background_images/mnist_background_images_train.mat')
    f_test = scio.loadmat('mnist_background_images/mnist_background_images_test.mat')
    data_train = f_train['mnist_background_images_train']
    data_test = f_test['mnist_background_images_test'] #this gives 50,000x785 where last column is y
    x_train = data_train[:, :-1]
    x_test= data_test[:, :-1] #now it's 50,000x784
    x_train = np.reshape(x_train, newshape=(-1, 28, 28 )) #new shape 50,000x28x28
    x_test = np.reshape(x_test, newshape=(-1, 28, 28))

这给出了正确的尺寸。

但是,当我尝试通过

img = x_train[2]
out = Image.fromarray(img, mode = 'L')
print(x_train.shape) 

给出 (50000, 784)

这张图片看起来一点也不像 MNIST 数据。像素混合在一起,到处都是,就像一切都被打乱了一样。我在某个地方犯了一个愚蠢的错误吗?

4

1 回答 1

0

Python 代码中的逻辑是正确的。看起来您的 .mat 文件已损坏,或者至少不包含您认为它应该包含的内容。(我个人对 Python/Matlab 数据交换感到头疼。)这不太可能,但你可以尝试

data_train = data_train.T.reshape(50000, 785)

以防万一在 Matlab 中的重塑动作不正确。

如果您加载原始数据,它会以带有文件名后缀的文本文件的形式提供.amat

import numpy as np
data = np.loadtxt('mnist_background_images_test.amat', dtype=np.float32) # shape (50000, 785)
scale = 255 / data.max() 
data8 = np.array(data * scale, dtype=np.uint8) # 8-bit image data

y = data[:, -1].astype(int)
x = data8[:, :-1].reshape(-1, 28, 28)

import matplotlib.pyplot as plt
plt.close('all')
plt.imshow(x[2], cmap='Greys')
plt.show()

MNIST 集中的一张图片

于 2020-06-21T21:12:28.033 回答