sklearn-pandas-1.8.0/0000775000175000017500000000000013400556661016071 5ustar dukebodydukebody00000000000000sklearn-pandas-1.8.0/sklearn_pandas.egg-info/0000775000175000017500000000000013400556661022550 5ustar dukebodydukebody00000000000000sklearn-pandas-1.8.0/sklearn_pandas.egg-info/dependency_links.txt0000664000175000017500000000000113400556661026616 0ustar dukebodydukebody00000000000000 sklearn-pandas-1.8.0/sklearn_pandas.egg-info/top_level.txt0000664000175000017500000000001713400556661025300 0ustar dukebodydukebody00000000000000sklearn_pandas sklearn-pandas-1.8.0/sklearn_pandas.egg-info/requires.txt0000664000175000017500000000007513400556661025152 0ustar dukebodydukebody00000000000000scikit-learn>=0.15.0 scipy>=0.14 pandas>=0.11.0 numpy>=1.6.1 sklearn-pandas-1.8.0/sklearn_pandas.egg-info/PKG-INFO0000664000175000017500000000052513400556661023647 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.8.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-Content-Type: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-1.8.0/sklearn_pandas.egg-info/SOURCES.txt0000664000175000017500000000072413400556661024437 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/features_generator.py sklearn_pandas/pipeline.py sklearn_pandas/transformers.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.8.0/README.rst0000664000175000017500000005134113400556541017561 0ustar dukebodydukebody00000000000000 Sklearn-pandas ============== .. image:: https://circleci.com/gh/pandas-dev/sklearn-pandas.svg?style=svg :target: https://circleci.com/gh/pandas-dev/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 couple of special transformers that work well with pandas inputs: ``CategoricalImputer`` and ``FunctionTransformer`.` 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 element of each tuple 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 element is an object which will perform the transformation which will be applied to that column. The third one 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.21 1 0 1 0 1.88 2 0 1 0 -0.63 3 0 0 1 -0.63 4 1 0 0 -1.46 5 0 1 0 -0.63 6 1 0 0 1.04 7 0 0 1 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. Same transformer for the multiple columns ***************************************** Sometimes it is required to apply the same transformation to several dataframe columns. To simplify this process, the package provides ``gen_features`` function which accepts a list of columns and feature transformer class (or list of classes), and generates a feature definition, acceptable by ``DataFrameMapper``. For example, consider a dataset with three categorical columns, 'col1', 'col2', and 'col3', To binarize each of them, one could pass column names and ``LabelBinarizer`` transformer class into generator, and then use returned definition as ``features`` argument for ``DataFrameMapper``: >>> from sklearn_pandas import gen_features >>> feature_def = gen_features( ... columns=['col1', 'col2', 'col3'], ... classes=[sklearn.preprocessing.LabelEncoder] ... ) >>> feature_def [('col1', [LabelEncoder()]), ('col2', [LabelEncoder()]), ('col3', [LabelEncoder()])] >>> mapper5 = DataFrameMapper(feature_def) >>> data5 = pd.DataFrame({ ... 'col1': ['yes', 'no', 'yes'], ... 'col2': [True, False, False], ... 'col3': ['one', 'two', 'three'] ... }) >>> mapper5.fit_transform(data5) array([[1, 1, 0], [0, 0, 2], [1, 0, 1]]) If it is required to override some of transformer parameters, then a dict with 'class' key and transformer parameters should be provided. For example, consider a dataset with missing values. Then the following code could be used to override default imputing strategy: >>> feature_def = gen_features( ... columns=[['col1'], ['col2'], ['col3']], ... classes=[{'class': sklearn.preprocessing.Imputer, 'strategy': 'most_frequent'}] ... ) >>> mapper6 = DataFrameMapper(feature_def) >>> data6 = pd.DataFrame({ ... 'col1': [None, 1, 1, 2, 3], ... 'col2': [True, False, None, None, True], ... 'col3': [0, 0, 0, None, None] ... }) >>> mapper6.fit_transform(data6) array([[1., 1., 0.], [1., 0., 0.], [1., 1., 0.], [2., 1., 0.], [3., 1., 0.]]) 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 works with strings, substituting null values with the most frequent value in that column. Alternatively, you can specify a fixed value to use. Example: imputing with the mode: >>> 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) Example: imputing with a fixed value: >>> from sklearn_pandas import CategoricalImputer >>> data = np.array(['a', 'b', 'b', np.nan], dtype=object) >>> imputer = CategoricalImputer(strategy='constant', fill_value='a') >>> imputer.fit_transform(data) array(['a', 'b', 'b', 'a'], dtype=object) ``FunctionTransformer`` *********************** Often one wants to apply simple transformations to data such as ``np.log``. ``FunctionTransformer`` is a simple wrapper that takes any function and applies vectorization so that it can be used as a transformer. Example: >>> from sklearn_pandas import FunctionTransformer >>> array = np.array([10, 100]) >>> transformer = FunctionTransformer(np.log10) >>> transformer.fit_transform(array) array([1., 2.]) Changelog --------- 1.8.0 (2018-12-01) ****************** * Add ``FunctionTransformer`` class (#117). * Fix column names derivation for dataframes with multi-index or non-string columns (#166). * Change behaviour of DataFrameMapper's fit_transform method to invoke each underlying transformers' native fit_transform if implemented. (#150) 1.7.0 (2018-08-15) ****************** * Fix issues with unicode names in ``get_names`` (#160). * Update to build using ``numpy==1.14`` and ``python==3.6`` (#154). * Add ``strategy`` and ``fill_value`` parameters to ``CategoricalImputer`` to allow imputing with values other than the mode (#144), (#161). * Preserve input data types when no transform is supplied (#138). 1.6.0 (2017-10-28) ****************** * Add column name to exception during fit/transform (#110). * Add ``gen_feature`` helper function to help generating the same transformation for multiple columns (#126). 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: * Ariel Rossanigo (@arielrossanigo) * Arnau Gil Amat (@arnau126) * Assaf Ben-David (@AssafBenDavid) * Brendan Herger (@bjherger) * Cal Paterson (@calpaterson) * @defvorfu * Gustavo Sena Mafra (@gsmafra) * Israel Saeta Pérez (@dukebody) * Jeremy Howard (@jph00) * Jimmy Wan (@jimmywan) * Kristof Van Engeland (@kristofve91) * Olivier Grisel (@ogrisel) * Paul Butler (@paulgb) * Richard Miller (@rwjmiller) * Ritesh Agrawal (@ragrawal) * @SandroCasagrande * Timothy Sweetser (@hacktuarial) * Vitaley Zaretskey (@vzaretsk) * Zac Stewart (@zacstewart) sklearn-pandas-1.8.0/LICENSE0000664000175000017500000000454612700175444017105 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.8.0/setup.py0000664000175000017500000000245512700175444017607 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.8.0/setup.cfg0000664000175000017500000000007513400556661017714 0ustar dukebodydukebody00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 sklearn-pandas-1.8.0/sklearn_pandas/0000775000175000017500000000000013400556661021056 5ustar dukebodydukebody00000000000000sklearn-pandas-1.8.0/sklearn_pandas/cross_validation.py0000664000175000017500000000413013075112634024765 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.8.0/sklearn_pandas/features_generator.py0000664000175000017500000000347013173156074025321 0ustar dukebodydukebody00000000000000def gen_features(columns, classes=None): """Generates a feature definition list which can be passed into DataFrameMapper Params: columns a list of column names to generate features for. classes a list of classes for each feature, a list of dictionaries with transformer class and init parameters, or None. If list of classes is provided, then each of them is instantiated with default arguments. Example: classes = [StandardScaler, LabelBinarizer] If list of dictionaries is provided, then each of them should have a 'class' key with transformer class. All other keys are passed into 'class' value constructor. Example: classes = [ {'class': StandardScaler, 'with_mean': False}, {'class': LabelBinarizer} }] If None value selected, then each feature left as is. """ if classes is None: return [(column, None) for column in columns] feature_defs = [] for column in columns: feature_transformers = [] classes = [cls for cls in classes if cls is not None] if not classes: feature_defs.append((column, None)) else: for definition in classes: if isinstance(definition, dict): params = definition.copy() klass = params.pop('class') feature_transformers.append(klass(**params)) else: feature_transformers.append(definition()) if not feature_transformers: feature_transformers = None feature_defs.append((column, feature_transformers)) return feature_defs sklearn-pandas-1.8.0/sklearn_pandas/transformers.py0000664000175000017500000001025013400556531024147 0ustar dukebodydukebody00000000000000import numpy as np import pandas as pd 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. strategy : string, optional (default = 'most_frequent') The imputation strategy. - If "most_frequent", then replace missing using the most frequent value along each column. Can be used with strings or numeric data. - If "constant", then replace missing values with fill_value. Can be used with strings or numeric data. fill_value : string, optional (default='?') The value that all instances of `missing_values` are replaced with if `strategy` is set to `constant`. This is useful if you don't want to impute with the mode, or if there are multiple modes in your data and you want to choose a particular one. If `strategy` is not set to `constant`, this parameter is ignored. Attributes ---------- fill_ : str The imputation fill value """ def __init__( self, missing_values='NaN', strategy='most_frequent', fill_value='?', copy=True ): self.missing_values = missing_values self.copy = copy self.fill_value = fill_value self.strategy = strategy strategies = ['constant', 'most_frequent'] if self.strategy not in strategies: raise ValueError( 'Strategy {0} not in {1}'.format(self.strategy, strategies) ) 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] if self.strategy == 'most_frequent': modes = pd.Series(X).mode() elif self.strategy == 'constant': modes = np.array([self.fill_value]) if modes.shape[0] == 0: raise ValueError('Data is empty or all values are null') elif modes.shape[0] > 1: 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) class FunctionTransformer(BaseEstimator, TransformerMixin): """ Use this class to convert a random function into a transformer. """ def __init__(self, func): self.__func = func def fit(self, x, y=None): return self def transform(self, x): return np.vectorize(self.__func)(x) def __call__(self, *args, **kwargs): return self.__func(*args, **kwargs) sklearn-pandas-1.8.0/sklearn_pandas/pipeline.py0000664000175000017500000000676213075112634023244 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.8.0/sklearn_pandas/__init__.py0000664000175000017500000000044413400556535023171 0ustar dukebodydukebody00000000000000__version__ = '1.8.0' from .dataframe_mapper import DataFrameMapper # NOQA from .cross_validation import cross_val_score, GridSearchCV, RandomizedSearchCV # NOQA from .transformers import CategoricalImputer, FunctionTransformer # NOQA from .features_generator import gen_features # NOQA sklearn-pandas-1.8.0/sklearn_pandas/categorical_imputer.py0000664000175000017500000000740713363055437025465 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. strategy : string, optional (default = 'most_frequent') The imputation strategy. - If "most_frequent", then replace missing using the most frequent value along each column. Can be used with strings or numeric data. - If "constant", then replace missing values with fill_value. Can be used with strings or numeric data. fill_value : string, optional (default='?') The value that all instances of `missing_values` are replaced with if `strategy` is set to `constant`. This is useful if you don't want to impute with the mode, or if there are multiple modes in your data and you want to choose a particular one. If `strategy` is not set to `constant`, this parameter is ignored. Attributes ---------- fill_ : str The imputation fill value """ def __init__( self, missing_values='NaN', strategy='most_frequent', fill_value='?', copy=True ): self.missing_values = missing_values self.copy = copy self.fill_value = fill_value self.strategy = strategy strategies = ['constant', 'most_frequent'] if self.strategy not in strategies: raise ValueError( 'Strategy {0} not in {1}'.format(self.strategy, strategies) ) 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] if self.strategy == 'most_frequent': modes = pd.Series(X).mode() elif self.strategy == 'constant': modes = np.array([self.fill_value]) if modes.shape[0] == 0: raise ValueError('Data is empty or all values are null') elif modes.shape[0] > 1: 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.8.0/sklearn_pandas/dataframe_mapper.py0000664000175000017500000003413313335017704024721 0ustar dukebodydukebody00000000000000import sys import contextlib 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 PY3 = sys.version_info[0] == 3 if PY3: string_types = text_type = str else: string_types = basestring # noqa text_type = unicode # 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 @contextlib.contextmanager def add_column_names_to_exception(column_names): # Stolen from https://stackoverflow.com/a/17677938/356729 try: yield except Exception as ex: if ex.args: msg = u'{}: {}'.format(column_names, ex.args[0]) else: msg = text_type(column_names) ex.args = (msg,) + ex.args[1:] raise 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 = 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") def _build(self): """ Build attributes built_features and built_default. """ 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) @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) self.transformed_names_ = state.get('transformed_names_', []) 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 """ if isinstance(cols, string_types): return_vector = True cols = [cols] else: return_vector = False # Needed when using the cross-validation compatibility # layer for sklearn<0.16.0. # Will be dropped on sklearn-pandas 2.0. if isinstance(X, list): X = [x[cols] for x in X] X = pd.DataFrame(X) elif isinstance(X, DataWrapper): X = X.df # fetch underlying data 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 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 """ self._build() for columns, transformers, options in self.built_features: input_df = options.get('input_df', self.input_df) if transformers is not None: with add_column_names_to_exception(columns): Xt = self._get_col_subset(X, columns, input_df) _call_fit(transformers.fit, Xt, y) # handle features not explicitly selected if self.built_default: # not False and not None unsel_cols = self._unselected_columns(X) with add_column_names_to_exception(unsel_cols): Xt = self._get_col_subset(X, unsel_cols, self.input_df) _call_fit(self.built_default.fit, Xt, 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(map(str, 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 ['%s_%s' % (name, 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 get_dtypes(self, extracted): dtypes_features = [self.get_dtype(ex) for ex in extracted] return [dtype for dtype_feature in dtypes_features for dtype in dtype_feature] def get_dtype(self, ex): if isinstance(ex, np.ndarray) or sparse.issparse(ex): return [ex.dtype] * ex.shape[1] elif isinstance(ex, pd.DataFrame): return list(ex.dtypes) else: raise TypeError(type(ex)) def _transform(self, X, y=None, do_fit=False): """ Transform the given data with possibility to fit in advance. Avoids code duplication for implementation of transform and fit_transform. """ if do_fit: self._build() 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: with add_column_names_to_exception(columns): if do_fit and hasattr(transformers, 'fit_transform'): Xt = _call_fit(transformers.fit_transform, Xt, y) else: if do_fit: _call_fit(transformers.fit, Xt, y) 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: with add_column_names_to_exception(unsel_cols): if do_fit and hasattr(self.built_default, 'fit_transform'): Xt = _call_fit(self.built_default.fit_transform, Xt, y) else: if do_fit: _call_fit(self.built_default.fit, Xt, y) Xt = self.built_default.transform(Xt) self.transformed_names_ += self.get_names( unsel_cols, self.built_default, Xt) else: # if not applying a default transformer, # keep column names unmodified self.transformed_names_ += unsel_cols extracted.append(_handle_feature(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 self.df_out: # if no rows were dropped preserve the original index, # otherwise use a new integer one no_rows_dropped = len(X) == len(stacked) if no_rows_dropped: index = X.index else: index = None # output different data types, if appropriate dtypes = self.get_dtypes(extracted) df_out = pd.DataFrame( stacked, columns=self.transformed_names_, index=index) # preserve types for col, dtype in zip(self.transformed_names_, dtypes): df_out[col] = df_out[col].astype(dtype) return df_out else: return stacked def transform(self, X): """ Transform the given data. Assumes that fit has already been called. X the data to transform """ return self._transform(X) def fit_transform(self, X, y=None): """ Fit a transformation from the pipeline and directly apply it to the given data. X the data to fit y the target vector relative to X, optional """ return self._transform(X, y, True) sklearn-pandas-1.8.0/PKG-INFO0000664000175000017500000000052513400556661017170 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.8.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-Content-Type: UNKNOWN Description: UNKNOWN Keywords: scikit,sklearn,pandas Platform: UNKNOWN sklearn-pandas-1.8.0/MANIFEST.in0000664000175000017500000000004312700175444017622 0ustar dukebodydukebody00000000000000include LICENSE include README.rst