MCPcopy Create free account
hub / github.com/ddbourgin/numpy-ml / transform

Method transform

numpy_ml/preprocessing/general.py:86–117  ·  view source on GitHub ↗

Convert a list of labels into a one-hot encoding. Parameters ---------- labels : list of length `N` A list of category labels. categories : list of length `C` List of the unique category labels for the items to encode. Default

(self, labels, categories=None)

Source from the content-addressed store, hash-verified

84 self._is_fit = True
85
86 def transform(self, labels, categories=None):
87 """
88 Convert a list of labels into a one-hot encoding.
89
90 Parameters
91 ----------
92 labels : list of length `N`
93 A list of category labels.
94 categories : list of length `C`
95 List of the unique category labels for the items to encode. Default
96 is None.
97
98 Returns
99 -------
100 Y : :py:class:`ndarray <numpy.ndarray>` of shape `(N, C)`
101 The one-hot encoded labels. Each row corresponds to an example,
102 with a single 1 in the column corresponding to the respective
103 label.
104 """
105 if not self._is_fit:
106 categories = set(labels) if categories is None else categories
107 self.fit(categories)
108
109 unknown = list(set(labels) - set(self.cat2idx.keys()))
110 assert len(unknown) == 0, "Unrecognized label(s): {}".format(unknown)
111
112 N, C = len(labels), len(self.cat2idx)
113 cols = np.array([self.cat2idx[c] for c in labels])
114
115 Y = np.zeros((N, C))
116 Y[np.arange(N), cols] = 1
117 return Y
118
119 def inverse_transform(self, Y):
120 """

Callers 1

__call__Method · 0.95

Calls 1

fitMethod · 0.95

Tested by

no test coverage detected