Github user falaki commented on a diff in the pull request:
https://github.com/apache/spark/pull/1025#discussion_r14542021
--- Diff: core/src/main/scala/org/apache/spark/rdd/PairRDDFunctions.scala
---
@@ -195,6 +193,40 @@ class PairRDDFunctions[K, V](self: RDD[(K, V)])
}
/**
+ * Return a subset of this RDD sampled by key (via stratified sampling).
+ *
+ * If exact set to true, we guarantee, with high probability, a sample
size =
+ * math.ceil(fraction * S_i), where S_i is the size of the ith stratum
(collection of entries
+ * that share the same key). When sampling without replacement, we need
one additional pass over
+ * the RDD to guarantee sample size with a 99.99% confidence; when
sampling with replacement, we
+ * need two additional passes.
+ *
+ * @param withReplacement whether to sample with or without replacement
+ * @param fractions map of specific keys to sampling rates
+ * @param seed seed for the random number generator
+ * @param exact whether sample size needs to be exactly
math.ceil(fraction * size) per stratum
+ * @return RDD containing the sampled subset
+ */
+ def sampleByKey(withReplacement: Boolean,
+ fractions: Map[K, Double],
+ exact: Boolean = true,
+ seed: Long = Utils.random.nextLong): RDD[(K, V)]= {
+
+ require(fractions.forall({case(k, v) => v >= 0.0}), "Invalid sampling
rates.")
+
+ if (withReplacement) {
--- End diff --
This can be written more functional (and readable) like this:
```scala
val samplingFunc = if (withReplacement) {
val counts = if (exact) Some(this.countByKey()) else None
StratifiedSampler.getPoissonSamplingFunction(self, fractions,
exact, counts, seed)
} else {
StratifiedSampler.getBernoulliSamplingFunction(self, fractions,
exact, seed)
}
self.mapPartitionsWithIndex(samplingFunc, preservesPartitioning = true)
```
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---