将 Mnist 数组数据转换为每个像素值的单热编码数组

Converting Mnist array data to one-hot encoded arrays for each pixel value

我正在尝试将来自 mnist 的归一化像素数据矩阵转换为单热数组矩阵,表示基于 class 每个像素的 y_val & 如果它大于0.

这是一个输入示例,更具体地说是来自数据集中单个示例的一行:

[[0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.01176471]
 [0.07058824]
 [0.07058824]
 [0.07058824]
 [0.49411765]
 [0.53333336]
 [0.6862745 ]
 [0.10196079]
 [0.6509804 ]
 [1.        ]
 [0.96862745]
 [0.49803922]
 [0.        ]
 [0.        ]
 [0.        ]
 [0.        ]]

像素亮度值的 28 元素数组。 现在,假设这个输入的真实 class 是数字“2”。 该脚本将遍历并插入一个单热数组,其中每个像素值当前所在的位置。

如果像素== 0,那么它将从

转换而来
[0.        ]

[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

因为我使用第 11 个条目来表示空白像素。

如果数组元素的值 > 0,它将插入示例真实标签的单热数组,即“2”。

[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

这是我目前的代码

#copying the shape of the train data matrix of arrays into a new
#array
new_y_train = np.copy(x_train)

for ex_index, example in enumerate(x_train):
  for row_index, row in enumerate(example):
    for px_index, pixel in enumerate(row):
      temp_arr = np.zeros(11)
      if pixel > 0:
        pixel = np.insert(temp_arr, np.argmax(y_train[index]), 1)
        new_y_train[ex_index][row_index][px_index] = pixel
      else:
        pixel = np.insert(temp_arr, 11, 1)
        new_y_train[ex_index][row_index][px_index] = pixel

然而,当我到达这一行时

new_y_train[ex_index][row_index][px_index] = pixel

我收到有关将数组广播到像素值的错误,"could not broadcast input array from shape (12) into shape (1)"

不确定如何调整数组大小或修改数组以允许将这个新的单热数组输入到矩阵中。

任何帮助都会很棒!

你可以使用花哨的索引来做到这一点

arr = np.array([[0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.01176471],
 [0.07058824],
 [0.07058824],
 [0.07058824],
 [0.49411765],
 [0.53333336],
 [0.6862745 ],
 [0.10196079],
 [0.6509804 ],
 [1.        ],
 [0.96862745],
 [0.49803922],
 [0.        ],
 [0.        ],
 [0.        ],
 [0.        ],],)

labels = np.random.choice(10, len(arr)).reshape(-1,1)

ind_row = np.arange(len(arr))
ind_col = np.where(arr>0, labels, 10).ravel()

one_hot_coded_arr = np.zeros((len(arr), 11))
one_hot_coded_arr[ind_row,ind_col]=1

one_hot_coded_arr

编辑

如果你有 10 个图像数据,那么可以像这样转换成你想要的形状

data = np.random.choice(255, (10,28,28))
labels = np.random.choice(9, (10,1))

## do you calculation of brightness here
## and expand it to one row per pixel
arr = data.reshape(-1,1)/255
## repeat labels to match the expanded pixel
labels = labels.repeat(28*28).reshape(-1,1)

ind_row = np.arange(len(arr))
ind_col = np.where(arr>0, labels, 10).ravel()

one_hot_coded_arr = np.zeros((len(arr), 11))
one_hot_coded_arr[ind_row,ind_col]=1

## convert back to desired shape
one_hot_coded_arr.reshape(-1, 28,28,11)