将numpy数组的一部分复制到另一个具有额外维度的数组中

我在尝试使用机器学习进行语义分割,并且我设法找到了获得正确的一热编码的方法(使用这个: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表示标签_0的像素,1表示标签_1的像素,2表示标签_2的像素)。

我希望我的函数输出一个具有3个额外通道的numpy数组,每个通道包含不同的信息:

  • (88,240,240,0)将包含标签_0的像素,其值为1(其余为0)
  • (88,240,240,1)将包含标签_1的像素,其值为1(其余为0)
  • (88,240,240,2)将包含标签_2的像素,其值为1(其余为0)

有人有建议吗?

此致,

Unic0


回答:

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 == 0temp[:, :, :, 1] = train_label_list == 1temp[:, :, :, 2] = train_label_list == 2

这应该能解决问题。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注