takeSample
返回一个Array[T];
该方法仅在预期结果数组很小的情况下使用,因为所有数据都被加载到driver的内存中。
源码
def takeSample(
withReplacement: Boolean,
num: Int,
seed: Long = Utils.random.nextLong): Array[T] = withScope {...}
withReplacement:元素可以多次抽样(在抽样时替换)
num:返回的样本的大小
seed:随机数生成器的种子(因为不好把控,建议不写默认)
(1)当不可以多次抽样:withReplacement=false;样本个数num大于父本个数时,只能返回父本个数
scala> val a = sc.parallelize(Array(2,5,6,8,9))
a: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[79] at parallelize at <console>:24
scala> a.takeSample(false,8)
res41: Array[Int] = Array(8, 5, 6, 2, 9)
(2)当不可以多次抽样:withReplacement=false;样本个数num小于父本个数时,返回样本个数
scala> a.takeSample(false,3)
res42: Array[Int] = Array(6, 8, 9)
(3)当可以多次抽样:withReplacement=true;样本个数num大于父本个数时,返回样本个数
scala> a.takeSample(true,10)
res43: Array[Int] = Array(9, 9, 9, 5, 2, 2, 8, 2, 8, 6)
(4)当可以多次抽样:withReplacement=true;样本个数num小于父本个数时,返回样本个数
scala> a.takeSample(true,3)
res44: Array[Int] = Array(5, 8, 2)