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

[FIX] DataSampler: Fix crash when stratifying unbalanced datasets #1952

Merged
merged 2 commits into from
Jan 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
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
23 changes: 20 additions & 3 deletions Orange/widgets/data/owdatasampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ class OWDataSampler(OWWidget):
number_of_folds = Setting(10)
selectedFold = Setting(1)

class Warning(OWWidget.Warning):
could_not_stratify = Msg("Stratification failed\n{}")

class Error(OWWidget.Error):
too_many_folds = Msg("Number of folds exceeds data size")
sample_larger_than_data = Msg("Sample must be smaller than data")
Expand Down Expand Up @@ -252,10 +255,17 @@ def updateindices(self):
self.indices = None
return

rnd = self.RandomSeed if self.use_seed else None
stratified = (self.stratify and
type(self.data) == Table and
self.data.domain.has_discrete_class)
try:
self.indices = self.sample(data_length, size, stratified)
except ValueError as ex:
self.Warning.could_not_stratify(str(ex))
self.indices = self.sample(data_length, size, stratified=False)

def sample(self, data_length, size, stratified):
rnd = self.RandomSeed if self.use_seed else None
if self.sampling_type == self.FixedSize:
self.indice_gen = SampleRandomN(
size, stratified=stratified, replace=self.replacement,
Expand All @@ -268,7 +278,7 @@ def updateindices(self):
else:
self.indice_gen = SampleFoldIndices(
self.number_of_folds, stratified=stratified, random_state=rnd)
self.indices = self.indice_gen(self.data)
return self.indice_gen(self.data)

def send_report(self):
if self.sampling_type == self.FixedProportion:
Expand Down Expand Up @@ -375,7 +385,14 @@ def __init__(self, size=0, random_state=None):
self.size = size
self.random_state = random_state

def __call__(self):
def __call__(self, table=None):
"""Bootstrap indices

Args:
table: Not used (but part of the signature)
Returns:
tuple (out_of_sample, sample) indices
"""
rgen = np.random.RandomState(self.random_state)
sample = rgen.randint(0, self.size, self.size)
sample.sort() # not needed for the code below, just for the user
Expand Down
35 changes: 34 additions & 1 deletion Orange/widgets/data/tests/test_owdatasampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def setUpClass(cls):
cls.iris = Table("iris")

def setUp(self):
self.widget = self.create_widget(OWDataSampler)
self.widget = self.create_widget(OWDataSampler) # type: OWDataSampler
Copy link
Contributor

Choose a reason for hiding this comment

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

This is cool. It always annoys me, but I never thought of helping PyCharm here...

Copy link
Member Author

Choose a reason for hiding this comment

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

I saw this in tests aleš writes :)


def test_error_message(self):
""" Check if error message appears and then disappears when
Expand All @@ -26,3 +26,36 @@ def test_error_message(self):
self.assertFalse(self.widget.Error.too_many_folds.is_shown())
self.send_signal("Data", Table(self.iris.domain))
self.assertTrue(self.widget.Error.no_data.is_shown())

def test_stratified_on_unbalanced_data(self):
unbalanced_data = self.iris[:51]

self.widget.controls.stratify.setChecked(True)
self.send_signal("Data", unbalanced_data)
self.assertTrue(self.widget.Warning.could_not_stratify.is_shown())

def test_bootstrap(self):
self.select_sampling_type(self.widget.Bootstrap)

self.send_signal("Data", self.iris)

in_input = set(self.iris.ids)
sample = self.get_output("Data Sample")
in_sample = set(sample.ids)
in_remaining = set(self.get_output("Remaining Data").ids)

# Bootstrap should sample len(input) instances
self.assertEqual(len(sample), len(self.iris))
# Sample and remaining should cover all instances, while none
# should be present in both
self.assertEqual(len(in_sample | in_remaining), len(in_input))
self.assertEqual(len(in_sample & in_remaining), 0)
# Sampling with replacement will always produce at least one distinct
# instance in sample, and at least one instance in remaining with
# high probability (1-(1/150*2/150*...*150/150) ~= 1-2e-64)
self.assertGreater(len(in_sample), 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

Third, isn't len(in_sample) always at least 1? :)

Copy link
Member Author

Choose a reason for hiding this comment

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

It is, it is also stated in the comment above:
will always produce at least one distinct instance in sample
The high probability part refers to the second assertion
and at least one instance in remaining with high probability

self.assertGreater(len(in_remaining), 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't you use self.assertProbablyGreater here? :)


def select_sampling_type(self, sampling_type):
buttons = self.widget.controls.sampling_type.group.buttons()
buttons[sampling_type].click()