在sklearn中保存MinMaxScaler模型

时间:2017-02-02 03:07:26

标签: python machine-learning scikit-learn normalization

我在sklearn中使用MinMaxScaler模型来规范化模型的功能。

training_set = np.random.rand(4,4)*10
training_set

       [[ 6.01144787,  0.59753007,  2.0014852 ,  3.45433657],
       [ 6.03041646,  5.15589559,  6.64992437,  2.63440202],
       [ 2.27733136,  9.29927394,  0.03718093,  7.7679183 ],
       [ 9.86934288,  7.59003904,  6.02363739,  2.78294206]]


scaler = MinMaxScaler()
scaler.fit(training_set)    
scaler.transform(training_set)


   [[ 0.49184811,  0.        ,  0.29704831,  0.15972182],
   [ 0.4943466 ,  0.52384506,  1.        ,  0.        ],
   [ 0.        ,  1.        ,  0.        ,  1.        ],
   [ 1.        ,  0.80357559,  0.9052909 ,  0.02893534]]

现在我想使用相同的缩放器来规范化测试集:

   [[ 8.31263467,  7.99782295,  0.02031658,  9.43249727],
   [ 1.03761228,  9.53173021,  5.99539478,  4.81456067],
   [ 0.19715961,  5.97702519,  0.53347403,  5.58747666],
   [ 9.67505429,  2.76225253,  7.39944931,  8.46746594]]

但我不想这样,所以一直使用scaler.fit()和训练数据。有没有办法保存缩放器并稍后从其他文件加载?

5 个答案:

答案 0 :(得分:48)

甚至比pickle(创建比此方法更大的文件)更好,您可以使用sklearn的内置工具:

from sklearn.externals import joblib
scaler_filename = "scaler.save"
joblib.dump(scaler, scaler_filename) 

# And now to load...

scaler = joblib.load(scaler_filename) 

答案 1 :(得分:12)

所以我实际上不是这方面的专家,但是通过一些研究和一些有用的links,我认为picklesklearn.externals.joblib将成为你的朋友。

pickle允许您将模型或“转储”模型保存到文件中。

我认为这个link也很有帮助。它讨论了创建持久性模型。你想要尝试的东西是:

# could use: import pickle... however let's do something else
from sklearn.externals import joblib 

# this is more efficient than pickle for things like large numpy arrays
# ... which sklearn models often have.   

# then just 'dump' your file
joblib.dump(clf, 'my_dope_model.pkl') 

Here是您可以了解更多关于sklearn外部的信息。

如果这没有帮助,或者我不了解您的模型,请告诉我。

答案 2 :(得分:7)

您可以使用pickle来保存缩放器:

import pickle
scalerfile = 'scaler.sav'
pickle.dump(scaler, open(scalerfile, 'wb'))

加载回来:

import pickle
scalerfile = 'scaler.sav'
scaler = pickle.load(open(scalerfile, 'rb'))
test_scaled_set = scaler.transform(test_set)

答案 3 :(得分:2)

做到这一点的最佳方法是创建如下所示的ML管道:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib


pipeline = make_pipeline(MinMaxScaler(),YOUR_ML_MODEL() )

model = pipeline.fit(X_train, y_train)

现在您可以将其保存到文件中:

joblib.dump(model, 'filename.mod') 

以后您可以像这样加载它:

model = joblib.load('filename.mod')

答案 4 :(得分:0)

仅需注意,sklearn.externals.joblib已被弃用并由普通的旧joblib(可以与pip install joblib一起安装)取代:

import joblib
joblib.dump(my_scaler, 'scaler.pkl')
my_scaler = joblib.load('scaler.pkl')

有关joblib.dump()joblib.load()方法的文档。