from sklearn.utils import shuffle
df_concat = shuffle(df_concat)
df = df_concat
X = df.loc[:, df.columns != 'NEWACCT_NO']
X = X.loc[:, X.columns != 'CURRENT_MTH_CHURN']
X = X.values
y = df.CURRENT_MTH_CHURN.values # Target variable
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 1)
#Train the model with the help of DecisionTreeClassifie
clf = DecisionTreeClassifier(class_weight="balanced")
clf = clf.fit(X_train,y_train)
#At last we need to make prediction. It can be done with the help of following script −
y_pred = clf.predict(X_test)
#Next, we can get the accuracy score, confusion matrix and classification report as follows −
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
result = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2)
输出:
Confusion Matrix:
[[8238 0]
[ 0 1066]]
Classification Report:
precision recall f1-score support
0 1.00 1.00 1.00 8238
1 1.00 1.00 1.00 1066
accuracy 1.00 9304
macro avg 1.00 1.00 1.00 9304
weighted avg 1.00 1.00 1.00 9304
Accuracy: 1.0
即使train_test_split随机划分训练和测试数据,除此之外,我还使用了sklearn.utils shuffle,但我仍然获得了100%的测试数据准确性。
无法识别错误。
此外,尝试删除class_weight =“ balanced”参数,但结果相同。
请提供专家建议。
答案 0 :(得分:4)
您正在将数据拆分为训练和测试,但是显然所有功能生成已在此代码的上游完成。因此,如果您的任何功能生成代码都涉及以任何方式使用因变量(例如,像mean_churn_per_account_type
之类的var之类的东西),则意味着您的训练集功能会合并来自测试集的因变量的信息。在ML中,这称为“数据泄漏”-您通过在训练测试拆分之前创建的功能将测试集数据泄漏到训练集中。
要解决此问题,您需要将训练测试拆分移到涉及因变量的任何特征生成步骤的上游。将特征生成步骤完全应用于训练和测试集可能会导致跳闸-但是使用sklearn pipeline会有所帮助。
免责声明:这都是猜测,因为我们实际上看不到您的功能生成代码。但是根据我的经验,这是最有可能的来源。
答案 1 :(得分:0)
Ahh,按照建议,我检查了相关矩阵,并知道有一个名为“ IMAGE”的变量与CHURN变量具有-0.86的相关性。
一旦我将其删除,便能够获得令人满意的结果:
print(classification_report(test_output_smote, test_prediction_upsampled_smote))
precision recall f1-score support
N 0.74 0.84 0.79 8233
Y 0.81 0.71 0.76 8233
accuracy 0.78 16466
macro avg 0.78 0.78 0.77 16466
weighted avg 0.78 0.78 0.77 16466
谢谢大家的帮助与支持。