训练和测试准确性图显示异常行为

时间:2019-03-08 17:35:20

标签: python machine-learning scikit-learn decision-tree

我正在尝试为二进制分类问题构建决策树分类器。我的数据集不平衡(1 = 173和0 = 354),我使用了重采样方法来增加少数族裔并使他们保持平衡。我使用gridSearchCv和我的代码构建模型

x=df_balanced["x"]
y=df_balanced['y']

X_train, X_test, Y_train, Y_test = model_selection.train_test_split( x, y, stratify=y, random_state=42,test_size=0.25)

pipeline = Pipeline([
    ('vectorizer',CountVectorizer(stop_words='english')),
    ('classifier', DecisionTreeClassifier(random_state=42))])


grid = {
    'vectorizer__ngram_range': [(1, 1), (1, 2)],
    'vectorizer__analyzer':('word', 'char'),
    'classifier__max_depth':[15,20,25,30]
}

grid_search = GridSearchCV(pipeline, param_grid=grid, scoring='accuracy', n_jobs=-1, cv=5)
grid_search.fit(X_train,Y_train)
print(grid_search.best_estimator_,"\n")

best_parameters = grid_search.best_estimator_.get_params()
for param_name in sorted(list(grid.keys())):
    print("\t{0}: {1}".format(param_name, best_parameters[param_name]))
best_model = grid_search.best_estimator_
y_pred=best_model.predict(X_test)

confusion=confusion_matrix(Y_test, y_pred)
report=classification_report(Y_test,y_pred)
false_positive_rate, true_positive_rate, thresholds = roc_curve(Y_test, y_pred)
roc_auc = auc(false_positive_rate, true_positive_rate)
print("Confusion matrix \n",confusion,"\n")
print("Classification_report \n ",report,"\n")
print("Train Accuracy",accuracy_score(Y_train, best_model.predict(X_train)))
print("Test Accuracy:",accuracy_score(Y_test,y_pred))
print("roc_auc_score",roc_auc)

和输出。

Confusion matrix 
 [[82  7]
 [13 75]] 

Classification_report 
                precision    recall  f1-score   support

           0       0.86      0.92      0.89        89
           1       0.91      0.85      0.88        88

   micro avg       0.89      0.89      0.89       177
   macro avg       0.89      0.89      0.89       177
weighted avg       0.89      0.89      0.89       177


Train Accuracy 0.9510357815442562
Test Accuracy: 0.8870056497175142
roc_auc_score 0.8868105209397344

要检查我是否在过度拟合问题上失败,我计算了火车和测试的准确性,我认为我并不过分。

然后我绘制可能导致过度拟合的树的深度。 代码

 #Setup arrays to store train and test accuracies
dep = np.arange(1, 50)
train_accuracy = np.empty(len(dep))
test_accuracy = np.empty(len(dep))

# Loop over different values of k
for i, k in enumerate(dep):

    model=best_model.fit(X_train,Y_train)
    y_pred = model.predict(X_test)

    #Compute accuracy on the training set
    train_accuracy[i] = model.score(X_train,Y_train)

    #Compute accuracy on the testing set
    test_accuracy[i] = model.score(X_test, Y_test)

# Generate plot
plt.title('clf: Varying depth of tree')
plt.plot(dep, test_accuracy, label = 'Testing Accuracy')
plt.plot(dep, train_accuracy, label = 'Training Accuracy')
plt.legend()
plt.xlabel('Depth of tree')
plt.ylabel('Accuracy')
plt.show()

情节很奇怪,我无法解释。

enter image description here

任何帮助Plz

1 个答案:

答案 0 :(得分:2)

仔细查看您的for循环,您会发现自己始终只适合 same 模型;以下行:

model=best_model.fit(X_train,Y_train)

完全不依赖您的k,并且完全不影响max_depth参数,

因此,您(培训和测试)准确性的所有值都是相同的,因此是“奇怪的”直线(即恒定值)。

我想您想要的是从CV和不同深度获得最佳参数的性能指标;但是这里的问题是max_depth中已经包含了best_parameters,所以您的方法看起来很模糊...