Tôi đang đào tạo BDT bằng XGBoost để thực hiện phân loại nhị phân trên 22 tính năng. Tôi có 18 triệu mẫu. [60% cho đào tạo, 40% cho kiểm tra]
ROC AUC mà tôi nhận được trong quá trình đào tạo không phù hợp với kết quả cuối cùng mà tôi nhận được và tôi không hiểu điều này có thể xảy ra như thế nào. Ngoài ra, ROC AUC cho thấy tập luyện quá sức nhiều hơn bất kỳ số liệu nào khác và dường như nó có mức tối đa trên dữ liệu thử nghiệm
Có ai từng gặp sự cố tương tự trước đây hoặc có bất kỳ ý tưởng nào về vấn đề xảy ra với mô hình của tôi hay cách tôi có thể tìm ra lỗi không?
Đường cong ROC và AUC [Diện tích dưới đường cong] là những cách đơn giản để xem kết quả của bộ phân loại
Đường cong ROC rất hữu ích khi xem mô hình của bạn hoạt động như thế nào ở các mức tỷ lệ dương tính giả khác nhau và AUC rất hữu ích khi bạn cần báo cáo một con số duy nhất để cho biết mô hình của bạn hoạt động tốt như thế nào
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
# load data
X_train, X_test, y_train, y_test = load_my_data[]
# model can be any trained classifier that supports predict_proba[]
clf = LogisticRegression[]
clf.fit[X_train, y_train]
y_preds = clf.predict_proba[X_test]
# take the second column because the classifier outputs scores for
# the 0 class as well
preds = y_preds[:,1]
# fpr means false-positive-rate
# tpr means true-positive-rate
fpr, tpr, _ = metrics.roc_curve[y_test, preds]
auc_score = metrics.auc[fpr, tpr]
# clear current figure
plt.clf[]
plt.title['ROC Curve']
plt.plot[fpr, tpr, label='AUC = {:.2f}'.format[auc_score]]
# it's helpful to add a diagonal to indicate where chance
# scores lie [i.e. just flipping a coin]
plt.plot[[0,1],[0,1],'r--']
plt.xlim[[-0.1,1.1]]
plt.ylim[[-0.1,1.1]]
plt.ylabel['True Positive Rate']
plt.xlabel['False Positive Rate']
plt.legend[loc='lower right']
plt.show[]
Đây là tập dữ liệu giả.
Kết quả tìm kiếm ô lưới
Sẽ rất hữu ích khi xem kết quả cho tất cả các lần chạy tìm kiếm dạng lưới
Xem đầu ra đầy đủ trên máy tính xách tay jupyter này
Đây là một cách để làm điều đó. tạo nhiều ô bằng cách sử dụng plt.subplots[]
và vẽ kết quả cho từng ô với tiêu đề là cấu hình lưới hiện tại
import matplotlib.pyplot as plt
import math
from sklearn import metrics
from sklearn.model_selection import ParameterGrid, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_classification
# load data
X, y = make_classification[n_samples=10000,
n_features=25,
n_redundant=10,
n_repeated=5,
class_sep=0.2,
flip_y=0.1]
X_train, X_test, y_train, y_test = train_test_split[X, y, test_size=0.35]
# out pipeline has uses PCA for preprocessing then
# a gradient boosting classifier
param_grid = [
{
'pca__n_components':[5,10,20],
'clf__n_estimators':[5,20,50,100,200],
'clf__max_depth':[1,2,3,4]
}
]
pipeline = Pipeline[[
['pca',PCA[]],
['clf',GradientBoostingClassifier[]]
]]
Khi đường ống và lưới tham số được tạo [khối mã trước đó], hãy tiến hành như sau
Tạo một ô để chứa tất cả các ô con
Lặp lại mỗi lần chạy của lưới bằng cách sử dụng
ParameterGrid
Trong mỗi vòng lặp, làm
- Huấn luyện/ghi điểm bộ phân loại cho cấu hình tham số hiện tại
- Vẽ hiệu suất cho cấu hình hiện tại
# now plotting:
num_cols = 3
num_rows = math.ceil[len[ParameterGrid[param_grid]] / num_cols]
# create a single figure
plt.clf[]
fig,axes = plt.subplots[num_rows,num_cols,sharey=True]
fig.set_size_inches[num_cols*5,num_rows*5]
for i,g in enumerate[ParameterGrid[param_grid]]:
pipeline.set_params[**g]
pipeline.fit[X_train,y_train]
y_preds = pipeline.predict_proba[X_test]
# take the second column because the classifier outputs scores for
# the 0 class as well
preds = y_preds[:,1]
# fpr means false-positive-rate
# tpr means true-positive-rate
fpr, tpr, _ = metrics.roc_curve[y_test, preds]
auc_score = metrics.auc[fpr, tpr]
ax = axes[i // num_cols, i % num_cols]
# don't print the whole name or it won't fit
ax.set_title[str[[r"{}:{}".format[k.split['__'][1:],v] for k,v in g.items[]]],fontsize=9]
ax.plot[fpr, tpr, label='AUC = {:.3f}'.format[auc_score]]
ax.legend[loc='lower right']
# it's helpful to add a diagonal to indicate where chance
# scores lie [i.e. just flipping a coin]
ax.plot[[0,1],[0,1],'r--']
ax.set_xlim[[-0.1,1.1]]
ax.set_ylim[[-0.1,1.1]]
ax.set_ylabel['True Positive Rate']
ax.set_xlabel['False Positive Rate']
plt.gcf[].tight_layout[]
plt.show[]
Kết quả sẽ như thế này
Một biểu đồ được vẽ cho mỗi cấu hình trong tìm kiếm dạng lưới.
Lưu ý rằng tiêu đề của mỗi ô là cấu hình của lưới ở bước đó.
Sơ đồ tầm quan trọng của tính năng XGBoost
Sử dụng dữ liệu từ cuộc thi Kaggle titanic
Sử dụng
import matplotlib.pyplot as plt
import math
from sklearn import metrics
from sklearn.model_selection import ParameterGrid, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_classification
# load data
X, y = make_classification[n_samples=10000,
n_features=25,
n_redundant=10,
n_repeated=5,
class_sep=0.2,
flip_y=0.1]
X_train, X_test, y_train, y_test = train_test_split[X, y, test_size=0.35]
# out pipeline has uses PCA for preprocessing then
# a gradient boosting classifier
param_grid = [
{
'pca__n_components':[5,10,20],
'clf__n_estimators':[5,20,50,100,200],
'clf__max_depth':[1,2,3,4]
}
]
pipeline = Pipeline[[
['pca',PCA[]],
['clf',GradientBoostingClassifier[]]
]]
0 để tạo từ điển liên kết tên biến [trong khung dữ liệu gấu trúc] và tầm quan trọng của biếnMã đầy đủ có thể được tìm thấy ở đây. cốt truyện quan trọng-xgb. ipynb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
# this is the titanic train set
df = pd.read_csv['train.csv']
# let's just use 'Fare' and 'Age' features
data=df[['Age','Fare']]
target = df['Survived']
X_train, X_test, y_train, y_test = train_test_split[data.values, target.values, test_size=0.4]
clf = XGBClassifier[]
clf.fit[X_train,y_train]
# build importance data
importance_data = sorted[list[zip[data.columns,clf.feature_importances_]],key=lambda tpl:tpl[1],reverse=True]
xs = range[len[importance_data]]
labels = [x for [x,_] in importance_data]
ys = [y for [_,y] in importance_data]
# plot
plt.clf[]
plt.bar[xs,ys,width=0.5]
plt.xticks[xs,labels]
plt.show[]
Vẽ biểu đồ tầm quan trọng của tính năng phân loại
Sử dụng dữ liệu từ cuộc thi Kaggle titanic
Như trên, chúng tôi xây dựng các mức độ quan trọng của biến nhưng chúng tôi cũng hợp nhất với nhau trong khung dữ liệu
XGBoost xử lý các biến được mã hóa một lần một cách riêng biệt, nhưng có thể bạn muốn xem toàn bộ tầm quan trọng của từng biến phân loại nói chung
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
# this is the titanic train set
df = pd.read_csv['train.csv']
# select the columns we will use
df = df[['Pclass','Sex','SibSp','Embarked','Age','Fare','Survived']]
# one-hot-encode categorical variables
# note that we use each variable name as the prefix for dummy variables
df = pd.concat[[df,pd.get_dummies[df['Pclass'], prefix='Pclass',dummy_na=True]],axis=1].drop[['Pclass'],axis=1]
df = pd.concat[[df,pd.get_dummies[df['Sex'], prefix='Sex',dummy_na=True]],axis=1].drop[['Sex'],axis=1]
df = pd.concat[[df,pd.get_dummies[df['SibSp'], prefix='SibSp',dummy_na=True]],axis=1].drop[['SibSp'],axis=1]
df = pd.concat[[df,pd.get_dummies[df['Embarked'], prefix='Embarked',dummy_na=True]],axis=1].drop[['Embarked'],axis=1]
data=df.drop[['Survived'],axis=1]
target = df['Survived']
X_train, X_test, y_train, y_test = train_test_split[data.values, target.values, test_size=0.4]
clf = XGBClassifier[]
clf.fit[X_train,y_train]
tại thời điểm này, chúng tôi sẽ sửa đổi lệnh quan trọng của tính năng để chúng tôi nhận được tổng các mức độ quan trọng cho từng biến phân loại
# clf should be a trained classifier
# data is a dataframe with ONLY features, no target variables od IDs
# define the base names for each variables
categorical_columns_names = ['Pclass','Sex','SibSp','Embarked']
importances_dict = dict[zip[data.columns,clf.feature_importances_]]
for column_name in categorical_columns_names:
all_values_sum = 0
for key,value in list[importances_dict.items[]]:
if key.startswith[column_name]:
all_values_sum += importances_dict[key]
del[importances_dict[key]]
importances_dict[column_name] = all_values_sum
# now we proceed the same as in the previous example, but using the
# modified importance we calculated above
importance_data = sorted[list[importances_dict.items[]],key=lambda tpl:tpl[1],reverse=True]
xs = range[len[importance_data]]
labels = [x for [x,_] in importance_data]
ys = [y for [_,y] in importance_data]
# plot
plt.bar[xs,ys,width=0.5]
plt.xticks[xs,labels]
plt.show[]
và sử dụng chúng trong Tăng cường độ dốc,
tầm quan trọng được tính riêng
for each possible category value. This
làm cho khó thấy tầm quan trọng của từng
biến phân loại.
các giá trị sao cho tổng của tất cả các giá trị
trong một danh mục được hiển thị.
[Dễ hình dung hơn nhiều]
Vẽ ma trận nhầm lẫn
Một cách đầy đủ hơn để vẽ ma trận nhầm lẫn có sẵn trong thư viện python-ds-util
Ma trận nhầm lẫn rất hữu ích để thông báo những loại lỗi mà mô hình của bạn có xu hướng mắc phải
Chúng hoạt động để phân loại nhị phân và phân loại nhiều lớp
Thí dụ. Huấn luyện trình phân loại xgboost trên dữ liệu đa lớp giả và ma trận nhầm lẫn biểu đồ, với nhãn và thanh màu ở bên phải của biểu đồ