Scikit-learn:如何水平标准化行值?

时间:2016-01-13 06:10:39

标签: python numpy scikit-learn

我想将水平值而不是垂直值标准化。代码读取代码后提供的csv文件,并输出具有规范化值的新csv文件。如何使其水平标准化?鉴于以下代码:

代码

#norm_code.py
#normalization = x-min/max-min

import numpy as np
from sklearn import preprocessing
all_data=np.loadtxt(open("c:/Python27/test.csv","r"),
delimiter=",",
skiprows=0,
dtype=np.float64)

x=all_data[:]

print('total number of samples (rows):', x.shape[0])
print('total number of features (columns):', x.shape[1])
minmax_scale = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(x)

X_minmax=minmax_scale.transform(x)
with open('test_norm.csv',"w") as f:
    f.write("\n".join(",".join(map(str, x)) for x in (X_minmax)))

test.csv

1   2   0   4   3
3   2   1   1   0
2   1   1   0   1

2 个答案:

答案 0 :(得分:4)

您可以简单地对转置进行操作,并对结果进行转置:

minmax_scale = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(x.T)

X_minmax=minmax_scale.transform(x.T).T

答案 1 :(得分:2)

Oneliner在不使用sklearn的情况下回答:

X_minmax = np.transpose( (x-np.min(x,axis=1))/(np.max(x, axis=1)-np.min(x,axis=1)))

这比使用预处理的MinMaxScaler快约8倍。