-
-
Notifications
You must be signed in to change notification settings - Fork 1k
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
[ENH] Correlations: Enhancements and fixes #3660
Merged
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ | |
""" | ||
from enum import IntEnum | ||
from operator import attrgetter | ||
from types import SimpleNamespace | ||
from itertools import combinations, groupby, chain | ||
|
||
import numpy as np | ||
|
@@ -45,17 +46,21 @@ def items(): | |
return ["Pearson correlation", "Spearman correlation"] | ||
|
||
|
||
class Cluster(SimpleNamespace): | ||
instances = None # type: Optional[List] | ||
centroid = None # type: Optional[np.ndarray] | ||
|
||
|
||
class KMeansCorrelationHeuristic: | ||
""" | ||
Heuristic to obtain the most promising attribute pairs, when there are to | ||
many attributes to calculate correlations for all possible pairs. | ||
""" | ||
n_clusters = 10 | ||
|
||
def __init__(self, data): | ||
self.n_attributes = len(data.domain.attributes) | ||
self.data = data | ||
self.states = None | ||
self.n_clusters = int(np.sqrt(self.n_attributes)) | ||
|
||
def get_clusters_of_attributes(self): | ||
""" | ||
|
@@ -67,22 +72,39 @@ def get_clusters_of_attributes(self): | |
data = Normalize()(self.data).X.T | ||
kmeans = KMeans(n_clusters=self.n_clusters, random_state=0).fit(data) | ||
labels_attrs = sorted([(l, i) for i, l in enumerate(kmeans.labels_)]) | ||
for _, group in groupby(labels_attrs, key=lambda x: x[0]): | ||
group = list(group) | ||
if len(group) > 1: | ||
yield list(pair[1] for pair in group) | ||
return [Cluster(instances=list(pair[1] for pair in group), | ||
centroid=kmeans.cluster_centers_[l]) | ||
for l, group in groupby(labels_attrs, key=lambda x: x[0])] | ||
janezd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def get_states(self, initial_state): | ||
""" | ||
Generates the most promising states (attribute pairs). | ||
Generates states (attribute pairs) - the most promising first, i.e. | ||
states within clusters, following by states among clusters. | ||
|
||
:param initial_state: initial state; None if this is the first call | ||
:return: generator of tuples of states | ||
""" | ||
if self.states is not None: | ||
return chain([initial_state], self.states) | ||
self.states = chain.from_iterable(combinations(inds, 2) for inds in | ||
self.get_clusters_of_attributes()) | ||
|
||
clusters = self.get_clusters_of_attributes() | ||
|
||
# combinations within clusters | ||
self.states = chain.from_iterable(combinations(cluster.instances, 2) | ||
for cluster in clusters) | ||
if self.n_clusters == 1: | ||
return self.states | ||
|
||
# combinations among clusters - closest clusters first | ||
centroids = [c.centroid for c in clusters] | ||
centroids_combs = np.array(list(combinations(centroids, 2))) | ||
distances = np.linalg.norm((centroids_combs[:, 0] - | ||
centroids_combs[:, 1]), axis=1) | ||
cluster_combs = list(combinations(range(len(clusters)), 2)) | ||
states = ((min((c1, c2)), max((c1, c2))) for i in np.argsort(distances) | ||
for c1 in clusters[cluster_combs[i][0]].instances | ||
for c2 in clusters[cluster_combs[i][1]].instances) | ||
self.states = chain(self.states, states) | ||
return self.states | ||
|
||
|
||
|
@@ -112,11 +134,8 @@ def initialize(self): | |
self.sel_feature_index = None | ||
if data: | ||
# use heuristic if data is too big | ||
n_attrs = len(self.attrs) | ||
use_heuristic = n_attrs > KMeansCorrelationHeuristic.n_clusters | ||
self.use_heuristic = use_heuristic and \ | ||
len(data) * n_attrs ** 2 > SIZE_LIMIT and \ | ||
self.sel_feature_index is None | ||
self.use_heuristic = len(data) * len(self.attrs) ** 2 > SIZE_LIMIT \ | ||
and self.sel_feature_index is None | ||
if self.use_heuristic: | ||
self.heuristic = KMeansCorrelationHeuristic(data) | ||
|
||
|
@@ -161,15 +180,8 @@ def iterate_states_by_feature(self): | |
yield self.sel_feature_index, j | ||
|
||
def state_count(self): | ||
if self.sel_feature_index is not None: | ||
return len(self.attrs) - 1 | ||
elif self.use_heuristic: | ||
n_clusters = KMeansCorrelationHeuristic.n_clusters | ||
n_avg_attrs = len(self.attrs) / n_clusters | ||
return n_clusters * n_avg_attrs * (n_avg_attrs - 1) / 2 | ||
else: | ||
n_attrs = len(self.attrs) | ||
return n_attrs * (n_attrs - 1) / 2 | ||
n = len(self.attrs) | ||
return n * (n - 1) / 2 if self.sel_feature_index is None else n - 1 | ||
|
||
@staticmethod | ||
def bar_length(score): | ||
|
@@ -206,9 +218,11 @@ class Outputs: | |
correlation_type = Setting(0) | ||
|
||
class Information(OWWidget.Information): | ||
removed_cons_feat = Msg("Constant features have been removed.") | ||
|
||
class Warning(OWWidget.Warning): | ||
not_enough_vars = Msg("Need at least two continuous features.") | ||
not_enough_inst = Msg("Need at least two instances.") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we make these messages proper sentences? |
||
removed_cons_feat = Msg("Constant features have been removed.") | ||
|
||
def __init__(self): | ||
super().__init__() | ||
|
@@ -223,9 +237,8 @@ def __init__(self): | |
) | ||
|
||
self.feature_model = DomainModel( | ||
separators=False, placeholder="(All combinations)", | ||
valid_types=ContinuousVariable, | ||
) | ||
order=DomainModel.ATTRIBUTES, separators=False, | ||
placeholder="(All combinations)", valid_types=ContinuousVariable) | ||
gui.comboBox( | ||
box, self, "feature", callback=self._feature_combo_changed, | ||
model=self.feature_model | ||
|
@@ -296,7 +309,7 @@ def set_data(self, data): | |
self.selection = () | ||
if data is not None: | ||
if len(data) < 2: | ||
self.Information.not_enough_inst() | ||
self.Warning.not_enough_inst() | ||
else: | ||
domain = data.domain | ||
cont_attrs = [a for a in domain.attributes if a.is_continuous] | ||
|
@@ -307,7 +320,7 @@ def set_data(self, data): | |
if remover.attr_results["removed"]: | ||
self.Information.removed_cons_feat() | ||
if len(cont_data.domain.attributes) < 2: | ||
self.Information.not_enough_vars() | ||
self.Warning.not_enough_vars() | ||
else: | ||
self.cont_data = SklImpute()(cont_data) | ||
self.set_feature_model() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
to -> too
(not important, skip if you don't make any other, substantial changes)