解决不平衡分类问题的一种常见方法是使用权重来调整模型的训练过程。以下是一个包含代码示例的解决方法:
import numpy as np
from sklearn.model_selection import train_test_split
# 加载数据集
X = ...
y = ...
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
from sklearn.utils.class_weight import compute_class_weight
# 计算类别权重
class_weights = compute_class_weight('balanced', np.unique(y_train), y_train)
from sklearn.svm import SVC
# 定义模型
model = SVC(class_weight={0: class_weights[0], 1: class_weights[1]})
# 训练模型
model.fit(X_train, y_train)
from sklearn.metrics import classification_report
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 输出分类指标
print(classification_report(y_test, y_pred))
这是一种使用权重来解决不平衡分类问题的基本方法。可以根据具体情况进行调整和改进,例如使用其他的权重计算方法、尝试不同的分类算法等。