我正在尝试为二分类问题构建决策树分类器。我的数据集是不平衡的(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 177weighted avg 0.89 0.89 0.89 177Train Accuracy 0.9510357815442562Test Accuracy: 0.8870056497175142roc_auc_score 0.8868105209397344
为了检查是否存在过拟合问题,我计算了训练和测试的准确率,我认为我并没有过度过拟合。
然后我绘制了可能导致过拟合的树深度,代码如下
#设置数组来存储训练和测试准确率dep = np.arange(1, 50)train_accuracy = np.empty(len(dep))test_accuracy = np.empty(len(dep))# 循环遍历不同的k值for i, k in enumerate(dep): model=best_model.fit(X_train,Y_train) y_pred = model.predict(X_test) #计算训练集上的准确率 train_accuracy[i] = model.score(X_train,Y_train) #计算测试集上的准确率 test_accuracy[i] = model.score(X_test, Y_test)# 生成图表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()
图表非常奇怪,我无法解释它。
请帮助我
回答:
仔细查看你的for
循环,你会发现你总是只训练了同一个模型;以下这行代码:
model=best_model.fit(X_train,Y_train)
并不依赖于你的k
,也不影响max_depth
参数,而这正是你实际想要做的。
因此,你的(训练和测试)准确率的所有值都是相同的,因此出现了“奇怪”的直线(即常数值)。
我猜你想要的是获取你从交叉验证中找到的最佳参数和不同深度下的性能指标;但问题在于max_depth
已经包含在你的best_parameters
中,所以你的方法看起来相当模糊…