JULIA:如何在 julia 中随机排列一个向量?

JULIA : How to permute randomly a vector in julia?

我有一个随机数向量,我想使用 randperm() 函数随机排列,如下所示,但它不起作用。

X=rand(100000) # a vector of 100000 random elements
Y=randperm(X) # want to permute randomly the vector x

返回的错误是: 错误:MethodError:没有匹配 randperm(::Array{Float64,1}) 的方法 在 eval(::Module, ::Any) 中./boot.jl:237

谢谢

使用shuffle()

如果您的唯一目标是随机排列向量,您可以使用 shuffle()Random 模块的一部分):

julia> using Random;

julia> X = collect(1:5)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> shuffle(X)
5-element Array{Int64,1}:
 5
 4
 1
 2
 3

如果你不想分配一个新的vector,而是想原地洗牌,你可以使用shuffle!():

julia> shuffle!(X);

julia> X
5-element Vector{Int64}:
 3
 4
 2
 5
 1

randperm()

randperm() 接受整数 n 并给出长度为 n 的排列。您可以使用此顺序对原始向量重新排序:

julia> X[randperm(length(X))]
5-element Array{Int64,1}:
 3
 4
 1
 2
 5

奖励:无放回抽样

您还可以使用 StatsBase.sample() 从数组中采样相同的 length(X) 元素而不用替换:

julia> import StatsBase;

julia> StatsBase.sample(X, length(X), replace=false)
5-element Vector{Int64}:
 5
 2
 4
 1
 3

借用@niczky12 回答中的第二点,如果您想直接随机排列向量 X 那么实际上调用 shuffle!(X) 而不是 [=14 更有效=]:

# precompile @time
@time 1+1

# create random vector
p = 10_000
X = collect(1:p)

# reproducible shuffles
srand(2016)

shuffle(X)
@time shuffle(X)

shuffle!(X)
@time shuffle!(X)

我机器上的输出:

  0.000004 seconds (148 allocations: 10.151 KB)
  0.000331 seconds (6 allocations: 78.344 KB)
  0.000309 seconds (4 allocations: 160 bytes)

shuffle! 的调用分配的内存少得多(160 字节对 78 Kb),因此可以更好地扩展 p