我使用统计.平均值()根据抽样分布计算平均值。但是,在下面的代码中,从下面的值返回的值是四舍五入的整数。如果我使用numpy.平均值()将获得正确的浮点类型的结果。这是怎么回事?在
import statistics
from scipy import stats
posterior_sample = stats.beta.rvs(3, 19, size = 1000)
predictive_sample = stats.binom.rvs(100, posterior_sample, size = 1000)
print(statistics.mean(predictive_sample))
print(statistics.mean([(data >= 15).astype(int) for data in predictive_sample]))
statistics.mean
不支持numpy.int64
数据类型。在来自
statistics
的docs:要解决这个问题,您可以按照建议进行操作,并在传递到
statistics.mean()
之前将数据转换为float
。在现在来看看这种行为背后的深层原因:
在
statistics.mean
的source code末尾,有一个对statistics._convert
的调用,这意味着将返回值转换为适当的类型(即,如果输入是分数,float
如果输入是int
等),则将返回值转换为适当的类型。在
^{pr2}$_convert
中的single line用于捕获其他数据类型,并确保返回值与提供的数据一致(T
是每个输入值的数据类型,value
是计算的平均值):如果您的输入是
numpy.int64
,那么_convert
函数将尝试将计算的平均值转换为numpy.int64
数据类型。NumPy很乐意将浮点转换为int(我想是四舍五入)。因此,mean
函数返回四舍五入到最接近整数的平均值,编码为numpy.int64
。在如果您的输入数据是
numpy.float64
,那么就不会有这个问题了。在相关问题 更多 >
编程相关推荐