3

我面临的问题是,我在处理极其不平衡的数据集时使用 imblearn 管道和使用 sklearn gridsearchcv 执行了网格搜索,但是当我尝试保存模型时,我收到错误“TypeError:不能pickle _thread.RLock 对象'。我用来保存模型的语句是

情况1:

import pickle

pickle.dump(grid_result,open(model_filename,'wb'))

案例2:

from sklearn.externals import joblib

joblib.dump(grid_result.best_estimator_, 'GS_obj.pkl')

1) 对于二元分类问题,我定义了模型架构,如下所示

构建函数来创建模型,KerasClassifier 需要

def create_model(optimizer_val='RMSprop',hidden_layer_size=16,activation_fn='relu',dropout_rate=0.1,regularization_fn=tf.keras.regularizers.l1(0.001),kernel_initializer_fn=tf.keras.initializers.glorot_uniform,bias_initializer_fn=tf.keras.initializers.zeros):

    model = tf.keras.models.Sequential([

    tf.keras.layers.Dropout(0.2),                                       

    tf.keras.layers.Input(shape=(D,)),

     tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), # 1st Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #2nd Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #3rd Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),   

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #4th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),       

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #5th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),       

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #6th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),         

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #7th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),       

    tf.keras.layers.Dense(units=1024, activation='relu',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #8th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),           

    tf.keras.layers.Dense(units=1024, activation=activation_fn,kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #9th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),     

    tf.keras.layers.Dense(units=1024, activation=activation_fn,kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn), #10th Layer

    tf.keras.layers.BatchNormalization(),   

    tf.keras.layers.Dropout(dropout_rate),   

   tf.keras.layers.Dense(units=1,activation='sigmoid',kernel_regularizer=regularization_fn,kernel_initializer=kernel_initializer_fn,bias_initializer=bias_initializer_fn) ])



    model.compile(optimizer=optimizer_val, loss='binary_crossentropy',metrics=['binary_accuracy'])

    return model



#Create the model with the wrapper

model = tf.keras.wrappers.scikit_learn.KerasClassifier(build_fn=create_model,verbose=2) #We donot specify batch_size and epochs here as it is part of the parameter grid

2)构建参数搜索网格,如下所示

初始化参数网格

nn_param_grid = {

    'NN_clf__epochs': [500],     

    'NN_clf__batch_size':[32],

    'NN_clf__optimizer_val': ['Adam','SGD'],

    'NN_clf__hidden_layer_size': [1024],

    'NN_clf__activation_fn': ['relu'],     

    'NN_clf__dropout_rate': [0.5],   

    'NN_clf__regularization_fn':['L1L2'],

    'NN_clf__kernel_initializer_fn':['glorot_normal', 'glorot_uniform'], #Works   

    'NN_clf__bias_initializer_fn':[tf.keras.initializers.zeros]   

}

2) 实例化管道并执行 GridSearch,如下所示

实例化 SMOTE 对象

smote_obj=SMOTE(sampling_strategy='minority',random_state=42,n_jobs=-1)

实例化缩放器对象

scaler_obj=StandardScaler()

实例化管道

steps = [('standardize', scaler_obj),('oversample', smote_obj),('NN_clf', model)]

pipe_clf = Pipeline(steps)

pipe_clf

执行 GridSearchCV

grid = GridSearchCV(estimator=pipe_clf, param_grid=nn_param_grid, verbose=2, cv=10,scoring='precision',return_train_score=False,n_jobs=-1) 

grid_result = grid.fit(X_train, y_train)

请告知如何使用下面给出的方法保存模型,我无法保存模型并收到错误“TypeError: can't pickle _thread.RLock objects”

情况1:

import pickle

pickle.dump(grid_result,open(model_filename,'wb'))

案例2:

from sklearn.externals import joblib

joblib.dump(grid_result.best_estimator_, 'GS_obj.pkl')

谢谢

苏拉吉特

4

0 回答 0