Joblib描述
Joblib是一组用于在Python中提供轻量级流水线的工具。
特点:
·透明的磁盘缓存功能和懒惰的重新评估(memoize模式)
·简单的并行计算
Joblib可以将模型保存到磁盘并可在必要时重新运行:
代码实现
#加载模块
from sklearn.datasets import load_iris
import joblib
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
#分割数据集
data = load_iris()
X = data.data
y = data.target
train_X,test_X,train_y,test_y = train_test_split(X,y,test_size=0.3,random_state=2)
#训练模型
lr = LinearRegression()
lr.fit(train_X,train_y)
#将训练的模型保存到磁盘(value=模型名) 默认当前文件夹下
joblib.dump(filename='LR.model',value=lr)
# 下载本地模型
model1 = joblib.load(filename="LR.model")
#对本地模型进行预测
print(model1.predict(test_X))
print(model1.score(test_X,test_y))
# 重新设置模型参数并训练
model1.set_params(normalize=True).fit(train_X,train_y)
#新模型做预测
print(model1.predict(test_X))
print(model1.score(test_X,test_y))
结果展示
[ 0.07145264 0.04505404 1.84184516 -0.07019985 0.10904718 1.55642666
0.00756981 1.76705607 1.93446083 0.04750114 -0.08284245 0.02393156
-0.10020463 0.06575346 1.40825647 1.30655593 0.08622949 1.2143428
2.1355411 1.20423688 1.49045338 1.12550814 1.96582271 1.23513179
1.18095234 0.05231031 -0.02521556 1.62175616 0.1687878 1.72140494
1.58393845 0.18697094 1.07567344 2.04256887 1.45651346 -0.24889011
1.99331133 1.30882831 1.2086435 1.83443025 1.36042253 1.15827289
2.05534495 0.9331102 0.03152131]
0.9286086986856661
[ 0.07145264 0.04505404 1.84184516 -0.07019985 0.10904718 1.55642666
0.00756981 1.76705607 1.93446083 0.04750114 -0.08284245 0.02393156
-0.10020463 0.06575346 1.40825647 1.30655593 0.08622949 1.2143428
2.1355411 1.20423688 1.49045338 1.12550814 1.96582271 1.23513179
1.18095234 0.05231031 -0.02521556 1.62175616 0.1687878 1.72140494
1.58393845 0.18697094 1.07567344 2.04256887 1.45651346 -0.24889011
1.99331133 1.30882831 1.2086435 1.83443025 1.36042253 1.15827289
2.05534495 0.9331102 0.03152131]
0.9286086986856662