python - Convert a 2D numpy array into a hot-encoded 3D numpy array, with same values in the same plane
问题描述
Suppose I have a Numpy array:
[
[0, 1, 0],
[0, 1, 4],
[2, 0, 0],
]
How can I turn this into a "hot encoded" 3D array? something like this:
[
# Group of 0's
[[1, 0, 1],
[1, 0, 0],
[0, 1, 1]],
# Group of 1's
[[0, 1, 0],
[0, 1, 0],
[0, 0, 0]],
# Group of 2's
[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]],
# Group of 3's
# the group is still here, even though there are no threes
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
# Group of 4's
[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]
]
That is, how can I take each occurrence of a number in the array and "group" them into their own plane in a 3D matrix? As shown in the example, even the "gap" in numbers (i.e. the 3
) should still appear. In my case, I know the range of the data beforehand (range (0, 6]
), so that should make it easier.
BTW, I need this because I have a chessboard represented by numbers, but need it in this form to pass into a 2d convolutional neural network (different "channels" for different pieces).
I've seen Convert a 2d matrix to a 3d one hot matrix numpy, but that has a one-hot encoding for every value, which isn't what I'm looking for.
解决方案
创建所需的数组(arr.max()+1
此处),然后对其进行整形以与原始数组进行比较:
设置:
arr = np.array([
[0, 1, 0],
[0, 1, 4],
[2, 0, 0],
])
u = np.arange(arr.max()+1)
(u[:,np.newaxis,np.newaxis]==arr).astype(int)
array([[[1, 0, 1],
[1, 0, 0],
[0, 1, 1]],
[[0, 1, 0],
[0, 1, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]])
推荐阅读
- angular - 角度多项目轮播的问题(flickity)
- php - WooCommerce - 将产品文档从产品信息移动到标签容器
- google-api - 为什么 Google+ API 方法 people.me 仍然有效?
- c# - 将 long 列表转换为可为空的 long 列表
- aws-lambda - AWS SAM 构建使用容器无需清洗
- mysql - 如何查询 mysql Kubernetes pod?用户 'root'@'localhost' 的访问被拒绝
- botframework - How can i implement bot framework in my visual studio code?
- powershell - 如何在 PowerShell 中获取 NuGet 包作者?
- sql - 为什么这个窗口表达式不会导致除以零错误?
- java - 如何避免在文件中的 JSONArray 中写入重复值