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] Fixing Issue #3550 - hard clamping. #3751

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 13 additions & 6 deletions sklearn/semi_supervised/label_propagation.py
Expand Up @@ -110,6 +110,7 @@ def __init__(self, kernel='rbf', gamma=20, n_neighbors=7,
self.n_neighbors = n_neighbors

# clamping factor
# alpha should be between 0 and 1
self.alpha = alpha

def _get_kernel(self, X, y=None):
Expand All @@ -121,6 +122,7 @@ def _get_kernel(self, X, y=None):
elif self.kernel == "knn":
if self.nn_fit is None:
self.nn_fit = NearestNeighbors(self.n_neighbors).fit(X)

if y is None:
return self.nn_fit.kneighbors_graph(self.nn_fit._fit_X,
self.n_neighbors,
Expand Down Expand Up @@ -222,19 +224,20 @@ def fit(self, X, y):

y = np.asarray(y)
unlabeled = y == -1
labeled = y != -1
clamp_weights = np.ones((n_samples, 1))
clamp_weights[unlabeled, 0] = self.alpha
clamp_weights[labeled, 0] = 1 - self.alpha

# initialize distributions
self.label_distributions_ = np.zeros((n_samples, n_classes))
for label in classes:
self.label_distributions_[y == label, classes == label] = 1

y_static = np.copy(self.label_distributions_)
if self.alpha > 0.:
y_static *= 1 - self.alpha
y_static[unlabeled] = 0
if self.alpha >= 0.:
y_static *= self.alpha

y_static[unlabeled] = 0
l_previous = np.zeros((self.X_.shape[0], n_classes))

remaining_iter = self.max_iter
Expand All @@ -245,6 +248,11 @@ def fit(self, X, y):
l_previous = self.label_distributions_
self.label_distributions_ = safe_sparse_dot(
graph_matrix, self.label_distributions_)

normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis]
normalizer[normalizer == 0] = 1
self.label_distributions_ /= normalizer

# clamp
self.label_distributions_ = np.multiply(
clamp_weights, self.label_distributions_) + y_static
Expand Down Expand Up @@ -420,8 +428,7 @@ def _build_graph(self):
self.nn_fit = None
n_samples = self.X_.shape[0]
affinity_matrix = self._get_kernel(self.X_)
laplacian = graph_laplacian(affinity_matrix, normed=True)
laplacian = -laplacian
laplacian = -graph_laplacian(affinity_matrix, normed=True)
if sparse.isspmatrix(laplacian):
diag_mask = (laplacian.row == laplacian.col)
laplacian.data[diag_mask] = 0.0
Expand Down