julia-lang中的直方图计算

问题描述 投票:0回答:3

请参阅 julia-lang 文档:

hist(v[, n]) → e, 计数

计算 v 的直方图,可选择使用大约 n 个 bin。返回值是范围 e(对应于 bin 的边缘)以及包含每个 bin 中 v 的元素数量的计数。注意:Julia 在计算中不会忽略 NaN 值。

我选择数据样本范围

testdata=0:1:10;

然后使用 hist 函数计算 1 到 5 个 bin 的直方图

hist(testdata,1) # => (-10.0:10.0:10.0,[1,10])
hist(testdata,2) # => (-5.0:5.0:10.0,[1,5,5])
hist(testdata,3) # => (-5.0:5.0:10.0,[1,5,5])
hist(testdata,4) # => (-5.0:5.0:10.0,[1,5,5])
hist(testdata,5) # => (-2.0:2.0:10.0,[1,2,2,2,2,2])

如您所见,当我想要 1 个 bin 时,它会计算 2 个 bin,当我想要 2 个 bin 时,它会计算 3 个。

为什么会出现这种情况?

histogram julia
3个回答
9
投票

作为编写底层函数的人:目标是获得在以 10 为基数的计数系统中“良好”的 bin 宽度(即 10k、2×10k、5×10k) )。如果您想要更多控制,您还可以指定确切的 bin 边缘。


5
投票

文档中的关键词是近似。您可以在 Julia 的

hist
模块
here
中检查 base 实际上为自己做了什么。

当您这样做时

hist(test,3)
,您实际上是在打电话

hist(v::AbstractVector, n::Integer) = hist(v,histrange(v,n))

也就是说,第一步将

n
参数通过
FloatRange
函数转换为
histrange
,其代码可以在 here 找到。正如您所看到的,这些步骤的计算并不完全简单,因此您应该稍微尝试一下这个函数,以弄清楚它是如何构建构成直方图基础的范围的。


0
投票

在 Julia 的新版本中,不存在

hist
函数。

要计算直方图,应使用

StatsBase.Histogram
StatsBase.fit
,例如:

    using StatsBase
    h = fit(Histogram, rand(100))
    print(h)

输出:

Histogram{Int64, 1, Tuple{StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}}
edges:
  0.0:0.2:1.0
weights: [21, 22, 17, 16, 24]
closed: left
isdensity: false
© www.soinside.com 2019 - 2024. All rights reserved.