计算数组中唯一数组的出现 [英] Count occurrences of unique arrays in array

查看:98
本文介绍了计算数组中唯一数组的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由多个热编码的numpy数组组成的numpy数组,例如;

I have a numpy array of various one hot encoded numpy arrays, eg;

x = np.array([[1, 0, 0], [0, 0, 1], [1, 0, 0]])

我想计算每个唯一的一个热向量的出现次数,

I would like to count the occurances of each unique one hot vector,

{[1, 0, 0]: 2, [0, 0, 1]: 1}

推荐答案

方法1

似乎是使用 numpy.unique (v1.13及更高版本),使我们能够沿着NumPy数组的轴进行工作-

Seems like a perfect setup to use the new functionality of numpy.unique (v1.13 and newer) that lets us work along an axis of a NumPy array -

unq_rows, count = np.unique(x,axis=0, return_counts=1)
out = {tuple(i):j for i,j in zip(unq_rows,count)}

样本输出-

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}


方法2

对于早于v1.13的NumPy版本,我们可以利用这样的事实,即输入数组是一个热编码的数组,就像这样-

For NumPy versions older than v1.13, we can make use of the fact that the input array is one-hot encoded array, like so -

_, 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

这篇关于计算数组中唯一数组的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆