Skip to content

Commit

Permalink
Fix for balanced class weight (#1080)
Browse files Browse the repository at this point in the history
* add balanced branch of _compute_class_weight

* Remove extra computation of weights
  • Loading branch information
Alexsandruss authored and napetrov committed Dec 15, 2022
1 parent 958c519 commit 4872a8e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
11 changes: 10 additions & 1 deletion onedal/datatypes/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import warnings
from scipy import sparse as sp
from scipy.sparse import issparse, dok_matrix, lil_matrix
from sklearn.preprocessing import LabelEncoder
from collections.abc import Sequence
from numbers import Integral

Expand Down Expand Up @@ -57,7 +58,15 @@ def _compute_class_weight(class_weight, classes, y):
if class_weight is None or len(class_weight) == 0:
weight = np.ones(classes.shape[0], dtype=np.float64, order='C')
elif class_weight == 'balanced':
weight = None
y_ = _column_or_1d(y)
classes, _ = np.unique(y_, return_inverse=True)

le = LabelEncoder()
y_ind = le.fit_transform(y_)
if not all(np.in1d(classes, le.classes_)):
raise ValueError("classes should have valid labels that are in y")

weight = len(y_) / (len(le.classes_) * np.bincount(y_ind).astype(np.float64))
else:
# user-defined dictionary
weight = np.ones(classes.shape[0], dtype=np.float64, order='C')
Expand Down
6 changes: 1 addition & 5 deletions sklearnex/svm/nusvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,7 @@ def _onedal_fit(self, X, y, sample_weight=None, queue=None):

self._onedal_estimator = onedal_NuSVC(**onedal_params)
self._onedal_estimator.fit(X, y, sample_weight, queue=queue)

if self.class_weight == 'balanced':
self.class_weight_ = self._compute_balanced_class_weight(y)
else:
self.class_weight_ = self._onedal_estimator.class_weight_
self.class_weight_ = self._onedal_estimator.class_weight_

if self.probability:
self._fit_proba(X, y, sample_weight, queue=queue)
Expand Down
6 changes: 1 addition & 5 deletions sklearnex/svm/svc.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,7 @@ def _onedal_fit(self, X, y, sample_weight=None, queue=None):

self._onedal_estimator = onedal_SVC(**onedal_params)
self._onedal_estimator.fit(X, y, sample_weight, queue=queue)

if self.class_weight == 'balanced':
self.class_weight_ = self._compute_balanced_class_weight(y)
else:
self.class_weight_ = self._onedal_estimator.class_weight_
self.class_weight_ = self._onedal_estimator.class_weight_

if self.probability:
self._fit_proba(X, y, sample_weight, queue=queue)
Expand Down

0 comments on commit 4872a8e

Please sign in to comment.