Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions scikits/learn/preprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import numpy as np

from .base import BaseEstimator

class Scaler(BaseEstimator):
"""Object to standardize a dataset along any axis

It centers the dataset and optionaly scales to
fix the variance to 1.

"""
def __init__(self, axis=0, with_std=True):
self.axis = axis
self.with_std = with_std

def fit(self, X, y=None, **params):
self._set_params(**params)
X = np.rollaxis(X, self.axis)
self.mean = X.mean(axis=0)
if self.with_std:
self.std = X.std(axis=0)
return self

def transform(self, X, y=None, copy=True):
if copy:
X = X.copy()
Xr = np.rollaxis(X, self.axis)
Xr -= self.mean
if self.with_std:
Xr /= self.std
return X
20 changes: 20 additions & 0 deletions scikits/learn/tests/test_preprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import numpy as np

from numpy.testing import assert_array_almost_equal

from scikits.learn.preprocessing import Scaler

def test_scaler():
"""Test scaling of dataset along all axis
"""

X = np.random.randn(4, 5)

scaler = Scaler(axis=1)
X_scaled = scaler.fit(X).transform(X, copy=False)
assert_array_almost_equal(X_scaled.mean(axis=1), 4*[0.0])
assert_array_almost_equal(X_scaled.std(axis=1), 4*[1.0])

scaler = Scaler(axis=0, with_std=False)
X_scaled = scaler.fit(X).transform(X, copy=False)
assert_array_almost_equal(X_scaled.mean(axis=0), 5*[0.0])