在Julia中置换字符串并作为函数参数传递

时间:2014-05-23 14:14:45

标签: julia

在我继续更加彻底地开始对朱莉娅的轮胎中,我会回去重新实现我对贝叶斯课程练习的解决方案。上次,我在Julia发现了共轭分布设施,并决定这次使用它们。那部分工作得很好(顺便说一下,我没有想出是否有一个很好的理由NormalInverseGamma函数不会采用足够的统计数据而不是数据向量,或者它是否尚未实现)。

在这里,我想对几个后验分布的样本进行一些比较。我有三个后验样本,我想比较所有的排列。我能够置换我的compare函数的参数:

using Distributions

# Data, the expirgated versions
d1 = [2.11, 9.75, 13.88, 11.3, 8.93, 15.66, 16.38, 4.54, 8.86, 11.94, 12.47]
d2 = [0.29, 1.13, 6.52, 11.72, 6.54, 5.63, 14.59, 11.74, 9.12, 9.43]
d3 = [4.33, 7.77, 4.15, 5.64, 7.69, 5.04, 10.01, 13.43, 13.63, 9.9]

# mu=5, sigsq=4, nu=2, k=1
# think I got those in there right... docs were a bit terse
pri = NormalInverseGamma(5, 4, 2, 1)
post1 = posterior(pri, Normal, d1)
post1_samp = [rand(post1)[1] for i in 1:5000]

post2 = posterior(pri, Normal, d2)
post2_samp = [rand(post2)[1] for i in 1:5000]

post3 = posterior(pri, Normal, d3)
post3_samp = [rand(post2)[1] for i in 1:5000];

# Where I want my permutations passed in as arguments
compare(a, b, c) = mean((a .> b) & (b .> c))

#perm = permutations([post1_samp, post2_samp, post3_samp]) # variables?
#perm = permutations([:post1_samp, :post2_samp, :post3_samp]) # symbols?
perm = permutations(["post1_samp", "post2_samp", "post3_samp"]) # strings?

[x for x in perm] # looks like what I want; now how to feed to compare()?

1 个答案:

答案 0 :(得分:2)

如果我正确地阅读了您并且您想要六个输出,则可以将包含数组的元组传递给permutations,然后使用apply

julia> perm = permutations((post1_samp, post2_samp, post3_samp))
Permutations{(Array{Any,1},Array{Any,1},Array{Any,1})}(({10.562517942895859,10.572164090071183,10.736702907907505,10.210772173751444,14.366729334490795,10.592629893299842,9.89659091860089,8.116412691836256,10.349724070315517,11.268377549210639  …  12.064725902593915,10.303602433314985,10.002042635051714,9.055831122365928,10.110819233623218,11.562207296236382,10.64265460839246,13.450063260877014,12.017400480458447,10.4932272939257},{7.405568037651908,8.02078920939688,7.511497830660621,7.887748694407902,7.698862774251405,6.007663099515951,7.848174806167786,9.23309632138448,7.205139036914154,8.277223275210972  …  7.06835013863376,6.488809918983307,9.250388581506368,7.350669918529516,5.546251008276725,8.778324046008263,10.833297020230216,9.2006982752771,9.882075423462595,3.253723211533207},{9.531489314208752,7.395780786761686,6.224734811478234,5.200474665890965,8.044992565567913,7.764939771450804,6.646382928269485,5.501893299017636,6.993003549302548,7.243273003116189  …  10.249365688182436,7.499165465689278,6.056692905419897,7.411776062227991,9.829197784956492,7.014685931227273,6.156474145474993,10.258900762434248,-1.044259248117803,7.284861693401341}))

julia> [apply(compare, p) for p in perm]
6-element Array{Any,1}:
 0.4198
 0.4182
 0.0636
 0.0154
 0.0672
 0.0158

请记住,虽然在名字中有一堆带有数字的变量通常是一个失误:这通常表明他们应该在一个某种命名的集合中(" post_samples",说。)