【问题标题】:Training and test accuracy plot shows strange behavior训练和测试准确度图显示奇怪的行为
【发布时间】:2019-07-30 18:49:04
【问题描述】:

我正在尝试为二元分类问题构建决策树分类器。我的数据集不平衡(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()

剧情很诡异,无法解释。

请帮帮忙

【问题讨论】:

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


    【解决方案1】:

    仔细观察您的for 循环,您会发现您总是适合相同 模型;以下行:

    model=best_model.fit(X_train,Y_train)
    

    不以任何方式依赖于您的 k 并且完全不影响 max_depth 参数,正如您实际打算做的那样。

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 2020-11-06
      • 2018-10-08
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      相关资源
      最近更新 更多