2d numpy数组中行的经验分布

时间:2016-01-28 15:52:05

标签: python arrays numpy probability

我们说我有一个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

有一个很好的方法吗?

2 个答案:

答案 0 :(得分:2)

我建议使用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]))

答案 1 :(得分:0)

这是我的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

我确信这样做的方法比较干净。