【问题标题】:Images get distorted after splitting the array using scikit-learn使用 scikit-learn 拆分数组后图像失真
【发布时间】:2021-01-17 09:20:14
【问题描述】:

我有一个 .mat 文件,其中包含一组 600 24*21 图像。因此得到的维度是(24, 21, 600)。以下代码将在子图中显示图像:

X = loadmat('../input/data.mat')['face']
# generate dummy labels for this example
y = np.concatenate([np.zeros(300), np.ones(300)])

# X.shape == (24, 21, 600)
# y.shape == (600,)

fig, ax = plt.subplots(4,5)

for i, axis in enumerate(ax.flat):
    axis.imshow(X[:,:,i], cmap='bone')
    axis.set(xticks=[], yticks=[])

没关系。问题是当我尝试使用以下方法将数据拆分为训练和测试数据时:

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    random_state=42,
    test_size=0.2,
    shuffle=True
)

发生错误:

ValueError: Found input variables with inconsistent numbers of samples: [24, 600]

我知道错误是我的Xy 的第一个维度不匹配。但是,如果我尝试使用X = X.reshape(600, 24, 21) 重塑X 以使X.shape === (600, 24, 21) 形状固定,我可以使用train_test_split() 成功拆分数据

但是,现在当我尝试使用以下代码制作子图时:

fig, ax = plt.subplots(4,5)

for i, axis in enumerate(ax.flat):
    axis.imshow(X[i,:,:], cmap='bone')
    axis.set(xticks=[], yticks=[])

图像没有意义并且被改变了。我无法使用这些图像制作分类器。谁能帮帮我?

  1. 在最好的情况下,如何拆分数据而无需重塑?
  2. 如何在重新整形并成功拆分数据后不扭曲图像?

【问题讨论】:

    标签: python numpy image-processing


    【解决方案1】:

    问题是样本轴在位置 2 而不是 0。然后 Sklearn 认为你有 24 个形状为 (21, 600) 的样本。 您希望 X.shape 成为 (600, 24, 21) 而不是 (24, 21, 600)

    所以,你可以使用np.rollaxis 来改变位置:

    X = np.rollaxis(X, 2, 0)
    

    【讨论】:

    • 虽然我使用了X = X.transpose([2, 0, 1]),但您的解决方案也可能会奏效。事实上,我的问题与this question 重复。
    猜你喜欢
    • 2016-05-22
    • 2021-05-10
    • 2018-03-25
    • 2015-02-23
    • 2012-07-16
    • 1970-01-01
    • 2019-10-04
    • 2015-06-08
    • 2020-06-22
    相关资源
    最近更新 更多