|
| 1 | +from itertools import combinations |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +from sklearn.utils.validation import (as_float_array, assert_all_finite, |
| 5 | + check_X_y, column_or_1d, indexable) |
| 6 | + |
| 7 | + |
| 8 | +def group_by(X, y, *, category_orders=None, operation=lambda x: x.mean(axis=0)): |
| 9 | + """Groups the samples in X by labels in y and applies `operation` |
| 10 | + to the aggregated groups. |
| 11 | +
|
| 12 | + Parameters |
| 13 | + __________ |
| 14 | + X: array-like of shape (n_samples, n_features) |
| 15 | + The data matrix. |
| 16 | + y: array-like of shape (n_samples,) |
| 17 | + The class labels. |
| 18 | + category_orders: array-like of shape (np.unique(y).size,) |
| 19 | + Order of class labels to use when constructing the matrix. |
| 20 | + If None, will sort the class labels alphabetically. |
| 21 | + operation: callable |
| 22 | + The function to apply to the aggregated groups. |
| 23 | + """ |
| 24 | + X, y = check_X_y(X, y, accept_sparse=["csr"]) |
| 25 | + X = indexable(X)[0] |
| 26 | + |
| 27 | + if category_orders is None: |
| 28 | + category_orders = np.unique(y) |
| 29 | + elif not set(category_orders).issubset(set(y)): |
| 30 | + # To avoid getting nan values |
| 31 | + raise ValueError("Found categories not present in `y`.") |
| 32 | + else: |
| 33 | + category_orders = column_or_1d(category_orders) |
| 34 | + |
| 35 | + if not callable(operation): |
| 36 | + raise ValueError("Please pass a callable operation.") |
| 37 | + |
| 38 | + M = np.zeros((len(category_orders), X.shape[1])) |
| 39 | + |
| 40 | + for i, category in enumerate(category_orders): |
| 41 | + _agg_values = operation(X[y == category]) |
| 42 | + _agg_values = as_float_array(_agg_values).flatten() |
| 43 | + if len(_agg_values) != X.shape[1]: |
| 44 | + raise ValueError( |
| 45 | + "Operation must return a vector of size X.shape[1]" |
| 46 | + f"but instead found vector of size {len(_agg_values)}." |
| 47 | + ) |
| 48 | + assert_all_finite(_agg_values) |
| 49 | + M[i] = _agg_values |
| 50 | + |
| 51 | + return M |
| 52 | + |
| 53 | + |
| 54 | +def pairwise_differences( |
| 55 | + X, y, |
| 56 | + *, |
| 57 | + classes=None, |
| 58 | + ordered=False, |
| 59 | + operation=lambda x: x.mean(axis=0)): |
| 60 | + """ |
| 61 | + Given an data matrix X, if ordered is False, construct a matrix P of shape |
| 62 | + (n * (n-1) / 2, X.shape[1]) where n is the number of classes in y. |
| 63 | + The (i*j, g) entry of P corresponds to the average expression of feature g |
| 64 | + in group i - average expression of feature g in group j, in absolute value. |
| 65 | + If ordered is True, the shape of P will be (n * (n-1), X.shape[1]) and |
| 66 | + the pairwise distances will be clipped at 0. |
| 67 | +
|
| 68 | + Returns P and a dictionary of mappings: label, label -> index. |
| 69 | +
|
| 70 | + Parameters |
| 71 | + _________ |
| 72 | + X: np.ndarray of shape (n_samples, n_features) |
| 73 | + y: np.ndarray of shape (n_samples,) |
| 74 | + classes: np.ndarray or None, unique class labels in y |
| 75 | + ordered: bool, if True will construct a matrix of ordered |
| 76 | + pairwise differences. In this case the shape of P is |
| 77 | + (n * (n-1), X.shape[1]). |
| 78 | + operation: callable, operation to use when constructing the class vector. |
| 79 | + """ |
| 80 | + if classes is None: |
| 81 | + classes = np.unique(y) |
| 82 | + |
| 83 | + n_classes = len(classes) |
| 84 | + # All pairwise combinations |
| 85 | + n_class_pairs = n_classes * (n_classes - 1) // 2 |
| 86 | + |
| 87 | + # Cache the average vector of each class |
| 88 | + class_averages = group_by( |
| 89 | + X, y, category_orders=classes, operation=operation) |
| 90 | + |
| 91 | + # Compute the actual pairwise differences |
| 92 | + P = np.zeros((n_class_pairs * (1 if not ordered else 2), X.shape[1])) |
| 93 | + index_to_pair_dict = {} |
| 94 | + |
| 95 | + # Make sure to use range(n_classes) when indexing instead of classes, |
| 96 | + # to allow for arbitrary class labels. |
| 97 | + for index, (i, j) in enumerate(combinations(range(n_classes), 2)): |
| 98 | + difference = class_averages[i] - class_averages[j] |
| 99 | + if ordered: |
| 100 | + # Clip negative values to 0 |
| 101 | + # Assign i - j to index and j - i to index + n_class_pairs |
| 102 | + P[index] = np.clip(difference, 0, None) |
| 103 | + index_to_pair_dict[index] = (i, j) |
| 104 | + P[index + n_class_pairs] = np.clip(-difference, 0, None) |
| 105 | + index_to_pair_dict[index + n_class_pairs] = (j, i) |
| 106 | + else: |
| 107 | + P[index] = np.abs(difference) |
| 108 | + index_to_pair_dict[index] = (i, j) |
| 109 | + |
| 110 | + return P, index_to_pair_dict |
0 commit comments