处理不平衡数据集的常用方法之一是通过网格搜索优化超参数。以下是一个示例代码,展示了如何使用网格搜索来优化超参数。
首先,导入必要的库和数据集。
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, make_scorer
from sklearn.model_selection import GridSearchCV
# 导入数据集
data = pd.read_csv('imbalanced_dataset.csv')
接下来,将数据集分为特征和目标变量,并将其划分为训练集和测试集。
# 将数据集划分为特征和目标变量
X = data.drop('target', axis=1)
y = data['target']
# 划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
定义一个评分函数,用于在网格搜索中评估模型的性能。在这个例子中,我们使用F1得分作为评估指标。
# 定义评分函数
scorer = make_scorer(f1_score)
然后,定义要调整的超参数和它们的候选值。
# 超参数候选值
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [None, 5, 10]
}
接下来,创建一个随机森林分类器对象,并使用GridSearchCV进行网格搜索。
# 创建随机森林分类器
rf = RandomForestClassifier()
# 进行网格搜索
grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, scoring=scorer)
grid_search.fit(X_train, y_train)
最后,输出最佳超参数和测试集上的F1得分。
# 输出最佳超参数
print("Best Parameters: ", grid_search.best_params_)
# 在测试集上评估模型性能
y_pred = grid_search.predict(X_test)
f1 = f1_score(y_test, y_pred)
print("F1 Score on Test Set: ", f1)
这是一个基本示例,展示了如何使用网格搜索来优化超参数以处理不平衡数据集。你可以根据自己的需求和数据集进行调整和扩展。