from imblearn.over_sampling import SMOTE from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, recall_score, f1_score # 加载数据集并划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 使用SMOTE算法进行数据重采样 smote = SMOTE(random_state=42) X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train) # 训练逻辑回归模型 model = LogisticRegression(random_state=42) model.fit(X_train_resampled, y_train_resampled) # 在测试集上进行预测 y_pred = model.predict(X_test) # 计算评估指标 accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print("Accuracy: {:.2f}%, Recall: {:.2f}%, F1: {:.2f}%".format(accuracy*100, recall*100, f1*100))
# 训练逻辑回归模型并设置类别权重 model = LogisticRegression(random_state=42, class_weight="balanced") model.fit(X_train, y_train) # 在测试集上进行预测 y_pred = model.predict(X_test) # 计算评估指标 accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print("Accuracy: {:.2f}%, Recall: {:.2f}%, F1: {:.2f}%".format(accuracy*100, recall*100, f1*100))
from sklearn.ensemble import RandomForestClassifier # 训练随机森林模型 model = RandomForestClassifier(random_state=42) model.fit(X_train, y_train) # 在测试集上进行预测 y_pred = model.predict(X_test) # 计算评估指标 accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print("Accuracy: {:.2f}%, Recall: {:.2f}%, F1: {:.2f}%".format(accuracy*100, recall*100, f1*100))
以上が不均衡なデータセットに対処するための分類方法は何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。