从Julia中的数组中采样行 [英] Sample rows from an array in Julia

查看:129
本文介绍了从Julia中的数组中采样行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从一维数组中采样.例如

I can sample from a 1-D array just fine. E.g.

julia> a = [1; 2; 3]
3-element Array{Int64,1}:
 1
 2
 3
julia> sample(a, myweights, 5)
5-element Array{Int64,1}:
 1
 2
 1
 3
 3

我也可以采集加权样本:

I can also take weighted samples:

julia> myweights = weights([0.8, 0.1, 0.1])
StatsBase.WeightVec{Float64,Array{Float64,1}}([0.8,0.1,0.1],1.0)

julia> sample(a, myweights, 5)
5-element Array{Int64,1}:
 2
 1
 1
 1
 1

我想对2D数组执行相同的操作,但是按行而不是按元素进行采样.例如.如果我有数组

I'd like to do the same thing for a 2D array, but sampling by row and not by element. E.g. if I have the array

julia> b = [1 1 1; 2 2 2; 3 3 3]
3×3 Array{Int64,2}:
 1  1  1
 2  2  2
 3  3  3

我希望能够获取未加权和加权的样本,这些样本可以为我提供类似的输出

I'd like to be able to take unweighted and weighted samples that give me outputs like

 1  1  1
 2  2  2
 1  1  1
 1  1  1
 3  3  3

我该怎么做?

推荐答案

这里最简单的解决方案是从行的索引中采样,然后使用它来索引矩阵:

The simplest solution here is to sample from the indices of the rows, and then use that to index into your matrix:

julia> idxs = sample(indices(b, 1), myweights, 10)
10-element Array{Int64,1}:
 1
 1
 1
 2
 1
 1
 3
 1
 1
 1

julia> b[idxs, :]
10×3 Array{Int64,2}:
 1  1  1
 1  1  1
 1  1  1
 2  2  2
 1  1  1
 1  1  1
 3  3  3
 1  1  1
 1  1  1
 1  1  1

这篇关于从Julia中的数组中采样行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆