python - 在 3D 数据上使用 Standardscaler

标签 python scikit-learn

我正在尝试使用 scikit-learn standardscaler 扩展具有多个特征和时间序列数据的数据集。目前我正在为每个功能创建一个单独的缩放器:

scale_feat1 = StandardScaler().fit(data[:,:,0])
scale_feat2 = StandardScaler().fit(data[:,:,1])
..

有没有一种方法可以使用一个缩放器分别缩放所有功能?另外,为所有功能保存缩放器并将其应用于验证数据集的最简单方法是什么?

编辑:Standardscaler 仅适用于二维数组,因此必须展平数组才能进行缩放。在 2D Standardscaler 中,为每个特征创建一个单独的均值和标准差

最佳答案

假设您的数据被整形为[num_instances, num_time_steps, num_features] 我会做的是首先 reshape 数据然后规范化数据。

import numpy as np
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
num_instances, num_time_steps, num_features = train_data.shape
train_data = np.reshape(train_data, shape=(-1, num_features))
train_data = scaler.fit_transform(train_data)

这将以每个特征为一列的格式 reshape 数据,并将分别对每个特征进行归一化。之后,您可以在训练前以相同的形状返回数据。

train_data = np.reshape(train_data, shape=(num_instances, num_time_steps, num_features))

当谈到在验证集上使用缩放器时,fit_transform 方法计算训练集上的meanstd 并且将它们存储在对象中。然后,当你想标准化验证集时,你可以这样做:

num_instances, num_time_steps, num_features = val_data.shape
val_data = np.reshape(val_data, shape=(-1, num_features))
val_data = scaler.transform(val_data)

然后将数据 reshape 为训练所需的形状。

val_data = np.reshape(val_data, shape=(num_instances, num_time_steps, num_features))

这应该可以解决问题。

更新:

根据@Medomatto 的评论,在以后的 numpy 版本中, reshape 的正确方法是:

... = np.reshape(data, newshape=(...))

关于python - 在 3D 数据上使用 Standardscaler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53870113/

相关文章:

python - Python中使用正则表达式进行批量替换

python - 如何在python中没有附加模块的情况下读取RGB图像(JPG)

python C扩展: multithreading and random numbers

控制台中文件夹目录的Python实现

python - 如何让文本对象与 sklearn 分类器管道一起工作?

python-3.x - Python 中的隔离森林

python - 如何从 MultiOutputRegressor 获取系数和特征重要性?

python - 托加染色?

python - 确定 k 均值聚类的准确性

python-3.x - 如何对多个属性进行机器学习(树)?