sklearn-pandas-1.5.0/0000775000175000017500000000000013123517745016070 5ustar dukebodydukebody00000000000000sklearn-pandas-1.5.0/sklearn_pandas.egg-info/0000775000175000017500000000000013123517745022547 5ustar dukebodydukebody00000000000000sklearn-pandas-1.5.0/sklearn_pandas.egg-info/dependency_links.txt0000664000175000017500000000000113123517743026613 0ustar dukebodydukebody00000000000000 sklearn-pandas-1.5.0/sklearn_pandas.egg-info/top_level.txt0000664000175000017500000000001713123517743025275 0ustar dukebodydukebody00000000000000sklearn_pandas sklearn-pandas-1.5.0/sklearn_pandas.egg-info/requires.txt0000664000175000017500000000007513123517743025147 0ustar dukebodydukebody00000000000000scikit-learn>=0.15.0 scipy>=0.14 pandas>=0.11.0 numpy>=1.6.1 sklearn-pandas-1.5.0/sklearn_pandas.egg-info/PKG-INFO0000664000175000017500000000046313123517743023645 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.5.0 Summary: Pandas integration with sklearn Home-page: https://github.com/paulgb/sklearn-pandas Author: Israel Saeta Pérez Author-email: israel.saeta@dukebody.com License: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-1.5.0/sklearn_pandas.egg-info/SOURCES.txt0000664000175000017500000000062013123517745024431 0ustar dukebodydukebody00000000000000LICENSE MANIFEST.in README.rst setup.cfg setup.py sklearn_pandas/__init__.py sklearn_pandas/categorical_imputer.py sklearn_pandas/cross_validation.py sklearn_pandas/dataframe_mapper.py sklearn_pandas/pipeline.py sklearn_pandas.egg-info/PKG-INFO sklearn_pandas.egg-info/SOURCES.txt sklearn_pandas.egg-info/dependency_links.txt sklearn_pandas.egg-info/requires.txt sklearn_pandas.egg-info/top_level.txtsklearn-pandas-1.5.0/README.rst0000664000175000017500000004057613123517544017570 0ustar dukebodydukebody00000000000000 Sklearn-pandas ============== This module provides a bridge between `Scikit-Learn `__'s machine learning methods and `pandas `__-style Data Frames. In particular, it provides: 1. A way to map ``DataFrame`` columns to transformations, which are later recombined into features. 2. A compatibility shim for old ``scikit-learn`` versions to cross-validate a pipeline that takes a pandas ``DataFrame`` as input. This is only needed for ``scikit-learn<0.16.0`` (see `#11 `__ for details). It is deprecated and will likely be dropped in ``skearn-pandas==2.0``. 3. A ``CategoricalImputer`` that replaces null-like values with the mode and works with string columns. Installation ------------ You can install ``sklearn-pandas`` with ``pip``:: # pip install sklearn-pandas Tests ----- The examples in this file double as basic sanity tests. To run them, use ``doctest``, which is included with python:: # python -m doctest README.rst Usage ----- Import ****** Import what you need from the ``sklearn_pandas`` package. The choices are: * ``DataFrameMapper``, a class for mapping pandas data frame columns to different sklearn transformations * ``cross_val_score``, similar to ``sklearn.cross_validation.cross_val_score`` but working on pandas DataFrames For this demonstration, we will import both:: >>> from sklearn_pandas import DataFrameMapper, cross_val_score For these examples, we'll also use pandas, numpy, and sklearn:: >>> import pandas as pd >>> import numpy as np >>> import sklearn.preprocessing, sklearn.decomposition, \ ... sklearn.linear_model, sklearn.pipeline, sklearn.metrics >>> from sklearn.feature_extraction.text import CountVectorizer Load some Data ************** Normally you'll read the data from a file, but for demonstration purposes we'll create a data frame from a Python dict:: >>> data = pd.DataFrame({'pet': ['cat', 'dog', 'dog', 'fish', 'cat', 'dog', 'cat', 'fish'], ... 'children': [4., 6, 3, 3, 2, 3, 5, 4], ... 'salary': [90, 24, 44, 27, 32, 59, 36, 27]}) Transformation Mapping ---------------------- Map the Columns to Transformations ********************************** The mapper takes a list of tuples. The first is a column name from the pandas DataFrame, or a list containing one or multiple columns (we will see an example with multiple columns later). The second is an object which will perform the transformation which will be applied to that column. The third is optional and is a dictionary containing the transformation options, if applicable (see "custom column names for transformed features" below). Let's see an example:: >>> mapper = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... (['children'], sklearn.preprocessing.StandardScaler()) ... ]) The difference between specifying the column selector as ``'column'`` (as a simple string) and ``['column']`` (as a list with one element) is the shape of the array that is passed to the transformer. In the first case, a one dimensional array will be passed, while in the second case it will be a 2-dimensional array with one column, i.e. a column vector. This behaviour mimics the same pattern as pandas' dataframes ``__getitem__`` indexing: >>> data['children'].shape (8,) >>> data[['children']].shape (8, 1) Be aware that some transformers expect a 1-dimensional input (the label-oriented ones) while some others, like ``OneHotEncoder`` or ``Imputer``, expect 2-dimensional input, with the shape ``[n_samples, n_features]``. Test the Transformation *********************** We can use the ``fit_transform`` shortcut to both fit the model and see what transformed data looks like. In this and the other examples, output is rounded to two digits with ``np.round`` to account for rounding errors on different hardware:: >>> np.round(mapper.fit_transform(data.copy()), 2) array([[ 1. , 0. , 0. , 0.21], [ 0. , 1. , 0. , 1.88], [ 0. , 1. , 0. , -0.63], [ 0. , 0. , 1. , -0.63], [ 1. , 0. , 0. , -1.46], [ 0. , 1. , 0. , -0.63], [ 1. , 0. , 0. , 1.04], [ 0. , 0. , 1. , 0.21]]) Note that the first three columns are the output of the ``LabelBinarizer`` (corresponding to ``cat``, ``dog``, and ``fish`` respectively) and the fourth column is the standardized value for the number of children. In general, the columns are ordered according to the order given when the ``DataFrameMapper`` is constructed. Now that the transformation is trained, we confirm that it works on new data:: >>> sample = pd.DataFrame({'pet': ['cat'], 'children': [5.]}) >>> np.round(mapper.transform(sample), 2) array([[ 1. , 0. , 0. , 1.04]]) Output features names ********************* In certain cases, like when studying the feature importances for some model, we want to be able to associate the original features to the ones generated by the dataframe mapper. We can do so by inspecting the automatically generated ``transformed_names_`` attribute of the mapper after transformation:: >>> mapper.transformed_names_ ['pet_cat', 'pet_dog', 'pet_fish', 'children'] Custom column names for transformed features ******************************************** We can provide a custom name for the transformed features, to be used instead of the automatically generated one, by specifying it as the third argument of the feature definition:: >>> mapper_alias = DataFrameMapper([ ... (['children'], sklearn.preprocessing.StandardScaler(), ... {'alias': 'children_scaled'}) ... ]) >>> _ = mapper_alias.fit_transform(data.copy()) >>> mapper_alias.transformed_names_ ['children_scaled'] Passing Series/DataFrames to the transformers ********************************************* By default the transformers are passed a numpy array of the selected columns as input. This is because ``sklearn`` transformers are historically designed to work with numpy arrays, not with pandas dataframes, even though their basic indexing interfaces are similar. However we can pass a dataframe/series to the transformers to handle custom cases initializing the dataframe mapper with ``input_df=True``:: >>> from sklearn.base import TransformerMixin >>> class DateEncoder(TransformerMixin): ... def fit(self, X, y=None): ... return self ... ... def transform(self, X): ... dt = X.dt ... return pd.concat([dt.year, dt.month, dt.day], axis=1) >>> dates_df = pd.DataFrame( ... {'dates': pd.date_range('2015-10-30', '2015-11-02')}) >>> mapper_dates = DataFrameMapper([ ... ('dates', DateEncoder()) ... ], input_df=True) >>> mapper_dates.fit_transform(dates_df) array([[2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2]]) We can also specify this option per group of columns instead of for the whole mapper:: >>> mapper_dates = DataFrameMapper([ ... ('dates', DateEncoder(), {'input_df': True}) ... ]) >>> mapper_dates.fit_transform(dates_df) array([[2015, 10, 30], [2015, 10, 31], [2015, 11, 1], [2015, 11, 2]]) Outputting a dataframe ********************** By default the output of the dataframe mapper is a numpy array. This is so because most sklearn estimators expect a numpy array as input. If however we want the output of the mapper to be a dataframe, we can do so using the parameter ``df_out`` when creating the mapper:: >>> mapper_df = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... (['children'], sklearn.preprocessing.StandardScaler()) ... ], df_out=True) >>> np.round(mapper_df.fit_transform(data.copy()), 2) pet_cat pet_dog pet_fish children 0 1.0 0.0 0.0 0.21 1 0.0 1.0 0.0 1.88 2 0.0 1.0 0.0 -0.63 3 0.0 0.0 1.0 -0.63 4 1.0 0.0 0.0 -1.46 5 0.0 1.0 0.0 -0.63 6 1.0 0.0 0.0 1.04 7 0.0 0.0 1.0 0.21 The names for the columns are the same ones present in the ``transformed_names_`` attribute. Note this does not work together with the ``default=True`` or ``sparse=True`` arguments to the mapper. Transform Multiple Columns ************************** Transformations may require multiple input columns. In these cases, the column names can be specified in a list:: >>> mapper2 = DataFrameMapper([ ... (['children', 'salary'], sklearn.decomposition.PCA(1)) ... ]) Now running ``fit_transform`` will run PCA on the ``children`` and ``salary`` columns and return the first principal component:: >>> np.round(mapper2.fit_transform(data.copy()), 1) array([[ 47.6], [-18.4], [ 1.6], [-15.4], [-10.4], [ 16.6], [ -6.4], [-15.4]]) Multiple transformers for the same column ***************************************** Multiple transformers can be applied to the same column specifying them in a list:: >>> mapper3 = DataFrameMapper([ ... (['age'], [sklearn.preprocessing.Imputer(), ... sklearn.preprocessing.StandardScaler()])]) >>> data_3 = pd.DataFrame({'age': [1, np.nan, 3]}) >>> mapper3.fit_transform(data_3) array([[-1.22474487], [ 0. ], [ 1.22474487]]) Columns that don't need any transformation ****************************************** Only columns that are listed in the DataFrameMapper are kept. To keep a column but don't apply any transformation to it, use `None` as transformer:: >>> mapper3 = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... ('children', None) ... ]) >>> np.round(mapper3.fit_transform(data.copy())) array([[ 1., 0., 0., 4.], [ 0., 1., 0., 6.], [ 0., 1., 0., 3.], [ 0., 0., 1., 3.], [ 1., 0., 0., 2.], [ 0., 1., 0., 3.], [ 1., 0., 0., 5.], [ 0., 0., 1., 4.]]) Applying a default transformer ****************************** A default transformer can be applied to columns not explicitly selected passing it as the ``default`` argument to the mapper: >>> mapper4 = DataFrameMapper([ ... ('pet', sklearn.preprocessing.LabelBinarizer()), ... ('children', None) ... ], default=sklearn.preprocessing.StandardScaler()) >>> np.round(mapper4.fit_transform(data.copy()), 1) array([[ 1. , 0. , 0. , 4. , 2.3], [ 0. , 1. , 0. , 6. , -0.9], [ 0. , 1. , 0. , 3. , 0.1], [ 0. , 0. , 1. , 3. , -0.7], [ 1. , 0. , 0. , 2. , -0.5], [ 0. , 1. , 0. , 3. , 0.8], [ 1. , 0. , 0. , 5. , -0.3], [ 0. , 0. , 1. , 4. , -0.7]]) Using ``default=False`` (the default) drops unselected columns. Using ``default=None`` pass the unselected columns unchanged. Feature selection and other supervised transformations ****************************************************** ``DataFrameMapper`` supports transformers that require both X and y arguments. An example of this is feature selection. Treating the 'pet' column as the target, we will select the column that best predicts it. >>> from sklearn.feature_selection import SelectKBest, chi2 >>> mapper_fs = DataFrameMapper([(['children','salary'], SelectKBest(chi2, k=1))]) >>> mapper_fs.fit_transform(data[['children','salary']], data['pet']) array([[ 90.], [ 24.], [ 44.], [ 27.], [ 32.], [ 59.], [ 36.], [ 27.]]) Working with sparse features **************************** A ``DataFrameMapper`` will return a dense feature array by default. Setting ``sparse=True`` in the mapper will return a sparse array whenever any of the extracted features is sparse. Example: >>> mapper5 = DataFrameMapper([ ... ('pet', CountVectorizer()), ... ], sparse=True) >>> type(mapper5.fit_transform(data)) The stacking of the sparse features is done without ever densifying them. Cross-Validation **************** Now that we can combine features from pandas DataFrames, we may want to use cross-validation to see whether our model works. ``scikit-learn<0.16.0`` provided features for cross-validation, but they expect numpy data structures and won't work with ``DataFrameMapper``. To get around this, sklearn-pandas provides a wrapper on sklearn's ``cross_val_score`` function which passes a pandas DataFrame to the estimator rather than a numpy array:: >>> pipe = sklearn.pipeline.Pipeline([ ... ('featurize', mapper), ... ('lm', sklearn.linear_model.LinearRegression())]) >>> np.round(cross_val_score(pipe, X=data.copy(), y=data.salary, scoring='r2'), 2) array([ -1.09, -5.3 , -15.38]) Sklearn-pandas' ``cross_val_score`` function provides exactly the same interface as sklearn's function of the same name. ``CategoricalImputer`` ********************** Since the ``scikit-learn`` ``Imputer`` transformer currently only works with numbers, ``sklearn-pandas`` provides an equivalent helper transformer that do work with strings, substituting null values with the most frequent value in that column. Example: >>> from sklearn_pandas import CategoricalImputer >>> data = np.array(['a', 'b', 'b', np.nan], dtype=object) >>> imputer = CategoricalImputer() >>> imputer.fit_transform(data) array(['a', 'b', 'b', 'b'], dtype=object) Changelog --------- 1.5.0 (2017-06-24) ****************** * Allow inputting a dataframe/series per group of columns. * Get feature names also from ``estimator.get_feature_names()`` if present. * Attempt to derive feature names from individual transformers when applying a list of transformers. * Do not mutate features in ``__init__`` to be compatible with ``sklearn>=0.20`` (#76). 1.4.0 (2017-05-13) ****************** * Allow specifying a custom name (alias) for transformed columns (#83). * Capture output columns generated names in ``transformed_names_`` attribute (#78). * Add ``CategoricalImputer`` that replaces null-like values with the mode for string-like columns. * Add ``input_df`` init argument to allow inputting a dataframe/series to the transformers instead of a numpy array (#60). 1.3.0 (2017-01-21) ****************** * Make the mapper return dataframes when ``df_out=True`` (#70, #74). * Update imports to avoid deprecation warnings in sklearn 0.18 (#68). 1.2.0 (2016-10-02) ****************** * Deprecate custom cross-validation shim classes. * Require ``scikit-learn>=0.15.0``. Resolves #49. * Allow applying a default transformer to columns not selected explicitly in the mapper. Resolves #55. * Allow specifying an optional ``y`` argument during transform for supervised transformations. Resolves #58. 1.1.0 (2015-12-06) ******************* * Delete obsolete ``PassThroughTransformer``. If no transformation is desired for a given column, use ``None`` as transformer. * Factor out code in several modules, to avoid having everything in ``__init__.py``. * Use custom ``TransformerPipeline`` class to allow transformation steps accepting only a X argument. Fixes #46. * Add compatibility shim for unpickling mappers with list of transformers created before 1.0.0. Fixes #45. 1.0.0 (2015-11-28) ******************* * Change version numbering scheme to SemVer. * Use ``sklearn.pipeline.Pipeline`` instead of copying its code. Resolves #43. * Raise ``KeyError`` when selecting unexistent columns in the dataframe. Fixes #30. * Return sparse feature array if any of the features is sparse and ``sparse`` argument is ``True``. Defaults to ``False`` to avoid potential breaking of existing code. Resolves #34. * Return model and prediction in custom CV classes. Fixes #27. 0.0.12 (2015-11-07) ******************** * Allow specifying a list of transformers to use sequentially on the same column. Credits ------- The code for ``DataFrameMapper`` is based on code originally written by `Ben Hamner `__. Other contributors: * Arnau Gil Amat * Cal Paterson * Gustavo Sena Mafra * Israel Saeta Pérez * Jeremy Howard * Jimmy Wan * Olivier Grisel * Paul Butler * Ritesh Agrawal * Vitaley Zaretskey * Zac Stewart sklearn-pandas-1.5.0/LICENSE0000664000175000017500000000454612700175444017102 0ustar dukebodydukebody00000000000000sklearn-pandas -- bridge code for cross-validation of pandas data frames with sklearn This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Paul Butler The source code of DataFrameMapper is derived from code originally written by Ben Hamner and released under the following license. Copyright (c) 2013, Ben Hamner Author: Ben Hamner (ben@benhamner.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sklearn-pandas-1.5.0/setup.py0000664000175000017500000000245512700175444017604 0ustar dukebodydukebody00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from setuptools.command.test import test as TestCommand import re for line in open('sklearn_pandas/__init__.py'): match = re.match("__version__ *= *'(.*)'", line) if match: __version__, = match.groups() class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run(self): import pytest errno = pytest.main(self.pytest_args) raise SystemExit(errno) setup(name='sklearn-pandas', version=__version__, description='Pandas integration with sklearn', maintainer='Israel Saeta Pérez', maintainer_email='israel.saeta@dukebody.com', url='https://github.com/paulgb/sklearn-pandas', packages=['sklearn_pandas'], keywords=['scikit', 'sklearn', 'pandas'], install_requires=[ 'scikit-learn>=0.15.0', 'scipy>=0.14', 'pandas>=0.11.0', 'numpy>=1.6.1'], tests_require=['pytest', 'mock'], cmdclass={'test': PyTest}, ) sklearn-pandas-1.5.0/setup.cfg0000664000175000017500000000012213123517745017704 0ustar dukebodydukebody00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 sklearn-pandas-1.5.0/sklearn_pandas/0000775000175000017500000000000013123517745021055 5ustar dukebodydukebody00000000000000sklearn-pandas-1.5.0/sklearn_pandas/cross_validation.py0000664000175000017500000000413013075112634024762 0ustar dukebodydukebody00000000000000import warnings try: from sklearn.model_selection import cross_val_score as sk_cross_val_score from sklearn.model_selection import GridSearchCV as SKGridSearchCV from sklearn.model_selection import RandomizedSearchCV as \ SKRandomizedSearchCV except ImportError: from sklearn.cross_validation import cross_val_score as sk_cross_val_score from sklearn.grid_search import GridSearchCV as SKGridSearchCV from sklearn.grid_search import RandomizedSearchCV as SKRandomizedSearchCV DEPRECATION_MSG = ''' Custom cross-validation compatibility shims are no longer needed for scikit-learn>=0.16.0 and will be dropped in sklearn-pandas==2.0. ''' def cross_val_score(model, X, *args, **kwargs): warnings.warn(DEPRECATION_MSG, DeprecationWarning) X = DataWrapper(X) return sk_cross_val_score(model, X, *args, **kwargs) class GridSearchCV(SKGridSearchCV): def __init__(self, *args, **kwargs): warnings.warn(DEPRECATION_MSG, DeprecationWarning) super(GridSearchCV, self).__init__(*args, **kwargs) def fit(self, X, *params, **kwparams): return super(GridSearchCV, self).fit( DataWrapper(X), *params, **kwparams) def predict(self, X, *params, **kwparams): return super(GridSearchCV, self).predict( DataWrapper(X), *params, **kwparams) try: class RandomizedSearchCV(SKRandomizedSearchCV): def __init__(self, *args, **kwargs): warnings.warn(DEPRECATION_MSG, DeprecationWarning) super(RandomizedSearchCV, self).__init__(*args, **kwargs) def fit(self, X, *params, **kwparams): return super(RandomizedSearchCV, self).fit( DataWrapper(X), *params, **kwparams) def predict(self, X, *params, **kwparams): return super(RandomizedSearchCV, self).predict( DataWrapper(X), *params, **kwparams) except AttributeError: pass class DataWrapper(object): def __init__(self, df): self.df = df def __len__(self): return len(self.df) def __getitem__(self, key): return self.df.iloc[key] sklearn-pandas-1.5.0/sklearn_pandas/pipeline.py0000664000175000017500000000676213075112634023241 0ustar dukebodydukebody00000000000000import six from sklearn.pipeline import _name_estimators, Pipeline from sklearn.utils import tosequence def _call_fit(fit_method, X, y=None, **kwargs): """ helper function, calls the fit or fit_transform method with the correct number of parameters fit_method: fit or fit_transform method of the transformer X: the data to fit y: the target vector relative to X, optional kwargs: any keyword arguments to the fit method return: the result of the fit or fit_transform method WARNING: if this function raises a TypeError exception, test the fit or fit_transform method passed to it in isolation as _call_fit will not distinguish TypeError due to incorrect number of arguments from other TypeError """ try: return fit_method(X, y, **kwargs) except TypeError: # fit takes only one argument return fit_method(X, **kwargs) class TransformerPipeline(Pipeline): """ Pipeline that expects all steps to be transformers taking a single X argument, an optional y argument, and having fit and transform methods. Code is copied from sklearn's Pipeline """ def __init__(self, steps): names, estimators = zip(*steps) if len(dict(steps)) != len(steps): raise ValueError( "Provided step names are not unique: %s" % (names,)) # shallow copy of steps self.steps = tosequence(steps) estimator = estimators[-1] for e in estimators: if (not (hasattr(e, "fit") or hasattr(e, "fit_transform")) or not hasattr(e, "transform")): raise TypeError("All steps of the chain should " "be transforms and implement fit and transform" " '%s' (type %s) doesn't)" % (e, type(e))) if not hasattr(estimator, "fit"): raise TypeError("Last step of chain should implement fit " "'%s' (type %s) doesn't)" % (estimator, type(estimator))) def _pre_transform(self, X, y=None, **fit_params): fit_params_steps = dict((step, {}) for step, _ in self.steps) for pname, pval in six.iteritems(fit_params): step, param = pname.split('__', 1) fit_params_steps[step][param] = pval Xt = X for name, transform in self.steps[:-1]: if hasattr(transform, "fit_transform"): Xt = _call_fit(transform.fit_transform, Xt, y, **fit_params_steps[name]) else: Xt = _call_fit(transform.fit, Xt, y, **fit_params_steps[name]).transform(Xt) return Xt, fit_params_steps[self.steps[-1][0]] def fit(self, X, y=None, **fit_params): Xt, fit_params = self._pre_transform(X, y, **fit_params) _call_fit(self.steps[-1][-1].fit, Xt, y, **fit_params) return self def fit_transform(self, X, y=None, **fit_params): Xt, fit_params = self._pre_transform(X, y, **fit_params) if hasattr(self.steps[-1][-1], 'fit_transform'): return _call_fit(self.steps[-1][-1].fit_transform, Xt, y, **fit_params) else: return _call_fit(self.steps[-1][-1].fit, Xt, y, **fit_params).transform(Xt) def make_transformer_pipeline(*steps): """Construct a TransformerPipeline from the given estimators. """ return TransformerPipeline(_name_estimators(steps)) sklearn-pandas-1.5.0/sklearn_pandas/__init__.py0000664000175000017500000000034113123517573023163 0ustar dukebodydukebody00000000000000__version__ = '1.5.0' from .dataframe_mapper import DataFrameMapper # NOQA from .cross_validation import cross_val_score, GridSearchCV, RandomizedSearchCV # NOQA from .categorical_imputer import CategoricalImputer # NOQA sklearn-pandas-1.5.0/sklearn_pandas/categorical_imputer.py0000664000175000017500000000465613101143003025436 0ustar dukebodydukebody00000000000000import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted def _get_mask(X, value): """ Compute the boolean mask X == missing_values. """ if value == "NaN" or \ value is None or \ (isinstance(value, float) and np.isnan(value)): return pd.isnull(X) else: return X == value class CategoricalImputer(BaseEstimator, TransformerMixin): """ Impute missing values from a categorical/string np.ndarray or pd.Series with the most frequent value on the training data. Parameters ---------- missing_values : string or "NaN", optional (default="NaN") The placeholder for the missing values. All occurrences of `missing_values` will be imputed. None and np.nan are treated as being the same, use the string value "NaN" for them. copy : boolean, optional (default=True) If True, a copy of X will be created. Attributes ---------- fill_ : str Most frequent value of the training data. """ def __init__(self, missing_values='NaN', copy=True): self.missing_values = missing_values self.copy = copy def fit(self, X, y=None): """ Get the most frequent value. Parameters ---------- X : np.ndarray or pd.Series Training data. y : Passthrough for ``Pipeline`` compatibility. Returns ------- self: CategoricalImputer """ mask = _get_mask(X, self.missing_values) X = X[~mask] modes = pd.Series(X).mode() if modes.shape[0] == 0: raise ValueError('No value is repeated more than ' 'once in the column') else: self.fill_ = modes[0] return self def transform(self, X): """ Replaces missing values in the input data with the most frequent value of the training data. Parameters ---------- X : np.ndarray or pd.Series Data with values to be imputed. Returns ------- np.ndarray Data with imputed values. """ check_is_fitted(self, 'fill_') if self.copy: X = X.copy() mask = _get_mask(X, self.missing_values) X[mask] = self.fill_ return np.asarray(X) sklearn-pandas-1.5.0/sklearn_pandas/dataframe_mapper.py0000664000175000017500000002565513123514021024714 0ustar dukebodydukebody00000000000000import sys import pandas as pd import numpy as np from scipy import sparse from sklearn.base import BaseEstimator, TransformerMixin from .cross_validation import DataWrapper from .pipeline import make_transformer_pipeline, _call_fit, TransformerPipeline # load in the correct stringtype: str for py3, basestring for py2 string_types = str if sys.version_info >= (3, 0) else basestring # NOQA def _handle_feature(fea): """ Convert 1-dimensional arrays to 2-dimensional column vectors. """ if len(fea.shape) == 1: fea = np.array([fea]).T return fea def _build_transformer(transformers): if isinstance(transformers, list): transformers = make_transformer_pipeline(*transformers) return transformers def _build_feature(columns, transformers, options={}): return (columns, _build_transformer(transformers), options) def _get_feature_names(estimator): """ Attempt to extract feature names based on a given estimator """ if hasattr(estimator, 'classes_'): return estimator.classes_ elif hasattr(estimator, 'get_feature_names'): return estimator.get_feature_names() return None class DataFrameMapper(BaseEstimator, TransformerMixin): """ Map Pandas data frame column subsets to their own sklearn transformation. """ def __init__(self, features, default=False, sparse=False, df_out=False, input_df=False): """ Params: features a list of tuples with features definitions. The first element is the pandas column selector. This can be a string (for one column) or a list of strings. The second element is an object that supports sklearn's transform interface, or a list of such objects. The third element is optional and, if present, must be a dictionary with the options to apply to the transformation. Example: {'alias': 'day_of_week'} default default transformer to apply to the columns not explicitly selected in the mapper. If False (default), discard them. If None, pass them through untouched. Any other transformer will be applied to all the unselected columns as a whole, taken as a 2d-array. sparse will return sparse matrix if set True and any of the extracted features is sparse. Defaults to False. df_out return a pandas data frame, with each column named using the pandas column that created it (if there's only one input and output) or the input columns joined with '_' if there's multiple inputs, and the name concatenated with '_1', '_2' etc if there's multiple outputs. NB: does not work if *default* or *sparse* are true input_df If ``True`` pass the selected columns to the transformers as a pandas DataFrame or Series. Otherwise pass them as a numpy array. Defaults to ``False``. """ # self.features_def = features self.features = features self.built_features = None self.default = default self.built_default = None self.sparse = sparse self.df_out = df_out self.input_df = input_df self.transformed_names_ = [] if (df_out and (sparse or default)): raise ValueError("Can not use df_out with sparse or default") @property def _selected_columns(self): """ Return a set of selected columns in the feature list. """ selected_columns = set() for feature in self.features: columns = feature[0] if isinstance(columns, list): selected_columns = selected_columns.union(set(columns)) else: selected_columns.add(columns) return selected_columns def _unselected_columns(self, X): """ Return list of columns present in X and not selected explicitly in the mapper. Unselected columns are returned in the order they appear in the dataframe to avoid issues with different ordering during default fit and transform steps. """ X_columns = list(X.columns) return [column for column in X_columns if column not in self._selected_columns] def __setstate__(self, state): # compatibility for older versions of sklearn-pandas self.features = [_build_feature(*feat) for feat in state['features']] self.sparse = state.get('sparse', False) self.default = state.get('default', False) self.df_out = state.get('df_out', False) self.input_df = state.get('input_df', False) self.built_features = state.get('built_features', self.features) self.built_default = state.get('built_default', self.default) def _get_col_subset(self, X, cols, input_df=False): """ Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the selected columns """ return_vector = False if isinstance(cols, string_types): return_vector = True cols = [cols] if isinstance(X, list): X = [x[cols] for x in X] X = pd.DataFrame(X) elif isinstance(X, DataWrapper): # if it's a datawrapper, unwrap it X = X.df if return_vector: t = X[cols[0]] else: t = X[cols] # return either a DataFrame/Series or a numpy array if input_df: return t else: return t.values return t def fit(self, X, y=None): """ Fit a transformation from the pipeline X the data to fit y the target vector relative to X, optional """ # if isinstance(self.features_def, list): # self.features = [_build_feature(*f) for f in self.features_def] # else: # self.features = self.features_def if isinstance(self.features, list): self.built_features = [_build_feature(*f) for f in self.features] else: self.built_features = self.features self.built_default = _build_transformer(self.default) for columns, transformers, options in self.built_features: input_df = options.get('input_df', self.input_df) if transformers is not None: _call_fit(transformers.fit, self._get_col_subset(X, columns, input_df), y) # handle features not explicitly selected if self.built_default: # not False and not None _call_fit(self.built_default.fit, self._get_col_subset( X, self._unselected_columns(X), self.input_df ), y) return self def get_names(self, columns, transformer, x, alias=None): """ Return verbose names for the transformed columns. columns name (or list of names) of the original column(s) transformer transformer - can be a TransformerPipeline x transformed columns (numpy.ndarray) alias base name to use for the selected columns """ if alias is not None: name = alias elif isinstance(columns, list): name = '_'.join(columns) else: name = columns num_cols = x.shape[1] if len(x.shape) > 1 else 1 if num_cols > 1: # If there are as many columns as classes in the transformer, # infer column names from classes names. # If we are dealing with multiple transformers for these columns # attempt to extract the names from each of them, starting from the # last one if isinstance(transformer, TransformerPipeline): inverse_steps = transformer.steps[::-1] estimators = (estimator for name, estimator in inverse_steps) names_steps = (_get_feature_names(e) for e in estimators) names = next((n for n in names_steps if n is not None), None) # Otherwise use the only estimator present else: names = _get_feature_names(transformer) if names is not None and len(names) == num_cols: return [name + '_' + str(o) for o in names] # otherwise, return name concatenated with '_1', '_2', etc. else: return [name + '_' + str(o) for o in range(num_cols)] else: return [name] def transform(self, X): """ Transform the given data. Assumes that fit has already been called. X the data to transform """ extracted = [] self.transformed_names_ = [] for columns, transformers, options in self.built_features: input_df = options.get('input_df', self.input_df) # columns could be a string or list of # strings; we don't care because pandas # will handle either. Xt = self._get_col_subset(X, columns, input_df) if transformers is not None: Xt = transformers.transform(Xt) extracted.append(_handle_feature(Xt)) alias = options.get('alias') self.transformed_names_ += self.get_names( columns, transformers, Xt, alias) # handle features not explicitly selected if self.built_default is not False: unsel_cols = self._unselected_columns(X) Xt = self._get_col_subset(X, unsel_cols, self.input_df) if self.built_default is not None: Xt = self.built_default.transform(Xt) extracted.append(_handle_feature(Xt)) self.transformed_names_ += self.get_names( unsel_cols, self.built_default, Xt) # combine the feature outputs into one array. # at this point we lose track of which features # were created from which input columns, so it's # assumed that that doesn't matter to the model. # If any of the extracted features is sparse, combine sparsely. # Otherwise, combine as normal arrays. if any(sparse.issparse(fea) for fea in extracted): stacked = sparse.hstack(extracted).tocsr() # return a sparse matrix only if the mapper was initialized # with sparse=True if not self.sparse: stacked = stacked.toarray() else: stacked = np.hstack(extracted) if not self.df_out: return stacked return pd.DataFrame(stacked, columns=self.transformed_names_) sklearn-pandas-1.5.0/PKG-INFO0000664000175000017500000000046313123517745017170 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.5.0 Summary: Pandas integration with sklearn Home-page: https://github.com/paulgb/sklearn-pandas Author: Israel Saeta Pérez Author-email: israel.saeta@dukebody.com License: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-1.5.0/MANIFEST.in0000664000175000017500000000004312700175444017617 0ustar dukebodydukebody00000000000000include LICENSE include README.rst