【SVM class_weight 】MAP - Charting Student Math Misunderstandings

针对数据不平衡问题,用调整类别权重的方式来处理数据不平衡问题,同时使用支持向量机(SVM)模型进行训练。

我们通过使用 class_weight=‘balanced’ 来调整模型对少数类别的关注度。

import pandas as pd
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

# Step 1: Load the dataset
file_path = '/kaggle/input/map-charting-student-math-misunderstandings/train.csv'  # 修改为实际文件路径
data = pd.read_csv(file_path)

# Step 2: Clean the student explanation text (remove punctuation and lower case)
def clean_text(text):
    text = text.lower()  # Convert to lower case
    text = ''.join([char for char in text if char not in string.punctuation])  # Remove punctuation
    return text

# Apply the cleaning function to the 'StudentExplanation' column
data['cleaned_explanation'] = data['StudentExplanation'].apply(clean_text)

# Step 3: Feature extraction using TF-IDF
vectorizer = TfidfVectorizer(stop_words='english', max_features=5000)
X = vectorizer.fit_transform(data['cleaned_explanation'])

# Step 4: Prepare labels (Misconception column)
# We will predict if the explanation contains a misconception or not
data['Misconception'] = data['Misconception'].fillna('No_Misconception')

# Convert labels to binary: 'No_Misconception' -> 0, any other label -> 1
y = data['Misconception'].apply(lambda x: 0 if x == 'No_Misconception' else 1)

# Step 5: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 6: Train an SVM model with class_weight='balanced' to handle the data imbalance
svm_model_weighted = SVC(kernel='linear', class_weight='balanced', random_state=42)
svm_model_weighted.fit(X_train, y_train)

# Step 7: Make predictions
y_pred_svm_weighted = svm_model_weighted.predict(X_test)

# Step 8: Evaluate the model
print(classification_report(y_test, y_pred_svm_weighted))

# Step 9: Plot confusion matrix
cm_weighted = confusion_matrix(y_test, y_pred_svm_weighted)

# Use ConfusionMatrixDisplay to display the confusion matrix
disp = ConfusionMatrixDisplay(confusion_matrix=cm_weighted, display_labels=['No Misconception', 'Misconception'])
disp.plot(cmap=plt.cm.Blues)
plt.title('SVM Model with Balanced Class Weight Confusion Matrix')
plt.show()

 precision    recall  f1-score   support

           0       0.91      0.75      0.82      5277
           1       0.56      0.82      0.67      2063

    accuracy                           0.77      7340
   macro avg       0.74      0.78      0.74      7340
weighted avg       0.81      0.77      0.78      7340

请添加图片描述

### SVC `class_weight` 参数的作用 在构建支持向量分类器(SVC)时,类别不平衡是一个常见问题。当数据集中某些类别的样本数量远多于其他类别时,模型可能会偏向多数类而忽略少数类。为了应对这种情况,在 scikit-learn 中提供了 `class_weight` 参数来调整不同类别的权重。 通过设置 `class_weight` 参数可以赋予各个类别不同的惩罚系数,从而使得损失函数对于误分不同类别的代价有所区别。这有助于提高对较少见类别的识别能力[^2]。 #### 使用方法 可以直接指定字典形式的权值分配给特定标签: ```python from sklearn.svm import SVC clf = SVC(class_weight={0: 1, 1: 5}) ``` 上述代码表示如果错误地预测了第1类,则其成本将是错认第0类的五倍。 也可以使用 `'balanced'` 自动计算合适的权重比例: ```python from sklearn.svm import SVC clf = SVC(class_weight='balanced') ``` 在这种情况下,程序会自动根据训练集中的各类频率反比地设定相应的权重,即越少出现的类别会被给予更高的重视程度[^4]。 #### 实际案例展示 下面给出一段完整的 Python 代码用于演示如何利用 `class_weight` 来处理不均衡的数据集: ```python import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.svm import SVC # 创建模拟二元分类问题,其中正负样例数严重失衡 X, y = make_classification(n_samples=1000, n_features=20, weights=[0.9], flip_y=0) # 划分测试集合验证集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4) # 不加任何特殊处理的标准SVM svc_default = SVC() svc_default.fit(X_train, y_train) print("Default SVM:\n", classification_report(y_test, svc_default.predict(X_test))) # 应用了 'balanced' class weightSVM svc_balanced = SVC(class_weight="balanced") svc_balanced.fit(X_train, y_train) print("'Balanced' Weighted SVM:\n", classification_report(y_test, svc_balanced.predict(X_test))) ``` 这段脚本展示了两种情况下的性能差异——一种是没有特别对待类别不平衡的情况;另一种则是应用了平衡化策略之后的结果对比[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术与健康

你的鼓励将是我最大的创作动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值