Skip to content

Commit

Permalink
fix seed distribution and add some tests for rdd.sample
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxr committed Oct 30, 2014
1 parent 51ce997 commit c1bacd9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
19 changes: 17 additions & 2 deletions python/pyspark/rdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,23 @@ def sample(self, withReplacement, fraction, seed=None):
Return a sampled subset of this RDD (relies on numpy and falls back
on default random generator if numpy is unavailable).
>>> sc.parallelize(range(0, 100)).sample(False, 0.1, 2).collect() #doctest: +SKIP
[2, 3, 20, 21, 24, 41, 42, 66, 67, 89, 90, 98]
>>> rdd = sc.parallelize(range(0, 100), 4)
>>> wo = rdd.sample(False, 0.1, 2).collect()
>>> wo_dup = rdd.sample(False, 0.1, 2).collect()
>>> set(wo) == set(wo_dup)
True
>>> wr = rdd.sample(True, 0.2, 5).collect()
>>> wr_dup = rdd.sample(True, 0.2, 5).collect()
>>> set(wr) == set(wr_dup)
True
>>> wo_s10 = rdd.sample(False, 0.3, 10).collect()
>>> wo_s20 = rdd.sample(False, 0.3, 20).collect()
>>> set(wo_s10) != set(wo_s20)
True
>>> wr_s11 = rdd.sample(True, 0.4, 11).collect()
>>> wr_s21 = rdd.sample(True, 0.4, 21).collect()
>>> set(wr_s11) != set(wr_s21)
True
"""
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True)
Expand Down
11 changes: 5 additions & 6 deletions python/pyspark/rddsampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,13 @@ def __init__(self, withReplacement, seed=None):
def initRandomGenerator(self, split):
if self._use_numpy:
import numpy
self._random = numpy.random.RandomState(self._seed)
self._random = numpy.random.RandomState(self._seed ^ split)
else:
self._random = random.Random(self._seed)
self._random = random.Random(self._seed ^ split)

for _ in range(0, split):
# discard the next few values in the sequence to have a
# different seed for the different splits
self._random.randint(0, 2 ** 32 - 1)
# mixing because the initial seeds are close to each other
for _ in xrange(10):
self._random.randint(0, 1)

self._split = split
self._rand_initialized = True
Expand Down

0 comments on commit c1bacd9

Please sign in to comment.