7

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

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

返回的错误是: ERROR: MethodError: no method matching randperm(::Array{Float64,1}) in eval(::Module, ::Any) at ./boot.jl:237

谢谢

4

2 回答 2

14

利用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

如果您不想分配新向量,但想就地洗牌,您可以使用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
于 2016-06-24T09:45:43.203 回答
2

要搭载@niczky12 回答中的第二点,如果您想X直接随机置换向量,那么调用shuffle!(X)而不是调用实际上更有效shuffle(X)

# 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 字节 v. 78 Kb),因此使用p.

于 2016-06-25T18:14:11.620 回答