obt*_*ind 2 python counter numpy
我有一个numpy数组的各种热编码numpy数组,例如;
x = np.array([[1, 0, 0], [0, 0, 1], [1, 0, 0]])
Run Code Online (Sandbox Code Playgroud)
我想计算每个独特的热矢量的出现,
{[1, 0, 0]: 2, [0, 0, 1]: 1}
Run Code Online (Sandbox Code Playgroud)
Div*_*kar 10
方法#1
似乎是一个完美的设置,可以使用numpy.unique (v1.13和更新版本)的新功能,让我们沿着NumPy数组的轴工作 -
unq_rows, count = np.unique(x,axis=0, return_counts=1)
out = {tuple(i):j for i,j in zip(unq_rows,count)}
Run Code Online (Sandbox Code Playgroud)
样本输出 -
In [289]: unq_rows
Out[289]:
array([[0, 0, 1],
[1, 0, 0]])
In [290]: count
Out[290]: array([1, 2])
In [291]: {tuple(i):j for i,j in zip(unq_rows,count)}
Out[291]: {(0, 0, 1): 1, (1, 0, 0): 2}
Run Code Online (Sandbox Code Playgroud)
方法#2
对于早于NumPy的版本v1.13,我们可以利用输入数组是一个热编码数组的事实,就像这样 -
_, idx, count = np.unique(x.argmax(1), return_counts=1, return_index=1)
out = {tuple(i):j for i,j in zip(x[idx],count)} # x[idx] is unq_rows
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
666 次 |
| 最近记录: |