Ruby statsample "mode" 函数是否正确?
Is Ruby statsample "mode" function correct?
Ruby's statiscts gem (Statsample) 似乎给出了错误的答案。
模式函数不应该 return 是数组中最常见的元素吗?例如:4
irb(main):185:0> [1,2,3,2,4,4,4,4].to_vector
=>
#<Daru::Vector:34330120 @name = nil @size = 8 >
nil
0 1
1 2
2 3
3 2
4 4
5 4
6 4
7 4
irb(main):186:0> [1,2,3,2,4,4,4,4].to_vector.mode
=> 2
为什么 returning 2 ?
ruby 2.1.6p336 (2015-04-13 revision 50298) [x64-mingw32]
statsample (2.0.1)
是的,你是对的维克多!矢量库中存在错误:
[1,2,3,2,4,4,4,4].to_vector
=>
#<Daru::Vector:70255750869440 @name = nil @size = 8 >
nil
0 1
1 2
2 3
3 2
4 4
5 4
6 4
7 4
[1,2,3,2,4,4,4,4].to_vector.frequencies
=> {1=>1, 2=>2, 3=>1, 4=>4}
[1,2,3,2,4,4,4,4].to_vector.frequencies.values
=> [1, 2, 1, 4]
然后从具有给定索引的基本数组中获取最大值和 returns 值的索引(第 4 个位置 -> 在您的情况下为值 2
)。这是通过 method:
完成的
def mode
freqs = frequencies.values
@data[freqs.index(freqs.max)]
end
解决方法
您可以使用此方法代替 mode
方法:
[1,2,3,2,4,4,4,4].to_vector.frequencies.max{|a,b| a[1]<=>b[1]}.first
=> 4
我同意 Jakub 所说的。这是 mode method in the Vector module of daru gem. All the Vector related methods in statsample are now based on daru. I have submitted a pull request to daru 修复此错误中的错误,希望这将在下一个发布版本中。
Ruby's statiscts gem (Statsample) 似乎给出了错误的答案。 模式函数不应该 return 是数组中最常见的元素吗?例如:4
irb(main):185:0> [1,2,3,2,4,4,4,4].to_vector
=>
#<Daru::Vector:34330120 @name = nil @size = 8 >
nil
0 1
1 2
2 3
3 2
4 4
5 4
6 4
7 4
irb(main):186:0> [1,2,3,2,4,4,4,4].to_vector.mode
=> 2
为什么 returning 2 ?
ruby 2.1.6p336 (2015-04-13 revision 50298) [x64-mingw32]
statsample (2.0.1)
是的,你是对的维克多!矢量库中存在错误:
[1,2,3,2,4,4,4,4].to_vector
=>
#<Daru::Vector:70255750869440 @name = nil @size = 8 >
nil
0 1
1 2
2 3
3 2
4 4
5 4
6 4
7 4
[1,2,3,2,4,4,4,4].to_vector.frequencies
=> {1=>1, 2=>2, 3=>1, 4=>4}
[1,2,3,2,4,4,4,4].to_vector.frequencies.values
=> [1, 2, 1, 4]
然后从具有给定索引的基本数组中获取最大值和 returns 值的索引(第 4 个位置 -> 在您的情况下为值 2
)。这是通过 method:
def mode
freqs = frequencies.values
@data[freqs.index(freqs.max)]
end
解决方法
您可以使用此方法代替 mode
方法:
[1,2,3,2,4,4,4,4].to_vector.frequencies.max{|a,b| a[1]<=>b[1]}.first
=> 4
我同意 Jakub 所说的。这是 mode method in the Vector module of daru gem. All the Vector related methods in statsample are now based on daru. I have submitted a pull request to daru 修复此错误中的错误,希望这将在下一个发布版本中。