sklearn-pandas-1.1.0/0000775000175000017500000000000012631025561016055 5ustar dukebodydukebody00000000000000sklearn-pandas-1.1.0/setup.cfg0000664000175000017500000000012212631025561017671 0ustar dukebodydukebody00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 sklearn-pandas-1.1.0/MANIFEST.in0000664000175000017500000000004312532351747017620 0ustar dukebodydukebody00000000000000include LICENSE include README.rst sklearn-pandas-1.1.0/PKG-INFO0000664000175000017500000000046312631025561017155 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.1.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.1.0/setup.py0000664000175000017500000000245312617451374017604 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.13', 'scipy>=0.14', 'pandas>=0.11.0', 'numpy>=1.6.1'], tests_require=['pytest', 'mock'], cmdclass={'test': PyTest}, ) sklearn-pandas-1.1.0/sklearn_pandas.egg-info/0000775000175000017500000000000012631025561022534 5ustar dukebodydukebody00000000000000sklearn-pandas-1.1.0/sklearn_pandas.egg-info/PKG-INFO0000664000175000017500000000046312631025556023640 0ustar dukebodydukebody00000000000000Metadata-Version: 1.0 Name: sklearn-pandas Version: 1.1.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.1.0/sklearn_pandas.egg-info/dependency_links.txt0000664000175000017500000000000112631025556026606 0ustar dukebodydukebody00000000000000 sklearn-pandas-1.1.0/sklearn_pandas.egg-info/top_level.txt0000664000175000017500000000001712631025556025270 0ustar dukebodydukebody00000000000000sklearn_pandas sklearn-pandas-1.1.0/sklearn_pandas.egg-info/pbr.json0000664000175000017500000000005712570577276024235 0ustar dukebodydukebody00000000000000{"git_version": "e4f0aaa", "is_release": false}sklearn-pandas-1.1.0/sklearn_pandas.egg-info/requires.txt0000664000175000017500000000007212631025556025137 0ustar dukebodydukebody00000000000000scikit-learn>=0.13 scipy>=0.14 pandas>=0.11.0 numpy>=1.6.1sklearn-pandas-1.1.0/sklearn_pandas.egg-info/SOURCES.txt0000664000175000017500000000061312631025561024420 0ustar dukebodydukebody00000000000000LICENSE MANIFEST.in README.rst setup.cfg setup.py sklearn_pandas/__init__.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/pbr.json sklearn_pandas.egg-info/requires.txt sklearn_pandas.egg-info/top_level.txtsklearn-pandas-1.1.0/LICENSE0000664000175000017500000000454612532351747017103 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.1.0/README.rst0000664000175000017500000002140212631025460017541 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 way to cross-validate a pipeline that takes a pandas ``DataFrame`` as input. 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 I'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 pairs. 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:: >>> 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 with 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]]) 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.]]) Working with sparse features **************************** ``DataFrameMapper``s 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: >>> mapper4 = DataFrameMapper([ ... ('pet', CountVectorizer()), ... ], sparse=True) >>> type(mapper4.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 provides 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, data.copy(), data.salary, '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. Changelog --------- 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: * Paul Butler * Cal Paterson * Israel Saeta Pérez * Zac Stewart * Olivier Grisel sklearn-pandas-1.1.0/sklearn_pandas/0000775000175000017500000000000012631025561021042 5ustar dukebodydukebody00000000000000sklearn-pandas-1.1.0/sklearn_pandas/__init__.py0000666000175000017500000000024512631025445023157 0ustar dukebodydukebody00000000000000__version__ = '1.1.0' from .dataframe_mapper import DataFrameMapper # NOQA from .cross_validation import cross_val_score, GridSearchCV, RandomizedSearchCV # NOQA sklearn-pandas-1.1.0/sklearn_pandas/dataframe_mapper.py0000666000175000017500000001042412631022754024710 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 # load in the correct stringtype: str for py3, basestring for py2 string_types = str if sys.version_info >= (3, 0) else basestring 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 class DataFrameMapper(BaseEstimator, TransformerMixin): """ Map Pandas data frame column subsets to their own sklearn transformation. """ def __init__(self, features, sparse=False): """ Params: features a list of pairs. 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. sparse will return sparse matrix if set True and any of the extracted features is sparse. Defaults to False. """ if isinstance(features, list): features = [(columns, _build_transformer(transformers)) for (columns, transformers) in features] self.features = features self.sparse = sparse def __setstate__(self, state): # compatibility shim for pickles created with sklearn-pandas<1.0.0 self.features = [(columns, _build_transformer(transformers)) for (columns, transformers) in state['features']] self.sparse = state.get('sparse', False) def _get_col_subset(self, X, cols): """ 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]].values else: t = X[cols].values return t def fit(self, X, y=None): """ Fit a transformation from the pipeline X the data to fit """ for columns, transformers in self.features: if transformers is not None: transformers.fit(self._get_col_subset(X, columns)) return self def transform(self, X): """ Transform the given data. Assumes that fit has already been called. X the data to transform """ extracted = [] for columns, transformers in self.features: # 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) if transformers is not None: Xt = transformers.transform(Xt) 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) return stacked sklearn-pandas-1.1.0/sklearn_pandas/cross_validation.py0000666000175000017500000000212012631020614024746 0ustar dukebodydukebody00000000000000from sklearn import cross_validation from sklearn import grid_search def cross_val_score(model, X, *args, **kwargs): X = DataWrapper(X) return cross_validation.cross_val_score(model, X, *args, **kwargs) class GridSearchCV(grid_search.GridSearchCV): 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(grid_search.RandomizedSearchCV): 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.1.0/sklearn_pandas/pipeline.py0000664000175000017500000000501412631016417023221 0ustar dukebodydukebody00000000000000import six from sklearn.pipeline import _name_estimators, Pipeline from sklearn.utils import tosequence class TransformerPipeline(Pipeline): """ Pipeline that expects all steps to be transformers taking a single argument and having fit and transform methods. Code is copied from sklearn's Pipeline, leaving out the `y=None` argument. """ 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, **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 = transform.fit_transform(Xt, **fit_params_steps[name]) else: Xt = transform.fit(Xt, **fit_params_steps[name]) \ .transform(Xt) return Xt, fit_params_steps[self.steps[-1][0]] def fit(self, X, **fit_params): Xt, fit_params = self._pre_transform(X, **fit_params) self.steps[-1][-1].fit(Xt, **fit_params) return self def fit_transform(self, X, **fit_params): Xt, fit_params = self._pre_transform(X, **fit_params) if hasattr(self.steps[-1][-1], 'fit_transform'): return self.steps[-1][-1].fit_transform(Xt, **fit_params) else: return self.steps[-1][-1].fit(Xt, **fit_params).transform(Xt) def make_transformer_pipeline(*steps): """Construct a TransformerPipeline from the given estimators. """ return TransformerPipeline(_name_estimators(steps))