scikit-learn/sklearn/preprocessing/_weights.py

26 lines
475 B
Python
Raw Normal View History

2013-07-29 00:45:20 +08:00
import numpy as np
def _balance_weights(y):
2013-07-29 00:45:20 +08:00
"""Compute sample weights such that the class distribution of y becomes
balanced.
Parameters
----------
y : array-like
Labels for the samples.
Returns
-------
weights : array-like
The sample weights.
"""
y = np.asarray(y)
2013-07-29 00:45:20 +08:00
y = np.searchsorted(np.unique(y), y)
bins = np.bincount(y)
weights = 1. / bins.take(y)
weights *= bins.min()
return weights