假设我有一个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有什么好办法吗?
发布于 2016-01-28 17:27:08
我建议使用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]))发布于 2016-01-28 16:08:13
下面是基于恶意闭包的方法:
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不过,我肯定有个更干净的方法。
https://stackoverflow.com/questions/35066029
复制相似问题