diff --git a/02_end_to_end_machine_learning_project.ipynb b/02_end_to_end_machine_learning_project.ipynb index 2eed4e3..8510a6d 100644 --- a/02_end_to_end_machine_learning_project.ipynb +++ b/02_end_to_end_machine_learning_project.ipynb @@ -790,7 +790,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing_cat = housing['ocean_proximity']\n", + "housing_cat = housing[['ocean_proximity']]\n", "housing_cat.head(10)" ] }, @@ -798,7 +798,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can use Pandas' `factorize()` method to convert this string categorical feature to an integer categorical feature, which will be easier for Machine Learning algorithms to handle:" + "**Warning**: earlier versions of the book used the `LabelEncoder` class or Pandas' `Series.factorize()` method instead of the `OrdinalEncoder` class (available since Scikit-Learn 0.20). It is preferable to use the `OrdinalEncoder` class, since it is designed for input features (instead of labels) and it plays well with pipelines, as we will see later in this notebook. Similarly, earlier version of the book used the `LabelBinarizer` class or the `CategoricalEncoder` class for one-hot encoding (which we will look at shortly), but since Scikit-Learn 0.20 it is preferable to use the `OneHotEncoder` class. If you are using an older version of Scikit-Learn, please consider upgrading (in case you want to stick to an old version of Scikit-Learn, the new `OrdinalEncoder` and `OneHotEncoder` classes are provided in the `future_encoders.py` file)." ] }, { @@ -807,8 +807,10 @@ "metadata": {}, "outputs": [], "source": [ - "housing_cat_encoded, housing_categories = housing_cat.factorize()\n", - "housing_cat_encoded[:10]" + "try:\n", + " from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder\n", + "except ImportError:\n", + " from future_encoders import OrdinalEncoder, OneHotEncoder" ] }, { @@ -817,21 +819,9 @@ "metadata": {}, "outputs": [], "source": [ - "housing_categories" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Warning**: earlier versions of the book used the `LabelEncoder` class instead of Pandas' `factorize()` method. This was incorrect: indeed, as its name suggests, the `LabelEncoder` class was designed for labels, not for input features. The code worked because we were handling a single categorical input feature, but it would break if you passed multiple categorical input features." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can convert each categorical value to a one-hot vector using a `OneHotEncoder`:" + "ordinal_encoder = OrdinalEncoder()\n", + "housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)\n", + "housing_cat_encoded[:10]" ] }, { @@ -840,18 +830,14 @@ "metadata": {}, "outputs": [], "source": [ - "from sklearn.preprocessing import OneHotEncoder\n", - "\n", - "encoder = OneHotEncoder()\n", - "housing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))\n", - "housing_cat_1hot" + "ordinal_encoder.categories_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "The `OneHotEncoder` returns a sparse array by default, but we can convert it to a dense array if needed:" + "We can convert each categorical value to a one-hot vector using a `OneHotEncoder`. Prior to Scikit-Learn 0.20, this class could only handle integer categorical inputs. Now it can also handle string categorical inputs:" ] }, { @@ -860,14 +846,16 @@ "metadata": {}, "outputs": [], "source": [ - "housing_cat_1hot.toarray()" + "cat_encoder = OneHotEncoder()\n", + "housing_cat_1hot = cat_encoder.fit_transform(housing_cat)\n", + "housing_cat_1hot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "**Warning**: earlier versions of the book used the `LabelBinarizer` class at this point. Again, this was incorrect: just like the `LabelEncoder` class, the `LabelBinarizer` class was designed to preprocess labels, not input features. A better solution is to use Scikit-Learn's upcoming `CategoricalEncoder` class: it will soon be added to Scikit-Learn, and in the meantime you can use the code below (copied from [Pull Request #9151](https://github.com/scikit-learn/scikit-learn/pull/9151))." + "By default, the `OneHotEncoder` class returns a sparse array, but we can convert it to a dense array if needed by calling the `toarray()` method:" ] }, { @@ -876,199 +864,14 @@ "metadata": {}, "outputs": [], "source": [ - "# Definition of the CategoricalEncoder class, copied from PR #9151.\n", - "# Just run this cell, or copy it to your code, do not try to understand it (yet).\n", - "\n", - "from sklearn.base import BaseEstimator, TransformerMixin\n", - "from sklearn.utils import check_array\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from scipy import sparse\n", - "\n", - "class CategoricalEncoder(BaseEstimator, TransformerMixin):\n", - " \"\"\"Encode categorical features as a numeric array.\n", - " The input to this transformer should be a matrix of integers or strings,\n", - " denoting the values taken on by categorical (discrete) features.\n", - " The features can be encoded using a one-hot aka one-of-K scheme\n", - " (``encoding='onehot'``, the default) or converted to ordinal integers\n", - " (``encoding='ordinal'``).\n", - " This encoding is needed for feeding categorical data to many scikit-learn\n", - " estimators, notably linear models and SVMs with the standard kernels.\n", - " Read more in the :ref:`User Guide `.\n", - " Parameters\n", - " ----------\n", - " encoding : str, 'onehot', 'onehot-dense' or 'ordinal'\n", - " The type of encoding to use (default is 'onehot'):\n", - " - 'onehot': encode the features using a one-hot aka one-of-K scheme\n", - " (or also called 'dummy' encoding). This creates a binary column for\n", - " each category and returns a sparse matrix.\n", - " - 'onehot-dense': the same as 'onehot' but returns a dense array\n", - " instead of a sparse matrix.\n", - " - 'ordinal': encode the features as ordinal integers. This results in\n", - " a single column of integers (0 to n_categories - 1) per feature.\n", - " categories : 'auto' or a list of lists/arrays of values.\n", - " Categories (unique values) per feature:\n", - " - 'auto' : Determine categories automatically from the training data.\n", - " - list : ``categories[i]`` holds the categories expected in the ith\n", - " column. The passed categories are sorted before encoding the data\n", - " (used categories can be found in the ``categories_`` attribute).\n", - " dtype : number type, default np.float64\n", - " Desired dtype of output.\n", - " handle_unknown : 'error' (default) or 'ignore'\n", - " Whether to raise an error or ignore if a unknown categorical feature is\n", - " present during transform (default is to raise). When this is parameter\n", - " is set to 'ignore' and an unknown category is encountered during\n", - " transform, the resulting one-hot encoded columns for this feature\n", - " will be all zeros.\n", - " Ignoring unknown categories is not supported for\n", - " ``encoding='ordinal'``.\n", - " Attributes\n", - " ----------\n", - " categories_ : list of arrays\n", - " The categories of each feature determined during fitting. When\n", - " categories were specified manually, this holds the sorted categories\n", - " (in order corresponding with output of `transform`).\n", - " Examples\n", - " --------\n", - " Given a dataset with three features and two samples, we let the encoder\n", - " find the maximum value per feature and transform the data to a binary\n", - " one-hot encoding.\n", - " >>> from sklearn.preprocessing import CategoricalEncoder\n", - " >>> enc = CategoricalEncoder(handle_unknown='ignore')\n", - " >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])\n", - " ... # doctest: +ELLIPSIS\n", - " CategoricalEncoder(categories='auto', dtype=<... 'numpy.float64'>,\n", - " encoding='onehot', handle_unknown='ignore')\n", - " >>> enc.transform([[0, 1, 1], [1, 0, 4]]).toarray()\n", - " array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.],\n", - " [ 0., 1., 1., 0., 0., 0., 0., 0., 0.]])\n", - " See also\n", - " --------\n", - " sklearn.preprocessing.OneHotEncoder : performs a one-hot encoding of\n", - " integer ordinal features. The ``OneHotEncoder assumes`` that input\n", - " features take on values in the range ``[0, max(feature)]`` instead of\n", - " using the unique values.\n", - " sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of\n", - " dictionary items (also handles string-valued features).\n", - " sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot\n", - " encoding of dictionary items or strings.\n", - " \"\"\"\n", - "\n", - " def __init__(self, encoding='onehot', categories='auto', dtype=np.float64,\n", - " handle_unknown='error'):\n", - " self.encoding = encoding\n", - " self.categories = categories\n", - " self.dtype = dtype\n", - " self.handle_unknown = handle_unknown\n", - "\n", - " def fit(self, X, y=None):\n", - " \"\"\"Fit the CategoricalEncoder to X.\n", - " Parameters\n", - " ----------\n", - " X : array-like, shape [n_samples, n_feature]\n", - " The data to determine the categories of each feature.\n", - " Returns\n", - " -------\n", - " self\n", - " \"\"\"\n", - "\n", - " if self.encoding not in ['onehot', 'onehot-dense', 'ordinal']:\n", - " template = (\"encoding should be either 'onehot', 'onehot-dense' \"\n", - " \"or 'ordinal', got %s\")\n", - " raise ValueError(template % self.handle_unknown)\n", - "\n", - " if self.handle_unknown not in ['error', 'ignore']:\n", - " template = (\"handle_unknown should be either 'error' or \"\n", - " \"'ignore', got %s\")\n", - " raise ValueError(template % self.handle_unknown)\n", - "\n", - " if self.encoding == 'ordinal' and self.handle_unknown == 'ignore':\n", - " raise ValueError(\"handle_unknown='ignore' is not supported for\"\n", - " \" encoding='ordinal'\")\n", - "\n", - " X = check_array(X, dtype=np.object, accept_sparse='csc', copy=True)\n", - " n_samples, n_features = X.shape\n", - "\n", - " self._label_encoders_ = [LabelEncoder() for _ in range(n_features)]\n", - "\n", - " for i in range(n_features):\n", - " le = self._label_encoders_[i]\n", - " Xi = X[:, i]\n", - " if self.categories == 'auto':\n", - " le.fit(Xi)\n", - " else:\n", - " valid_mask = np.in1d(Xi, self.categories[i])\n", - " if not np.all(valid_mask):\n", - " if self.handle_unknown == 'error':\n", - " diff = np.unique(Xi[~valid_mask])\n", - " msg = (\"Found unknown categories {0} in column {1}\"\n", - " \" during fit\".format(diff, i))\n", - " raise ValueError(msg)\n", - " le.classes_ = np.array(np.sort(self.categories[i]))\n", - "\n", - " self.categories_ = [le.classes_ for le in self._label_encoders_]\n", - "\n", - " return self\n", - "\n", - " def transform(self, X):\n", - " \"\"\"Transform X using one-hot encoding.\n", - " Parameters\n", - " ----------\n", - " X : array-like, shape [n_samples, n_features]\n", - " The data to encode.\n", - " Returns\n", - " -------\n", - " X_out : sparse matrix or a 2-d array\n", - " Transformed input.\n", - " \"\"\"\n", - " X = check_array(X, accept_sparse='csc', dtype=np.object, copy=True)\n", - " n_samples, n_features = X.shape\n", - " X_int = np.zeros_like(X, dtype=np.int)\n", - " X_mask = np.ones_like(X, dtype=np.bool)\n", - "\n", - " for i in range(n_features):\n", - " valid_mask = np.in1d(X[:, i], self.categories_[i])\n", - "\n", - " if not np.all(valid_mask):\n", - " if self.handle_unknown == 'error':\n", - " diff = np.unique(X[~valid_mask, i])\n", - " msg = (\"Found unknown categories {0} in column {1}\"\n", - " \" during transform\".format(diff, i))\n", - " raise ValueError(msg)\n", - " else:\n", - " # Set the problematic rows to an acceptable value and\n", - " # continue `The rows are marked `X_mask` and will be\n", - " # removed later.\n", - " X_mask[:, i] = valid_mask\n", - " X[:, i][~valid_mask] = self.categories_[i][0]\n", - " X_int[:, i] = self._label_encoders_[i].transform(X[:, i])\n", - "\n", - " if self.encoding == 'ordinal':\n", - " return X_int.astype(self.dtype, copy=False)\n", - "\n", - " mask = X_mask.ravel()\n", - " n_values = [cats.shape[0] for cats in self.categories_]\n", - " n_values = np.array([0] + n_values)\n", - " indices = np.cumsum(n_values)\n", - "\n", - " column_indices = (X_int + indices[:-1]).ravel()[mask]\n", - " row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),\n", - " n_features)[mask]\n", - " data = np.ones(n_samples * n_features)[mask]\n", - "\n", - " out = sparse.csc_matrix((data, (row_indices, column_indices)),\n", - " shape=(n_samples, indices[-1]),\n", - " dtype=self.dtype).tocsr()\n", - " if self.encoding == 'onehot-dense':\n", - " return out.toarray()\n", - " else:\n", - " return out" + "housing_cat_1hot.toarray()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "The `CategoricalEncoder` expects a 2D array containing one or more categorical input features. We need to reshape `housing_cat` to a 2D array:" + "Alternatively, you can set `sparse=False` when creating the `OneHotEncoder`:" ] }, { @@ -1077,53 +880,16 @@ "metadata": {}, "outputs": [], "source": [ - "#from sklearn.preprocessing import CategoricalEncoder # in future versions of Scikit-Learn\n", - "\n", - "cat_encoder = CategoricalEncoder()\n", - "housing_cat_reshaped = housing_cat.values.reshape(-1, 1)\n", - "housing_cat_1hot = cat_encoder.fit_transform(housing_cat_reshaped)\n", + "cat_encoder = OneHotEncoder(sparse=False)\n", + "housing_cat_1hot = cat_encoder.fit_transform(housing_cat)\n", "housing_cat_1hot" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The default encoding is one-hot, and it returns a sparse array. You can use `toarray()` to get a dense array:" - ] - }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], - "source": [ - "housing_cat_1hot.toarray()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternatively, you can specify the encoding to be `\"onehot-dense\"` to get a dense matrix rather than a sparse matrix:" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "metadata": {}, - "outputs": [], - "source": [ - "cat_encoder = CategoricalEncoder(encoding=\"onehot-dense\")\n", - "housing_cat_1hot = cat_encoder.fit_transform(housing_cat_reshaped)\n", - "housing_cat_1hot" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "metadata": {}, - "outputs": [], "source": [ "cat_encoder.categories_" ] @@ -1137,7 +903,7 @@ }, { "cell_type": "code", - "execution_count": 69, + "execution_count": 67, "metadata": {}, "outputs": [], "source": [ @@ -1167,11 +933,13 @@ }, { "cell_type": "code", - "execution_count": 70, + "execution_count": 68, "metadata": {}, "outputs": [], "source": [ - "housing_extra_attribs = pd.DataFrame(housing_extra_attribs, columns=list(housing.columns)+[\"rooms_per_household\", \"population_per_household\"])\n", + "housing_extra_attribs = pd.DataFrame(\n", + " housing_extra_attribs,\n", + " columns=list(housing.columns)+[\"rooms_per_household\", \"population_per_household\"])\n", "housing_extra_attribs.head()" ] }, @@ -1184,7 +952,7 @@ }, { "cell_type": "code", - "execution_count": 71, + "execution_count": 69, "metadata": {}, "outputs": [], "source": [ @@ -1202,7 +970,7 @@ }, { "cell_type": "code", - "execution_count": 72, + "execution_count": 70, "metadata": {}, "outputs": [], "source": [ @@ -1218,7 +986,7 @@ }, { "cell_type": "code", - "execution_count": 73, + "execution_count": 71, "metadata": {}, "outputs": [], "source": [ @@ -1244,7 +1012,7 @@ }, { "cell_type": "code", - "execution_count": 74, + "execution_count": 72, "metadata": {}, "outputs": [], "source": [ @@ -1260,13 +1028,13 @@ "\n", "cat_pipeline = Pipeline([\n", " ('selector', DataFrameSelector(cat_attribs)),\n", - " ('cat_encoder', CategoricalEncoder(encoding=\"onehot-dense\")),\n", + " ('cat_encoder', OneHotEncoder(sparse=False)),\n", " ])" ] }, { "cell_type": "code", - "execution_count": 75, + "execution_count": 73, "metadata": {}, "outputs": [], "source": [ @@ -1280,7 +1048,7 @@ }, { "cell_type": "code", - "execution_count": 76, + "execution_count": 74, "metadata": {}, "outputs": [], "source": [ @@ -1290,7 +1058,7 @@ }, { "cell_type": "code", - "execution_count": 77, + "execution_count": 75, "metadata": {}, "outputs": [], "source": [ @@ -1306,7 +1074,7 @@ }, { "cell_type": "code", - "execution_count": 78, + "execution_count": 76, "metadata": {}, "outputs": [], "source": [ @@ -1318,7 +1086,7 @@ }, { "cell_type": "code", - "execution_count": 79, + "execution_count": 77, "metadata": {}, "outputs": [], "source": [ @@ -1339,7 +1107,7 @@ }, { "cell_type": "code", - "execution_count": 80, + "execution_count": 78, "metadata": {}, "outputs": [], "source": [ @@ -1348,7 +1116,7 @@ }, { "cell_type": "code", - "execution_count": 81, + "execution_count": 79, "metadata": {}, "outputs": [], "source": [ @@ -1357,7 +1125,7 @@ }, { "cell_type": "code", - "execution_count": 82, + "execution_count": 80, "metadata": {}, "outputs": [], "source": [ @@ -1371,7 +1139,7 @@ }, { "cell_type": "code", - "execution_count": 83, + "execution_count": 81, "metadata": {}, "outputs": [], "source": [ @@ -1383,7 +1151,7 @@ }, { "cell_type": "code", - "execution_count": 84, + "execution_count": 82, "metadata": {}, "outputs": [], "source": [ @@ -1395,7 +1163,7 @@ }, { "cell_type": "code", - "execution_count": 85, + "execution_count": 83, "metadata": {}, "outputs": [], "source": [ @@ -1414,7 +1182,7 @@ }, { "cell_type": "code", - "execution_count": 86, + "execution_count": 84, "metadata": {}, "outputs": [], "source": [ @@ -1427,7 +1195,7 @@ }, { "cell_type": "code", - "execution_count": 87, + "execution_count": 85, "metadata": {}, "outputs": [], "source": [ @@ -1441,7 +1209,7 @@ }, { "cell_type": "code", - "execution_count": 88, + "execution_count": 86, "metadata": {}, "outputs": [], "source": [ @@ -1453,7 +1221,7 @@ }, { "cell_type": "code", - "execution_count": 89, + "execution_count": 87, "metadata": {}, "outputs": [], "source": [ @@ -1465,7 +1233,7 @@ }, { "cell_type": "code", - "execution_count": 90, + "execution_count": 88, "metadata": {}, "outputs": [], "source": [ @@ -1477,7 +1245,7 @@ }, { "cell_type": "code", - "execution_count": 91, + "execution_count": 89, "metadata": {}, "outputs": [], "source": [ @@ -1491,7 +1259,7 @@ }, { "cell_type": "code", - "execution_count": 92, + "execution_count": 90, "metadata": {}, "outputs": [], "source": [ @@ -1501,7 +1269,7 @@ }, { "cell_type": "code", - "execution_count": 93, + "execution_count": 91, "metadata": {}, "outputs": [], "source": [ @@ -1517,7 +1285,7 @@ }, { "cell_type": "code", - "execution_count": 94, + "execution_count": 92, "metadata": {}, "outputs": [], "source": [ @@ -1546,7 +1314,7 @@ }, { "cell_type": "code", - "execution_count": 95, + "execution_count": 93, "metadata": {}, "outputs": [], "source": [ @@ -1555,7 +1323,7 @@ }, { "cell_type": "code", - "execution_count": 96, + "execution_count": 94, "metadata": {}, "outputs": [], "source": [ @@ -1571,7 +1339,7 @@ }, { "cell_type": "code", - "execution_count": 97, + "execution_count": 95, "metadata": {}, "outputs": [], "source": [ @@ -1582,7 +1350,7 @@ }, { "cell_type": "code", - "execution_count": 98, + "execution_count": 96, "metadata": {}, "outputs": [], "source": [ @@ -1591,7 +1359,7 @@ }, { "cell_type": "code", - "execution_count": 99, + "execution_count": 97, "metadata": {}, "outputs": [], "source": [ @@ -1611,7 +1379,7 @@ }, { "cell_type": "code", - "execution_count": 100, + "execution_count": 98, "metadata": {}, "outputs": [], "source": [ @@ -1622,7 +1390,7 @@ }, { "cell_type": "code", - "execution_count": 101, + "execution_count": 99, "metadata": {}, "outputs": [], "source": [ @@ -1632,7 +1400,7 @@ }, { "cell_type": "code", - "execution_count": 102, + "execution_count": 100, "metadata": {}, "outputs": [], "source": [ @@ -1645,7 +1413,7 @@ }, { "cell_type": "code", - "execution_count": 103, + "execution_count": 101, "metadata": {}, "outputs": [], "source": [ @@ -1663,7 +1431,7 @@ }, { "cell_type": "code", - "execution_count": 104, + "execution_count": 102, "metadata": {}, "outputs": [], "source": [ @@ -1686,7 +1454,7 @@ }, { "cell_type": "code", - "execution_count": 105, + "execution_count": 103, "metadata": {}, "outputs": [], "source": [ @@ -1708,7 +1476,7 @@ }, { "cell_type": "code", - "execution_count": 106, + "execution_count": 104, "metadata": {}, "outputs": [], "source": [ @@ -1717,7 +1485,7 @@ }, { "cell_type": "code", - "execution_count": 107, + "execution_count": 105, "metadata": {}, "outputs": [], "source": [ @@ -1736,7 +1504,7 @@ }, { "cell_type": "code", - "execution_count": 108, + "execution_count": 106, "metadata": {}, "outputs": [], "source": [ @@ -1774,7 +1542,7 @@ }, { "cell_type": "code", - "execution_count": 109, + "execution_count": 107, "metadata": {}, "outputs": [], "source": [ @@ -1800,7 +1568,7 @@ }, { "cell_type": "code", - "execution_count": 110, + "execution_count": 108, "metadata": {}, "outputs": [], "source": [ @@ -1818,7 +1586,7 @@ }, { "cell_type": "code", - "execution_count": 111, + "execution_count": 109, "metadata": {}, "outputs": [], "source": [ @@ -1848,7 +1616,7 @@ }, { "cell_type": "code", - "execution_count": 112, + "execution_count": 110, "metadata": {}, "outputs": [], "source": [ @@ -1881,7 +1649,7 @@ }, { "cell_type": "code", - "execution_count": 113, + "execution_count": 111, "metadata": {}, "outputs": [], "source": [ @@ -1899,7 +1667,7 @@ }, { "cell_type": "code", - "execution_count": 114, + "execution_count": 112, "metadata": {}, "outputs": [], "source": [ @@ -1922,7 +1690,7 @@ }, { "cell_type": "code", - "execution_count": 115, + "execution_count": 113, "metadata": {}, "outputs": [], "source": [ @@ -1947,7 +1715,7 @@ }, { "cell_type": "code", - "execution_count": 116, + "execution_count": 114, "metadata": {}, "outputs": [], "source": [ @@ -1986,7 +1754,7 @@ }, { "cell_type": "code", - "execution_count": 117, + "execution_count": 115, "metadata": {}, "outputs": [], "source": [ @@ -2022,7 +1790,7 @@ }, { "cell_type": "code", - "execution_count": 118, + "execution_count": 116, "metadata": {}, "outputs": [], "source": [ @@ -2038,7 +1806,7 @@ }, { "cell_type": "code", - "execution_count": 119, + "execution_count": 117, "metadata": {}, "outputs": [], "source": [ @@ -2048,7 +1816,7 @@ }, { "cell_type": "code", - "execution_count": 120, + "execution_count": 118, "metadata": {}, "outputs": [], "source": [ @@ -2064,7 +1832,7 @@ }, { "cell_type": "code", - "execution_count": 121, + "execution_count": 119, "metadata": {}, "outputs": [], "source": [ @@ -2080,7 +1848,7 @@ }, { "cell_type": "code", - "execution_count": 122, + "execution_count": 120, "metadata": {}, "outputs": [], "source": [ @@ -2092,7 +1860,7 @@ }, { "cell_type": "code", - "execution_count": 123, + "execution_count": 121, "metadata": {}, "outputs": [], "source": [ @@ -2108,7 +1876,7 @@ }, { "cell_type": "code", - "execution_count": 124, + "execution_count": 122, "metadata": {}, "outputs": [], "source": [ @@ -2124,7 +1892,7 @@ }, { "cell_type": "code", - "execution_count": 125, + "execution_count": 123, "metadata": {}, "outputs": [], "source": [ @@ -2154,7 +1922,7 @@ }, { "cell_type": "code", - "execution_count": 126, + "execution_count": 124, "metadata": {}, "outputs": [], "source": [ @@ -2167,7 +1935,7 @@ }, { "cell_type": "code", - "execution_count": 127, + "execution_count": 125, "metadata": {}, "outputs": [], "source": [ @@ -2183,7 +1951,7 @@ }, { "cell_type": "code", - "execution_count": 128, + "execution_count": 126, "metadata": {}, "outputs": [], "source": [ @@ -2217,7 +1985,7 @@ }, { "cell_type": "code", - "execution_count": 129, + "execution_count": 127, "metadata": {}, "outputs": [], "source": [ @@ -2233,7 +2001,7 @@ }, { "cell_type": "code", - "execution_count": 130, + "execution_count": 128, "metadata": {}, "outputs": [], "source": [ @@ -2271,7 +2039,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.4" + "version": "3.6.5" }, "nav_menu": { "height": "279px", diff --git a/future_encoders.py b/future_encoders.py new file mode 100644 index 0000000..defd89e --- /dev/null +++ b/future_encoders.py @@ -0,0 +1,882 @@ +# Authors: Andreas Mueller +# Joris Van den Bossche +# License: BSD 3 clause + +from __future__ import division + +import numbers +import warnings + +import numpy as np +from scipy import sparse + +from sklearn.base import BaseEstimator, TransformerMixin +from sklearn.externals import six +from sklearn.utils import check_array +from sklearn.utils.validation import check_is_fitted, FLOAT_DTYPES +from sklearn.preprocessing.label import LabelEncoder + + +BOUNDS_THRESHOLD = 1e-7 + + +zip = six.moves.zip +map = six.moves.map +range = six.moves.range + +__all__ = [ + 'OneHotEncoder', + 'OrdinalEncoder' +] + + +def _argmax(arr_or_spmatrix, axis=None): + return arr_or_spmatrix.argmax(axis=axis) + + +def _handle_zeros_in_scale(scale, copy=True): + ''' Makes sure that whenever scale is zero, we handle it correctly. + + This happens in most scalers when we have constant features.''' + + # if we are fitting on 1D arrays, scale might be a scalar + if np.isscalar(scale): + if scale == .0: + scale = 1. + return scale + elif isinstance(scale, np.ndarray): + if copy: + # New array to avoid side-effects + scale = scale.copy() + scale[scale == 0.0] = 1.0 + return scale + + +def _transform_selected(X, transform, selected="all", copy=True): + """Apply a transform function to portion of selected features + + Parameters + ---------- + X : {array-like, sparse matrix}, shape [n_samples, n_features] + Dense array or sparse matrix. + + transform : callable + A callable transform(X) -> X_transformed + + copy : boolean, optional + Copy X even if it could be avoided. + + selected: "all" or array of indices or mask + Specify which features to apply the transform to. + + Returns + ------- + X : array or sparse matrix, shape=(n_samples, n_features_new) + """ + X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES) + + if isinstance(selected, six.string_types) and selected == "all": + return transform(X) + + if len(selected) == 0: + return X + + n_features = X.shape[1] + ind = np.arange(n_features) + sel = np.zeros(n_features, dtype=bool) + sel[np.asarray(selected)] = True + not_sel = np.logical_not(sel) + n_selected = np.sum(sel) + + if n_selected == 0: + # No features selected. + return X + elif n_selected == n_features: + # All features selected. + return transform(X) + else: + X_sel = transform(X[:, ind[sel]]) + X_not_sel = X[:, ind[not_sel]] + + if sparse.issparse(X_sel) or sparse.issparse(X_not_sel): + return sparse.hstack((X_sel, X_not_sel)) + else: + return np.hstack((X_sel, X_not_sel)) + + +class _BaseEncoder(BaseEstimator, TransformerMixin): + """ + Base class for encoders that includes the code to categorize and + transform the input features. + + """ + + def _fit(self, X, handle_unknown='error'): + + X_temp = check_array(X, dtype=None) + if not hasattr(X, 'dtype') and np.issubdtype(X_temp.dtype, np.str_): + X = check_array(X, dtype=np.object) + else: + X = X_temp + + n_samples, n_features = X.shape + + if self.categories != 'auto': + for cats in self.categories: + if not np.all(np.sort(cats) == np.array(cats)): + raise ValueError("Unsorted categories are not yet " + "supported") + if len(self.categories) != n_features: + raise ValueError("Shape mismatch: if n_values is an array," + " it has to be of shape (n_features,).") + + self._label_encoders_ = [LabelEncoder() for _ in range(n_features)] + + for i in range(n_features): + le = self._label_encoders_[i] + Xi = X[:, i] + if self.categories == 'auto': + le.fit(Xi) + else: + if handle_unknown == 'error': + valid_mask = np.in1d(Xi, self.categories[i]) + if not np.all(valid_mask): + diff = np.unique(Xi[~valid_mask]) + msg = ("Found unknown categories {0} in column {1}" + " during fit".format(diff, i)) + raise ValueError(msg) + le.classes_ = np.array(self.categories[i]) + + self.categories_ = [le.classes_ for le in self._label_encoders_] + + def _transform(self, X, handle_unknown='error'): + + X_temp = check_array(X, dtype=None) + if not hasattr(X, 'dtype') and np.issubdtype(X_temp.dtype, np.str_): + X = check_array(X, dtype=np.object) + else: + X = X_temp + + _, n_features = X.shape + X_int = np.zeros_like(X, dtype=np.int) + X_mask = np.ones_like(X, dtype=np.bool) + + for i in range(n_features): + Xi = X[:, i] + valid_mask = np.in1d(Xi, self.categories_[i]) + + if not np.all(valid_mask): + if handle_unknown == 'error': + diff = np.unique(X[~valid_mask, i]) + msg = ("Found unknown categories {0} in column {1}" + " during transform".format(diff, i)) + raise ValueError(msg) + else: + # Set the problematic rows to an acceptable value and + # continue `The rows are marked `X_mask` and will be + # removed later. + X_mask[:, i] = valid_mask + Xi = Xi.copy() + Xi[~valid_mask] = self.categories_[i][0] + X_int[:, i] = self._label_encoders_[i].transform(Xi) + + return X_int, X_mask + + +WARNING_MSG = ( + "The handling of integer data will change in the future. Currently, the " + "categories are determined based on the range [0, max(values)], while " + "in the future they will be determined based on the unique values.\n" + "If you want the future behaviour, you can specify \"categories='auto'\"." +) + + +class OneHotEncoder(_BaseEncoder): + """Encode categorical integer features as a one-hot numeric array. + + The input to this transformer should be an array-like of integers or + strings, denoting the values taken on by categorical (discrete) features. + The features are encoded using a one-hot (aka 'one-of-K' or 'dummy') + encoding scheme. This creates a binary column for each category and + returns a sparse matrix or dense array. + + By default, the encoder derives the categories based on the unique values + in each feature. Alternatively, you can also specify the `categories` + manually. + The OneHotEncoder previously assumed that the input features take on + values in the range [0, max(values)). This behaviour is deprecated. + + This encoding is needed for feeding categorical data to many scikit-learn + estimators, notably linear models and SVMs with the standard kernels. + + Note: a one-hot encoding of y labels should use a LabelBinarizer + instead. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + categories : 'auto' or a list of lists/arrays of values. + Categories (unique values) per feature: + + - 'auto' : Determine categories automatically from the training data. + - list : ``categories[i]`` holds the categories expected in the ith + column. The passed categories must be sorted and should not mix + strings and numeric values. + + The used categories can be found in the ``categories_`` attribute. + + sparse : boolean, default=True + Will return sparse matrix if set True else will return an array. + + dtype : number type, default=np.float + Desired dtype of output. + + handle_unknown : 'error' (default) or 'ignore' + Whether to raise an error or ignore if a unknown categorical feature is + present during transform (default is to raise). When this parameter + is set to 'ignore' and an unknown category is encountered during + transform, the resulting one-hot encoded columns for this feature + will be all zeros. In the inverse transform, an unknown category + will be denoted as None. + + n_values : 'auto', int or array of ints + Number of values per feature. + + - 'auto' : determine value range from training data. + - int : number of categorical values per feature. + Each feature value should be in ``range(n_values)`` + - array : ``n_values[i]`` is the number of categorical values in + ``X[:, i]``. Each feature value should be + in ``range(n_values[i])`` + + .. deprecated:: 0.20 + The `n_values` keyword is deprecated and will be removed in 0.22. + Use `categories` instead. + + categorical_features : "all" or array of indices or mask + Specify what features are treated as categorical. + + - 'all' (default): All features are treated as categorical. + - array of indices: Array of categorical feature indices. + - mask: Array of length n_features and with dtype=bool. + + Non-categorical features are always stacked to the right of the matrix. + + .. deprecated:: 0.20 + The `categorical_features` keyword is deprecated and will be + removed in 0.22. + + Attributes + ---------- + categories_ : list of arrays + The categories of each feature determined during fitting + (in order corresponding with output of ``transform``). + + active_features_ : array + Indices for active features, meaning values that actually occur + in the training set. Only available when n_values is ``'auto'``. + + .. deprecated:: 0.20 + + feature_indices_ : array of shape (n_features,) + Indices to feature ranges. + Feature ``i`` in the original data is mapped to features + from ``feature_indices_[i]`` to ``feature_indices_[i+1]`` + (and then potentially masked by `active_features_` afterwards) + + .. deprecated:: 0.20 + + n_values_ : array of shape (n_features,) + Maximum number of values per feature. + + .. deprecated:: 0.20 + + Examples + -------- + Given a dataset with two features, we let the encoder find the unique + values per feature and transform the data to a binary one-hot encoding. + + >>> from sklearn.preprocessing import OneHotEncoder + >>> enc = OneHotEncoder(handle_unknown='ignore') + >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] + >>> enc.fit(X) + ... # doctest: +ELLIPSIS + OneHotEncoder(categories='auto', dtype=<... 'numpy.float64'>, + handle_unknown='ignore', sparse=True) + + >>> enc.categories_ + [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] + >>> enc.transform([['Female', 1], ['Male', 4]]).toarray() + array([[ 1., 0., 1., 0., 0.], + [ 0., 1., 0., 0., 0.]]) + >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) + array([['Male', 1], + [None, 2]], dtype=object) + + See also + -------- + sklearn.preprocessing.OrdinalEncoder : performs an ordinal (integer) + encoding of the categorical features. + sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of + dictionary items (also handles string-valued features). + sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot + encoding of dictionary items or strings. + sklearn.preprocessing.LabelBinarizer : binarizes labels in a one-vs-all + fashion. + sklearn.preprocessing.MultiLabelBinarizer : transforms between iterable of + iterables and a multilabel format, e.g. a (samples x classes) binary + matrix indicating the presence of a class label. + """ + + def __init__(self, n_values=None, categorical_features=None, + categories=None, sparse=True, dtype=np.float64, + handle_unknown='error'): + self._categories = categories + if categories is None: + self.categories = 'auto' + else: + self.categories = categories + self.sparse = sparse + self.dtype = dtype + self.handle_unknown = handle_unknown + + if n_values is not None: + pass + # warnings.warn("Deprecated", DeprecationWarning) + else: + n_values = "auto" + self._deprecated_n_values = n_values + + if categorical_features is not None: + pass + # warnings.warn("Deprecated", DeprecationWarning) + else: + categorical_features = "all" + self._deprecated_categorical_features = categorical_features + + # Deprecated keywords + + @property + def n_values(self): + warnings.warn("The 'n_values' parameter is deprecated.", + DeprecationWarning) + return self._deprecated_n_values + + @n_values.setter + def n_values(self, value): + warnings.warn("The 'n_values' parameter is deprecated.", + DeprecationWarning) + self._deprecated_n_values = value + + @property + def categorical_features(self): + warnings.warn("The 'categorical_features' parameter is deprecated.", + DeprecationWarning) + return self._deprecated_categorical_features + + @categorical_features.setter + def categorical_features(self, value): + warnings.warn("The 'categorical_features' parameter is deprecated.", + DeprecationWarning) + self._deprecated_categorical_features = value + + # Deprecated attributes + + @property + def active_features_(self): + check_is_fitted(self, 'categories_') + warnings.warn("The 'active_features_' attribute is deprecated.", + DeprecationWarning) + return self._active_features_ + + @property + def feature_indices_(self): + check_is_fitted(self, 'categories_') + warnings.warn("The 'feature_indices_' attribute is deprecated.", + DeprecationWarning) + return self._feature_indices_ + + @property + def n_values_(self): + check_is_fitted(self, 'categories_') + warnings.warn("The 'n_values_' attribute is deprecated.", + DeprecationWarning) + return self._n_values_ + + def _handle_deprecations(self, X): + + user_set_categories = False + + if self._categories is not None: + self._legacy_mode = False + user_set_categories = True + + elif self._deprecated_n_values != 'auto': + msg = ( + "Passing 'n_values' is deprecated and will be removed in a " + "future release. You can use the 'categories' keyword instead." + " 'n_values=n' corresponds to 'n_values=[range(n)]'.") + warnings.warn(msg, DeprecationWarning) + + # we internally translate this to the correct categories + # and don't use legacy mode + X = check_array(X, dtype=np.int) + + if isinstance(self._deprecated_n_values, numbers.Integral): + n_features = X.shape[1] + self.categories = [ + list(range(self._deprecated_n_values)) + for _ in range(n_features)] + n_values = np.empty(n_features, dtype=np.int) + n_values.fill(self._deprecated_n_values) + else: + try: + n_values = np.asarray(self._deprecated_n_values, dtype=int) + self.categories = [list(range(i)) + for i in self._deprecated_n_values] + except (ValueError, TypeError): + raise TypeError( + "Wrong type for parameter `n_values`. Expected 'auto'," + " int or array of ints, got %r".format(type(X))) + + self._n_values_ = n_values + n_values = np.hstack([[0], n_values]) + indices = np.cumsum(n_values) + self._feature_indices_ = indices + + self._legacy_mode = False + + else: # n_values = 'auto' + if self.handle_unknown == 'ignore': + # no change in behaviour, no need to raise deprecation warning + self._legacy_mode = False + else: + + # check if we have integer or categorical input + try: + X = check_array(X, dtype=np.int) + except ValueError: + self._legacy_mode = False + else: + warnings.warn(WARNING_MSG, DeprecationWarning) + self._legacy_mode = True + + if (not isinstance(self._deprecated_categorical_features, + six.string_types) + or (isinstance(self._deprecated_categorical_features, + six.string_types) + and self._deprecated_categorical_features != 'all')): + if user_set_categories: + raise ValueError( + "The 'categorical_features' keyword is deprecated, and " + "cannot be used together with specifying 'categories'.") + warnings.warn("The 'categorical_features' keyword is deprecated.", + DeprecationWarning) + self._legacy_mode = True + + def fit(self, X, y=None): + """Fit OneHotEncoder to X. + + Parameters + ---------- + X : array-like, shape [n_samples, n_feature] + The data to determine the categories of each feature. + + Returns + ------- + self + """ + if self.handle_unknown not in ['error', 'ignore']: + template = ("handle_unknown should be either 'error' or " + "'ignore', got %s") + raise ValueError(template % self.handle_unknown) + + self._handle_deprecations(X) + + if self._legacy_mode: + # TODO not with _transform_selected ?? + self._legacy_fit_transform(X) + return self + else: + self._fit(X, handle_unknown=self.handle_unknown) + return self + + def _legacy_fit_transform(self, X): + """Assumes X contains only categorical features.""" + self_n_values = self._deprecated_n_values + dtype = getattr(X, 'dtype', None) + X = check_array(X, dtype=np.int) + if np.any(X < 0): + raise ValueError("X needs to contain only non-negative integers.") + n_samples, n_features = X.shape + if (isinstance(self_n_values, six.string_types) and + self_n_values == 'auto'): + n_values = np.max(X, axis=0) + 1 + elif isinstance(self_n_values, numbers.Integral): + if (np.max(X, axis=0) >= self_n_values).any(): + raise ValueError("Feature out of bounds for n_values=%d" + % self_n_values) + n_values = np.empty(n_features, dtype=np.int) + n_values.fill(self_n_values) + else: + try: + n_values = np.asarray(self_n_values, dtype=int) + except (ValueError, TypeError): + raise TypeError("Wrong type for parameter `n_values`. Expected" + " 'auto', int or array of ints, got %r" + % type(X)) + if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]: + raise ValueError("Shape mismatch: if n_values is an array," + " it has to be of shape (n_features,).") + + self._n_values_ = n_values + self.categories_ = [np.arange(n_val - 1, dtype=dtype) + for n_val in n_values] + n_values = np.hstack([[0], n_values]) + indices = np.cumsum(n_values) + self._feature_indices_ = indices + + column_indices = (X + indices[:-1]).ravel() + row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), + n_features) + data = np.ones(n_samples * n_features) + out = sparse.coo_matrix((data, (row_indices, column_indices)), + shape=(n_samples, indices[-1]), + dtype=self.dtype).tocsr() + + if (isinstance(self_n_values, six.string_types) and + self_n_values == 'auto'): + mask = np.array(out.sum(axis=0)).ravel() != 0 + active_features = np.where(mask)[0] + out = out[:, active_features] + self._active_features_ = active_features + + self.categories_ = [ + np.unique(X[:, i]).astype(dtype) if dtype else np.unique(X[:, i]) + for i in range(n_features)] + #import pdb; pdb.set_trace() + + return out if self.sparse else out.toarray() + + def fit_transform(self, X, y=None): + """Fit OneHotEncoder to X, then transform X. + + Equivalent to self.fit(X).transform(X), but more convenient and more + efficient. See fit for the parameters, transform for the return value. + + Parameters + ---------- + X : array-like, shape [n_samples, n_feature] + Input array of type int. + """ + if self.handle_unknown not in ['error', 'ignore']: + template = ("handle_unknown should be either 'error' or " + "'ignore', got %s") + raise ValueError(template % self.handle_unknown) + + self._handle_deprecations(X) + + if self._legacy_mode: + return _transform_selected(X, self._legacy_fit_transform, + self._deprecated_categorical_features, + copy=True) + else: + return self.fit(X).transform(X) + + def _legacy_transform(self, X): + """Assumes X contains only categorical features.""" + self_n_values = self._deprecated_n_values + X = check_array(X, dtype=np.int) + if np.any(X < 0): + raise ValueError("X needs to contain only non-negative integers.") + n_samples, n_features = X.shape + + indices = self._feature_indices_ + if n_features != indices.shape[0] - 1: + raise ValueError("X has different shape than during fitting." + " Expected %d, got %d." + % (indices.shape[0] - 1, n_features)) + + # We use only those categorical features of X that are known using fit. + # i.e lesser than n_values_ using mask. + # This means, if self.handle_unknown is "ignore", the row_indices and + # col_indices corresponding to the unknown categorical feature are + # ignored. + mask = (X < self._n_values_).ravel() + if np.any(~mask): + if self.handle_unknown not in ['error', 'ignore']: + raise ValueError("handle_unknown should be either error or " + "unknown got %s" % self.handle_unknown) + if self.handle_unknown == 'error': + raise ValueError("unknown categorical feature present %s " + "during transform." % X.ravel()[~mask]) + + column_indices = (X + indices[:-1]).ravel()[mask] + row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), + n_features)[mask] + data = np.ones(np.sum(mask)) + out = sparse.coo_matrix((data, (row_indices, column_indices)), + shape=(n_samples, indices[-1]), + dtype=self.dtype).tocsr() + if (isinstance(self_n_values, six.string_types) and + self_n_values == 'auto'): + out = out[:, self._active_features_] + + return out if self.sparse else out.toarray() + + def _transform_new(self, X): + """New implementation assuming categorical input""" + X_temp = check_array(X, dtype=None) + if not hasattr(X, 'dtype') and np.issubdtype(X_temp.dtype, np.str_): + X = check_array(X, dtype=np.object) + else: + X = X_temp + + n_samples, n_features = X.shape + + X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) + + mask = X_mask.ravel() + n_values = [cats.shape[0] for cats in self.categories_] + n_values = np.array([0] + n_values) + feature_indices = np.cumsum(n_values) + + indices = (X_int + feature_indices[:-1]).ravel()[mask] + indptr = X_mask.sum(axis=1).cumsum() + indptr = np.insert(indptr, 0, 0) + data = np.ones(n_samples * n_features)[mask] + + out = sparse.csr_matrix((data, indices, indptr), + shape=(n_samples, feature_indices[-1]), + dtype=self.dtype) + if not self.sparse: + return out.toarray() + else: + return out + + def transform(self, X): + """Transform X using one-hot encoding. + + Parameters + ---------- + X : array-like, shape [n_samples, n_features] + The data to encode. + + Returns + ------- + X_out : sparse matrix if sparse=True else a 2-d array + Transformed input. + """ + if not self._legacy_mode: + return self._transform_new(X) + else: + return _transform_selected(X, self._legacy_transform, + self._deprecated_categorical_features, + copy=True) + + def inverse_transform(self, X): + """Convert back the data to the original representation. + + In case unknown categories are encountered (all zero's in the + one-hot encoding), ``None`` is used to represent this category. + + Parameters + ---------- + X : array-like or sparse matrix, shape [n_samples, n_encoded_features] + The transformed data. + + Returns + ------- + X_tr : array-like, shape [n_samples, n_features] + Inverse transformed array. + + """ + # if self._legacy_mode: + # raise ValueError("only supported for categorical features") + + check_is_fitted(self, 'categories_') + X = check_array(X, accept_sparse='csr') + + n_samples, _ = X.shape + n_features = len(self.categories_) + n_transformed_features = sum([len(cats) for cats in self.categories_]) + + # validate shape of passed X + msg = ("Shape of the passed X data is not correct. Expected {0} " + "columns, got {1}.") + if X.shape[1] != n_transformed_features: + raise ValueError(msg.format(n_transformed_features, X.shape[1])) + + # create resulting array of appropriate dtype + dt = np.find_common_type([cat.dtype for cat in self.categories_], []) + X_tr = np.empty((n_samples, n_features), dtype=dt) + + j = 0 + found_unknown = {} + + for i in range(n_features): + n_categories = len(self.categories_[i]) + sub = X[:, j:j + n_categories] + + # for sparse X argmax returns 2D matrix, ensure 1D array + labels = np.asarray(_argmax(sub, axis=1)).flatten() + X_tr[:, i] = self.categories_[i][labels] + + if self.handle_unknown == 'ignore': + # ignored unknown categories: we have a row of all zero's + unknown = np.asarray(sub.sum(axis=1) == 0).flatten() + if unknown.any(): + found_unknown[i] = unknown + + j += n_categories + + # if ignored are found: potentially need to upcast result to + # insert None values + if found_unknown: + if X_tr.dtype != object: + X_tr = X_tr.astype(object) + + for idx, mask in found_unknown.items(): + X_tr[mask, idx] = None + + return X_tr + + +class OrdinalEncoder(_BaseEncoder): + """Encode categorical features as an integer array. + + The input to this transformer should be an array-like of integers or + strings, denoting the values taken on by categorical (discrete) features. + The features are converted to ordinal integers. This results in + a single column of integers (0 to n_categories - 1) per feature. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + categories : 'auto' or a list of lists/arrays of values. + Categories (unique values) per feature: + + - 'auto' : Determine categories automatically from the training data. + - list : ``categories[i]`` holds the categories expected in the ith + column. The passed categories must be sorted and should not mix + strings and numeric values. + + The used categories can be found in the ``categories_`` attribute. + + dtype : number type, default np.float64 + Desired dtype of output. + + Attributes + ---------- + categories_ : list of arrays + The categories of each feature determined during fitting + (in order corresponding with output of ``transform``). + + Examples + -------- + Given a dataset with two features, we let the encoder find the unique + values per feature and transform the data to a binary one-hot encoding. + + >>> from sklearn.preprocessing import OrdinalEncoder + >>> enc = OrdinalEncoder() + >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] + >>> enc.fit(X) + ... # doctest: +ELLIPSIS + OrdinalEncoder(categories='auto', dtype=<... 'numpy.float64'>) + >>> enc.categories_ + [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] + >>> enc.transform([['Female', 3], ['Male', 1]]) + array([[ 0., 2.], + [ 1., 0.]]) + + >>> enc.inverse_transform([[1, 0], [0, 1]]) + array([['Male', 1], + ['Female', 2]], dtype=object) + + See also + -------- + sklearn.preprocessing.OneHotEncoder : performs a one-hot encoding of + categorical features. + sklearn.preprocessing.LabelEncoder : encodes target labels with values + between 0 and n_classes-1. + sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of + dictionary items (also handles string-valued features). + sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot + encoding of dictionary items or strings. + """ + + def __init__(self, categories='auto', dtype=np.float64): + self.categories = categories + self.dtype = dtype + + def fit(self, X, y=None): + """Fit the OrdinalEncoder to X. + + Parameters + ---------- + X : array-like, shape [n_samples, n_features] + The data to determine the categories of each feature. + + Returns + ------- + self + + """ + self._fit(X) + + return self + + def transform(self, X): + """Transform X to ordinal codes. + + Parameters + ---------- + X : array-like, shape [n_samples, n_features] + The data to encode. + + Returns + ------- + X_out : sparse matrix or a 2-d array + Transformed input. + + """ + X_int, _ = self._transform(X) + return X_int.astype(self.dtype, copy=False) + + def inverse_transform(self, X): + """Convert back the data to the original representation. + + Parameters + ---------- + X : array-like or sparse matrix, shape [n_samples, n_encoded_features] + The transformed data. + + Returns + ------- + X_tr : array-like, shape [n_samples, n_features] + Inverse transformed array. + + """ + check_is_fitted(self, 'categories_') + X = check_array(X, accept_sparse='csr') + + n_samples, _ = X.shape + n_features = len(self.categories_) + + # validate shape of passed X + msg = ("Shape of the passed X data is not correct. Expected {0} " + "columns, got {1}.") + if X.shape[1] != n_features: + raise ValueError(msg.format(n_features, X.shape[1])) + + # create resulting array of appropriate dtype + dt = np.find_common_type([cat.dtype for cat in self.categories_], []) + X_tr = np.empty((n_samples, n_features), dtype=dt) + + for i in range(n_features): + labels = X[:, i].astype('int64') + X_tr[:, i] = self.categories_[i][labels] + + return X_tr