我正在尝试使用joblib.dump使用以下代码保存训练好的GradientBoostingClassifier:
# use 90% of training data
NI=int(len(X_tr)*0.9)
I1=np.random.choice(len(X_tr),NI)
Xi=X_tr[I1,:]
Yi=Y_tr[I1]
#train a GradientBoostingCalssifier using that data
a=GradientBoostingClassifier(learning_rate=0.02, n_estimators=500, min_samples_leaf=50,presort=True,warm_start=True)
a.fit(Xi,Yi)
# calculate class probabilities for the remaining data
I2=np.array(list(set(range(len(X_tr)))-set(I1)))
Pi=np.zeros(len(X_tr))
Pi[I2]=a.predict_proba(X_tr[I2,:])[:,1].reshape(-1)
#save indexes of training data and the predicted probabilites
np.savetxt('models\\balanced\\GBT1\\oob_index'+str(j)+'.txt',I2)
np.savetxt('models\\balanced\\GBT1\\oob_m'+str(j)+'.txt',Pi)
# save the trained classifier
joblib.dump(a, 'models\\balanced\\GBT1\\m'+str(j)+'.pkl')
分类器经过训练和保存后,我关闭终端,打开一个新终端并运行以下代码加载分类器并在保存的测试数据集上进行测试
# load the saved class probabilities
Pi=np.loadtxt('models\\balanced\\GBT1\\oob_m'+str(j)+'.txt')
#load the training data index
Ii=np.loadtxt('models\\balanced\\GBT1\\oob_index'+str(j)+'.txt')
#load the trained model
a=joblib.load('models\\balanced\\GBT1\\m'+str(j)+'.pkl')
#predict class probabilities using the trained model
Pi1=a.predict_proba(X_tr[Ii,:])[:,1]
# Calculate aupr for the retrained model
_prec,_rec,_=metrics.precision_recall_curve(Y[Ii],Pi1,pos_label=1)
auc=metrics.auc(_rec,_prec);
# calculate aupr for the saved probabilities
_prec1,_rec1,_=metrics.precision_recall_curve(Y[Ii],Pi[Ii],pos_label=1)
auc1=metrics.auc(_rec1,_prec1);
print('in iteration ', j, ' aucs: ', auc, auc1)
代码打印以下内容: 在迭代0 aucs:0.0331879 0.0657821 ............................... 在所有情况下,重新加载的分类器的aupr与原始训练的分类器显着不同。我使用相同版本的sklearn和python进行加载和保存。我做错了什么?
答案 0 :(得分:1)
错误在您的代码中。我建议您使用train_test_split
拆分数据。它按default
以下代码为auc
指标生成相同的结果:
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import auc
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pickle
from sklearn.externals import joblib
def main():
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=.3)
clf = GradientBoostingClassifier()
clf.fit(X_train, y_train)
preds = clf.predict(X_test)
prec, rec, _ = precision_recall_curve(y_test, preds, pos_label=1)
with open('dump.pkl', 'wb') as f:
pickle.dump(clf, f)
print('AUC SCORE: ', auc(rec, prec))
clf2 = joblib.load('dump.pkl')
preds2 = clf2.predict(X_test)
prec2, rec2, _ = precision_recall_curve(y_test, preds2, pos_label=1)
print('AUC SCORE AFTER DUMP: ', auc(rec2, prec2))
if __name__ == '__main__':
main()
>>> AUC SCORE: 0.273271889401
>>> AUC SCORE AFTER DUMP: 0.273271889401