如何使用sklearn
缩放器/ imputer来估算张量?我想在管道中扩展/估算。我的输入是一个3-d numpy
数组。
我有一个形状的张量(n_samples,n_timesteps,n_feat)a la Keras。这是一个可以由LSTM学习的序列。不过,我想先缩放/估算。特别是,我希望在sci-kit学习pipeline内快速扩展,因为扩展完整数据集(这很容易)会导致leakage。 Keras已经集成了sklearn(参见here),但似乎没有简单的方法来缩放和估算keras时间序列模型处理的张量。
不幸的是,以下是错误
import numpy as np
X = np.array([[[3,5],[6,2]],[[8.,23.],[7.,23]],[[3, 4],[2, 55]]])
print X
from sklearn.preprocessing import StandardScaler
s = StandardScaler()
X = s.fit_transform(X)
print X
效果,“缩放器仅适用于2-d numpy阵列”。
我的解决方案是在sklearn预处理data.py文件
中添加一个装饰器def flat(func):
def wrapper(*args, **kwargs):
self, X = args
a, b, c = X.shape
X = X.reshape(a, b*c)
r = func(self, X, **kwargs)
if hasattr(r,'ndim'):
X = r.reshape(a, b, c)
return X
else:
return r
return wrapper
然后在函数上使用它,例如fit
@flat
def fit(self, X, y=None):
"""Compute the mean and std to be used for later scaling.
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
y : Passthrough for ``Pipeline`` compatibility.
"""
# Reset internal state before fitting
self._reset()
return self.partial_fit(X, y)
效果很好;使用与上面相同的脚本,我得到了
[[[ 3. 5.]
[ 6. 2.]]
[[ 8. 23.]
[ 7. 23.]]
[[ 3. 4.]
[ 2. 55.]]]
[[[-0.70710678 -0.64906302]
[ 0.46291005 -1.13191668]]
[[ 1.41421356 1.41266656]
[ 0.9258201 -0.16825789]]
[[-0.70710678 -0.76360355]
[-1.38873015 1.30017457]]]
但要注意,它不检查2d数组,它无法处理。因此,使用普通的预处理模块进行二维数组!