2015-06-02 04:08:31 +08:00
|
|
|
"""
|
|
|
|
|
=========================================================
|
2015-07-31 00:48:04 +08:00
|
|
|
Using FunctionTransformer to select columns
|
2015-06-02 04:08:31 +08:00
|
|
|
=========================================================
|
|
|
|
|
|
2015-07-31 00:48:04 +08:00
|
|
|
Shows how to use a function transformer in a pipeline. If you know your
|
2015-06-02 04:08:31 +08:00
|
|
|
dataset's first principle component is irrelevant for a classification task,
|
2015-07-31 00:48:04 +08:00
|
|
|
you can use the FunctionTransformer to select all but the first column of the
|
2015-06-02 04:08:31 +08:00
|
|
|
PCA transformed data.
|
|
|
|
|
"""
|
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
|
from sklearn.cross_validation import train_test_split
|
|
|
|
|
from sklearn.decomposition import PCA
|
|
|
|
|
from sklearn.pipeline import make_pipeline
|
2015-07-31 00:48:04 +08:00
|
|
|
from sklearn.preprocessing import FunctionTransformer
|
2015-06-02 04:08:31 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _generate_vector(shift=0.5, noise=15):
|
|
|
|
|
return np.arange(1000) + (np.random.rand(1000) - shift) * noise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_dataset():
|
|
|
|
|
"""
|
|
|
|
|
This dataset is two lines with a slope ~ 1, where one has
|
|
|
|
|
a y offset of ~100
|
|
|
|
|
"""
|
|
|
|
|
return np.vstack((
|
|
|
|
|
np.vstack((
|
|
|
|
|
_generate_vector(),
|
|
|
|
|
_generate_vector() + 100,
|
|
|
|
|
)).T,
|
|
|
|
|
np.vstack((
|
|
|
|
|
_generate_vector(),
|
|
|
|
|
_generate_vector(),
|
|
|
|
|
)).T,
|
|
|
|
|
)), np.hstack((np.zeros(1000), np.ones(1000)))
|
|
|
|
|
|
|
|
|
|
|
2015-07-31 00:48:04 +08:00
|
|
|
def all_but_first_column(X):
|
2015-06-02 04:08:31 +08:00
|
|
|
return X[:, 1:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def drop_first_component(X, y):
|
|
|
|
|
"""
|
|
|
|
|
Create a pipeline with PCA and the column selector and use it to
|
|
|
|
|
transform the dataset.
|
|
|
|
|
"""
|
|
|
|
|
pipeline = make_pipeline(
|
2015-07-31 00:48:04 +08:00
|
|
|
PCA(), FunctionTransformer(all_but_first_column),
|
2015-06-02 04:08:31 +08:00
|
|
|
)
|
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y)
|
|
|
|
|
pipeline.fit(X_train, y_train)
|
|
|
|
|
return pipeline.transform(X_test), y_test
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
X, y = generate_dataset()
|
2015-10-24 01:06:53 +08:00
|
|
|
lw = 0
|
|
|
|
|
plt.figure()
|
|
|
|
|
plt.scatter(X[:, 0], X[:, 1], c=y, lw=lw)
|
|
|
|
|
plt.figure()
|
2015-06-02 04:08:31 +08:00
|
|
|
X_transformed, y_transformed = drop_first_component(*generate_dataset())
|
|
|
|
|
plt.scatter(
|
|
|
|
|
X_transformed[:, 0],
|
|
|
|
|
np.zeros(len(X_transformed)),
|
|
|
|
|
c=y_transformed,
|
2015-10-24 01:06:53 +08:00
|
|
|
lw=lw,
|
|
|
|
|
s=60
|
2015-06-02 04:08:31 +08:00
|
|
|
)
|
|
|
|
|
plt.show()
|