我有一个与 this topic 非常相似的问题但我想重用 StandardScaler 而不是 LabelEncoder。这是我所做的:
# in one program
dict = {"mean": scaler.mean_, "var": scaler.var_}
# and save the dict
# in another program
# load the dict first
new_scaler = StandardScaler()
new_scaler.mean_ = dict['mean'] # Hoever it doesn't work
new_scaler.var_ = dict['var'] # Doesn't work either...
我也试过 set_params 但它只能更改这些参数:copy、with_mean 和 with_std。
那么,我怎样才能重新使用我在程序一中得到的定标器呢?谢谢!
请您参考如下方法:
只是pickle 整件事。
关注官方docs .
您可以使用第一个链接中的 python standard-pickle 或第二个链接中提到的专门的 joblib-pickle(我推荐;通常效率更高,尽管对于这种简单的对象 = 缩放器并不那么重要):
import joblib
import sklearn.preprocessing as skp
new_scaler = skp.StandardScaler()
# ...fit it... do something ...
joblib.dump(new_scaler , 'my_scaler.pkl') # save to disk
loaded_scaler = joblib.load('my_scaler.pkl') # load from disk
如果您偶然想将您的 sklearn-objects 存储在 MySQL、MongoDB、Redis 等数据库中,上面使用基于文件的存储的示例当然是行不通的。
那么简单的方法是:使用 python-pickle 的 dumps它将转储到一个字节对象(为大多数 DB 包装器做好准备)。
为了更高效的joblib,你必须使用python的BytesIO以类似的方式使用它(因为该方法本身是基于文件的,但可以用于类似文件的对象)。
