【发布时间】:2019-02-27 16:02:59
【问题描述】:
我有一个 2d numpy 数组:
array([[21, 17, 11],
[230, 231, 232],
[21, 17, 11]], dtype=uint8)
我想找到更频繁的一维数组。对于上面的二维数组,它是: [21、17、11]。类似于统计模式中的模式。
【问题讨论】:
标签: arrays python-3.x python-2.7 numpy mode
我有一个 2d numpy 数组:
array([[21, 17, 11],
[230, 231, 232],
[21, 17, 11]], dtype=uint8)
我想找到更频繁的一维数组。对于上面的二维数组,它是: [21、17、11]。类似于统计模式中的模式。
【问题讨论】:
标签: arrays python-3.x python-2.7 numpy mode
我们可以使用np.unique 及其可选参数return_counts 来获取每个唯一行的计数,最后让argmax() 选择具有最大计数的行-
# a is input array
unq, count = np.unique(a, axis=0, return_counts=True)
out = unq[count.argmax()]
对于uint8 类型的数据,我们也可以通过将每一行减少为一个标量然后使用np.unique 来转换为1D -
s = 256**np.arange(a.shape[-1])
_, idx, count = np.unique(a.dot(s), return_index=True, return_counts=True)
out = a[idx[count.argmax()]]
如果我们正在使用3D(最后一个轴是颜色通道)的彩色图像并且想要获得最主要的颜色,我们需要使用a.reshape(-1,a.shape[-1]) 进行整形,然后将其提供给建议的方法。
【讨论】:
np.tensordot(a, s, axes = ((-1), (0))) 只是np.tensordot(a, s, 1)?
np.dot。编辑了那部分。
a.shape[-1]。如果您使用 256 ** np.arange(8, dtype = 'int64'),则为 7。否则你会溢出。