Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-4148][PySpark] fix seed distribution and add some tests for rdd.sample #3010

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests should be moved into tests.py, then the docstring will be much clearer.

"""
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