def __init__(self, probs, labels=None): """The discrete individual perturbation to a feature variable. Parameters ---------- probs: np.ndarray the probabilities to change from a value of a category to another value. """ self._initialization() self.basecoreperturbation = BaseCoreSubstitutionArray(probs, labels)
class DiscreteIndPerturbation(BasePerturbation): """Discrete perturbation of a discrete feature variable.""" _categorytype = "feature" _perturbtype = "discrete" def __init__(self, probs, labels=None): """The discrete individual perturbation to a feature variable. Parameters ---------- probs: np.ndarray the probabilities to change from a value of a category to another value. """ self._initialization() self.basecoreperturbation = BaseCoreSubstitutionArray(probs, labels) # if np.all(probs.sum(1) != 1): # raise TypeError("Not correct probs input.") # if probs.shape[0] != probs.shape[1]: # raise IndexError("Probs is noot a square matrix.") # self.probs = probs.cumsum(1) # self.labels = np.arange(len(probs)) if labels is None else labels def apply2features(self, feature, k=None): """Apply perturbation to features. Parameters ---------- features: np.ndarray or others the element features collection to be perturbed. k: int (default=None) the perturbation indices. Returns ------- features: np.ndarray or others the element features collection perturbated. """ ## Prepare inputs # categories = np.unique(feature) # if len(categories) > len(self.probs): # msg = "Not matching dimension between probs and features." # raise IndexError(msg) k = self._format_k_perturb(k) logi_int = check_int(k) if logi_int: k = [k] if len(feature.shape) == 1: feature = feature.reshape((len(feature), 1)) ## Compute each change features_p = self.basecoreperturbation.apply(feature, k) # features_p = np.zeros((len(feature), 1, len(k))) # for i_k in k: # for i in xrange(len(feature)): # r = np.random.random() # idx = np.where(feature[i] == self.labels)[0] # idx2 = np.where(self.probs[idx] > r)[0][0] # features_p[i, 0, i_k] = self.labels[idx2] if logi_int: features_p = features_p[:, :, 0] return features_p