python模型保存并调用——joblib模块

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


背景

用已知的数据集经过反复调优后,训练出一个较为精准的模型,想要用来对格式相同的新数据进行预测或分类。难道又要重复运行用于训练模型的源数据和代码?

常见的做法是将其训练好模型封装成一个模型文件,直接调用此模型文件用于后续的训练 。


一、保存最佳模型

dump

  • joblib.dump(value,filename,compress=0,protocol=None)
    • value:任何Python对象,要存储到磁盘的对象。
    • filename:文件名,str.pathlib.Path 或文件对象。要在其中存储文件的文件对象或文件路径。与支持的文件扩展名之一(“.z”,“.gz”,“bz2”,“.xz”,“.lzma”)
    • compress:int从0到9或bool或2元组。数据的可选压缩级别。0或False不压缩,较高的值表示更多的压缩,但同时也降低了读写时间。使用3值通常是一个很好的折衷方案。如果compress为True,则使用的压缩级别为3。如果compress为2元组,则第一个元素必须对应于受支持的压缩器之间的字符串(例如’zlib’,‘gzip’,‘bz2’,‘lzma’,'xz '),第二个元素必须是0到9的整数,对应于压缩级别。
    • protocol:不用管了,与pickle里的protocol参数一样

举例

  1. 导入数据
import pandas as pd

# 训练集
file_pos="F:\\python_machine_learing_work\\501_model\\data\\训练集\\train_data_only_one.csv"
data_pos=pd.read_csv(file_pos,encoding='utf-8')

# 测试集
val_pos="F:\\python_machine_learing_work\\501_model\\data\\测试集\\test_data_table_only_one.csv"
data_val=pd.read_csv(val_pos,encoding='utf-8')
  1. 划分数据
# 重要变量
ipt_col=['called_rate', 'calling_called_act_hour', 'calling_called_distinct_rp', 'calling_called_distinct_cnt', 'star_level_int', 'online_days', 'calling_called_raom_cnt', 'cert_cnt', 'white_flag_0', 'age', 'calling_called_cdr_less_15_cnt', 'white_flag_1', 'calling_called_same_area_rate', 'volte_cnt', 'cdr_duration_sum', 'calling_hour_cnt', 'cdr_duration_avg', 'calling_pre7_rate', 'cdr_duration_std', 'calling_disperate', 'calling_out_area_rate', 'calling_distinct_out_op_area_cnt','payment_type_2.0', 'package_price_group_2.0', 'is_vice_card_1.0']

#拆分数据集(一个训练集一个测试集)
def train_test_spl(train_data,val_data):
    global ipt_col
    X_train=train_data[ipt_col]
    X_test=val_data[ipt_col]
    y_train=train_data[target_col]
    y_test=val_data[target_col]
    return X_train, X_test, y_train, y_test

	X_train, X_test, y_train, y_test =train_test_spl(data_pos_4,data_val_4)
  1. 训练模型
from sklearn.model_selection import GridSearchCV
def model_train(X_train,y_train,model):
    ## 导入XGBoost模型
    from xgboost.sklearn import XGBClassifier


    if  model=='XGB':
        parameters = {
    
    'max_depth': [3,5, 10, 15, 20, 25],
          			  'learning_rate':[0.1, 0.3, 0.6],
          			  'subsample': [0.6, 0.7, 0.8, 0.85, 0.95],
              		  'colsample_bytree': [0.5, 0.6, 0.7, 0.8, 0.9]}
      
        xlf= XGBClassifier(n_estimators=50)
        grid = GridSearchCV(xlf, param_grid=parameters, scoring='accuracy', cv=3)
        grid.fit(X_train, y_train)
        best_params=grid.best_params_
        res_model=XGBClassifier(max_depth=best_params['max_depth'],learning_rate=best_params['learning_rate'],subsample=best_params['subsample'],colsample_bytree=best_params['colsample_bytree'])
        res_model.fit(X_train, y_train)

    else:
        pass
    return res_model

xgb_model= model_train(X_train, y_train, model='XGB') 
  1. 保存模型
# 导入包
import joblib 

# 保存模型
joblib.dump(xgb_model, 'train_rf_importance_model.dat', compress=3) 

二、加载模型并用于预测

load

  • joblib.load(filename, mmap_mode=None)
    • filename:str.pathlib.Path或文件对象。要从中加载对象的文件或文件路径。
    • mmap_mode:{无,‘r +’,‘r’,‘w +’,‘c’},可选如果不是“None”,则从磁盘对阵列进行内存映射。此模式对压缩文件无效。请注意,在这种情况下,重建对象可能不再与原始对象完全匹配。
  1. 加载模型
# 加载模型
load_model_xgb_importance = joblib.load("F:\\python_machine_learing_work\\501_model\\data\\测试集\\train_xgb_importance_model.dat")

# 使用模型预测
y_pred_rf = model_predict(load_model_xgb_importance, X_test, alpha = alpha)

猜你喜欢

转载自blog.csdn.net/sodaloveer/article/details/129857727