import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# 加载数据
df = pd.read_csv("C:\\Users\吴鑫\Desktop\数据挖掘\数据挖掘课程设计\学生成绩预测.csv") # 需将学生成绩预测.csv这个文件放在该路径下
# 查看数据
print(df.head())
# 对'Class'列进行编码(L, M, H -> 0, 1, 2)
le_class = LabelEncoder()
df['Class'] = le_class.fit_transform(df['Class'])
# 对'StudentAbsenceDays'列进行编码(Under-7, Above-7 -> 0, 1)
df['StudentAbsenceDays'] = df['StudentAbsenceDays'].map({'Under-7': 0, 'Above-7': 1})
# 选择特征列和目标列
X = df[['raisedhands', 'VisITedResources', 'AnnouncementsView', 'Discussion', 'StudentAbsenceDays']]
y = df['Class']
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并训练随机森林分类器
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 评估模型
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
# 数据可视化:特征与成绩等级的关系
plt.figure(figsize=(12, 8))
sns.pairplot(df[['raisedhands', 'VisITedResources', 'AnnouncementsView', 'Discussion', 'StudentAbsenceDays', 'Class']],
hue='Class', palette='coolwarm')
plt.show()
# 结果可视化:混淆矩阵
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(10, 7))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()
# 将混淆矩阵的数值转换回成绩等级(L, M, H)
class_labels = le_class.inverse_transform([0, 1, 2])
cm_df = pd.DataFrame(cm, index=class_labels, columns=class_labels)
print(cm_df)