二维 numpy 数组中行的经验分布

Empirical distribution of rows in 2d numpy array

假设我有一个 2d numpy 数组 A:

A = [[0.3, 0.2],
     [1.0, 0.1],
     [0.3, 0.1],
     [1.0, 0.1]]

我想要的是将 A 的行映射到它们的经验分布:

f([0.3, 0.2]) = 0.25
f([1.0, 0.1]) = 0.50
f([-12, 140]) = 0.00

有什么好的方法吗?

这是我的基于闭包的 hacky 方法:

def pdf_maker(A, round_place=10):
    counts = {}
    for i in range(A.shape[0]):
        key = tuple([round(a,round_place) for a in A[i]])
        try:
            counts[key] += 1.0
        except KeyError:
            counts[key] = 1.0

    pdf = {}
    for key in counts:
        pdf[key] = counts[key] / A.shape[0]

    def f_pdf(row):
        key = tuple([round(a,round_place) for a in row])
        try:
            return pdf[key]
        except KeyError:
            return 0.0

    return f_pdf

不过,我确信有更简洁的方法。

我建议使用 numpy.allclose。你可以选择一个公差,我这里放 1.e-10 :

import numpy as np

A = np.array([[0.3, 0.2],[1.0, 0.1],[0.3, 0.1], [1.0, 0.1]])

def f(x,tol=1.e-10):
  l = [np.allclose(x,row,tol) for row in A]
  return l.count(True)/float(A.shape[0])

print f(np.array([0.3,0.2]))
print f(np.array([1.0, 0.1]))
print f(np.array([-12, 140]))