From 147d916d9cc641d496b8bbb32b7db99701038491 Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Sun, 22 Nov 2015 16:43:24 +0000 Subject: Imported Upstream version 0.0.12 --- LICENSE | 48 +++++++ MANIFEST.in | 2 + PKG-INFO | 11 ++ README.rst | 194 +++++++++++++++++++++++++++ setup.cfg | 8 ++ setup.py | 47 +++++++ sklearn_pandas.egg-info/PKG-INFO | 11 ++ sklearn_pandas.egg-info/SOURCES.txt | 12 ++ sklearn_pandas.egg-info/dependency_links.txt | 1 + sklearn_pandas.egg-info/pbr.json | 1 + sklearn_pandas.egg-info/requires.txt | 4 + sklearn_pandas.egg-info/top_level.txt | 1 + sklearn_pandas/__init__.py | 159 ++++++++++++++++++++++ 13 files changed, 499 insertions(+) create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 PKG-INFO create mode 100644 README.rst create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 sklearn_pandas.egg-info/PKG-INFO create mode 100644 sklearn_pandas.egg-info/SOURCES.txt create mode 100644 sklearn_pandas.egg-info/dependency_links.txt create mode 100644 sklearn_pandas.egg-info/pbr.json create mode 100644 sklearn_pandas.egg-info/requires.txt create mode 100644 sklearn_pandas.egg-info/top_level.txt create mode 100644 sklearn_pandas/__init__.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fb27143 --- /dev/null +++ b/LICENSE @@ -0,0 +1,48 @@ +sklearn-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. + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..9d5d250 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include LICENSE +include README.rst diff --git a/PKG-INFO b/PKG-INFO new file mode 100644 index 0000000..c95774a --- /dev/null +++ b/PKG-INFO @@ -0,0 +1,11 @@ +Metadata-Version: 1.0 +Name: sklearn-pandas +Version: 0.0.12 +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 diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..a401384 --- /dev/null +++ b/README.rst @@ -0,0 +1,194 @@ + +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 + +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.]]) + +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 +--------- + +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 +* Olivier Grisel diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..6c71b61 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,8 @@ +[wheel] +universal = 1 + +[egg_info] +tag_build = +tag_date = 0 +tag_svn_revision = 0 + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..143f2f6 --- /dev/null +++ b/setup.py @@ -0,0 +1,47 @@ +#!/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}, + ) diff --git a/sklearn_pandas.egg-info/PKG-INFO b/sklearn_pandas.egg-info/PKG-INFO new file mode 100644 index 0000000..c95774a --- /dev/null +++ b/sklearn_pandas.egg-info/PKG-INFO @@ -0,0 +1,11 @@ +Metadata-Version: 1.0 +Name: sklearn-pandas +Version: 0.0.12 +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 diff --git a/sklearn_pandas.egg-info/SOURCES.txt b/sklearn_pandas.egg-info/SOURCES.txt new file mode 100644 index 0000000..107a3a6 --- /dev/null +++ b/sklearn_pandas.egg-info/SOURCES.txt @@ -0,0 +1,12 @@ +LICENSE +MANIFEST.in +README.rst +setup.cfg +setup.py +sklearn_pandas/__init__.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.txt \ No newline at end of file diff --git a/sklearn_pandas.egg-info/dependency_links.txt b/sklearn_pandas.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/sklearn_pandas.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/sklearn_pandas.egg-info/pbr.json b/sklearn_pandas.egg-info/pbr.json new file mode 100644 index 0000000..bec666c --- /dev/null +++ b/sklearn_pandas.egg-info/pbr.json @@ -0,0 +1 @@ +{"git_version": "e4f0aaa", "is_release": false} \ No newline at end of file diff --git a/sklearn_pandas.egg-info/requires.txt b/sklearn_pandas.egg-info/requires.txt new file mode 100644 index 0000000..e8d13b2 --- /dev/null +++ b/sklearn_pandas.egg-info/requires.txt @@ -0,0 +1,4 @@ +scikit-learn>=0.13 +scipy>=0.14 +pandas>=0.11.0 +numpy>=1.6.1 diff --git a/sklearn_pandas.egg-info/top_level.txt b/sklearn_pandas.egg-info/top_level.txt new file mode 100644 index 0000000..d78c5a2 --- /dev/null +++ b/sklearn_pandas.egg-info/top_level.txt @@ -0,0 +1 @@ +sklearn_pandas diff --git a/sklearn_pandas/__init__.py b/sklearn_pandas/__init__.py new file mode 100644 index 0000000..0f5d94c --- /dev/null +++ b/sklearn_pandas/__init__.py @@ -0,0 +1,159 @@ +__version__ = '0.0.12' + +import numpy as np +import pandas as pd +from sklearn.base import BaseEstimator, TransformerMixin +from sklearn import cross_validation +from sklearn import grid_search +import sys + +# load in the correct stringtype: str for py3, basestring for py2 +string_types = str if sys.version_info >= (3, 0) else basestring + + +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): + super(GridSearchCV, self).fit(DataWrapper(X), *params, **kwparams) + + def predict(self, X, *params, **kwparams): + super(GridSearchCV, self).fit(DataWrapper(X), *params, **kwparams) + + +try: + class RandomizedSearchCV(grid_search.RandomizedSearchCV): + def fit(self, X, *params, **kwparams): + super(RandomizedSearchCV, self).fit(DataWrapper(X), *params, **kwparams) + + def predict(self, X, *params, **kwparams): + super(RandomizedSearchCV, self).fit(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] + + +class PassthroughTransformer(TransformerMixin): + def fit(self, X, y=None, **fit_params): + return self + + def transform(self, X): + return np.array(X).astype(np.float) + + +def _handle_feature(fea): + if hasattr(fea, 'toarray'): + # sparse arrays should be converted to regular arrays + # for hstack. + fea = fea.toarray() + + if len(fea.shape) == 1: + fea = np.array([fea]).T + + return fea + + +class DataFrameMapper(BaseEstimator, TransformerMixin): + """ + Map Pandas data frame column subsets to their own + sklearn transformation. + """ + + def __init__(self, features): + """ + 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. + """ + self.features = features + + 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.as_matrix(cols) + + 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: + if isinstance(transformers, list): + # first fit_transform all transformers except the last one + Xt = self._get_col_subset(X, columns) + for transformer in transformers[:-1]: + Xt = transformer.fit_transform(Xt) + # then fit the last one without transformation + transformers[-1].fit(Xt) + else: + 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: + if isinstance(transformers, list): + for transformer in transformers: + Xt = transformer.transform(Xt) + else: + 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. + return np.hstack(extracted) -- cgit v1.2.3