【问题标题】:Copying parts of numpy array to another array with extra dimension将部分numpy数组复制到另一个具有额外维度的数组
【发布时间】:2020-04-14 08:54:46
【问题描述】:

我正在尝试使用机器学习进行语义分割,我设法找到了一种方法来获得正确的热编码(使用这个:https://www.jeremyjordan.me/semantic-segmentation/)但是我获得的代码非常糟糕,我确信 numpy具有可以提供更优雅解决方案的功能。

想法如下:从标签数组 (88,240,240) 创建一个新数组 (88,240,240,3),并在每个通道中使用适当的值。

我想出了这个:

def data_reshape(train_image_list, train_label_list, img_size):
    temp = np.empty(shape=[train_label_list.shape[0], img_size[1], img_size[0], 3])
    temp[:,:,:,0] = train_label_list
    temp[temp[:,:,:,0] > 0] = 2
    temp[temp[:,:,:,0] == 0] = 1
    temp[temp[:,:,:,0] == 2] = 0

    temp[:,:,:,1] = train_label_list
    temp[temp[:,:,:,1] == 2] = 0

    temp[:,:,:,2] = train_label_list
    temp[temp[:,:,:,2] < 2] = 0
    temp[temp[:,:,:,2] == 2] = 1
    train_image_list = np.reshape(train_image_list, newshape=[-1, img_size[1], img_size[0], 1])
    train_label_list = np.reshape(temp, newshape=[-1, img_size[1], img_size[0], 3])

    return train_image_list, train_label_list

编辑:

它实际上并没有按应有的方式运行

我将重新制定:

我有一个 numpy 数组:(88,240,240),其中包含 88 个图像中每个图像上 3 个不同标签的信息(0 表示 label_0 的像素,1 表示 label_1 的像素,2 表示 label_2 的像素)。

我想从我的函数中拿出一个 numpy 数组,其中包含另外 3 个通道,每个通道包含不同的信息:

  • (88,240,240,0) 的 label_0 像素的值为 1(其余为 0)
  • (88,240,240,1) 的 label_1 像素的值为 1(其余为 0)
  • (88,240,240,2) 的 label_2 像素的值为 1(其余为 0)

有人有建议吗?

亲切的问候,

Unic0

【问题讨论】:

  • 是否运行并产生正确的结果?我没有看到任何需要删除的循环。 temp = train_label_list[...,None].repeat(3, -1) 简化了 temp 的启动。 temp 是否需要最后的 reshape
  • 是的,它运行并产生正确的结果。最后的重塑是将 'train_label_list 放入正确的形状,它可能确实不需要。但是你知道我是否可以做些什么来改进大量的 temp[:,:,:]... temp[:,:,:] 一遍又一遍。
  • 如果您提供一些人工输入(例如低亮度数组)会有所帮助,这样我们就可以运行代码并测试任何替代方案。

标签: python arrays numpy machine-learning one-hot-encoding


【解决方案1】:

train_label_list 的值为 0,1,2,您希望将其扩展为 3 个通道。那正确吗?

temp = np.zeros(shape=[train_label_list.shape[0], img_size[1], img_size[0], 3])
temp[:, :, :, 0] = train_label_list == 0
temp[:, :, :, 1] = train_label_list == 1
temp[:, :, :, 2] = train_label_list == 2

这应该可以解决问题。

【讨论】:

  • 这完全可以解决问题。我觉得很愚蠢,但是我不知道这种分配方式是可能的。非常感谢,
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
相关资源
最近更新 更多