DAY 10

发布时间:2026/6/28 1:08:34

DAY 10 浙大疏锦行 导入所需库 import pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_reportimport warningswarnings.filterwarnings(‘ignore’) 1. 读取数据 file_path rC:\Python Study\Python60DaysChallenge-main\data.csvdf pd.read_csv(file_path) 2. 数据预处理 ---- 2.1 特殊异常值修正数据集特有问题 ----Current Loan Amount 中 99999999 是缺失值占位符替换为NaNdf[‘Current Loan Amount’] df[‘Current Loan Amount’].replace(99999999, np.nan)信用分正常范围300~850大于1000的属于输入错误多打1位除以10修正df[‘Credit Score’] df[‘Credit Score’].apply(lambda x: x/10 if x 1000 else x)---- 2.2 缺失值填充 ----分离数值型、分类型特征以及标签列label_col df.columns[-1] # 最后一列是违约标签0未违约1违约num_cols df.select_dtypes(include[‘int64’, ‘float64’]).columns.tolist()cat_cols df.select_dtypes(include[‘object’]).columns.tolist()num_cols.remove(label_col)num_cols.remove(‘ID’) # ID是样本标识不作为建模特征数值型用中位数填充分类型用众数填充for col in num_cols:df[col] df[col].fillna(df[col].median())for col in cat_cols:df[col] df[col].fillna(df[col].mode()[0])---- 2.3 异常值处理箱线图IQR法 迭代思想知识点1 ----原理小于 Q1-1.5IQR 或 大于 Q31.5IQR 判定为异常值迭代思想去除一次异常值后数据分布变化需重新计算分位数直到无新异常值def remove_outliers_iqr(data, cols, max_iter3):for i in range(max_iter):before_size len(data)for col in cols:Q1 data[col].quantile(0.25)Q3 data[col].quantile(0.75)IQR Q3 - Q1lower_bound Q1 - 1.5 * IQRupper_bound Q3 1.5 * IQR# 保留非异常值样本data data[(data[col] lower_bound) (data[col] upper_bound)]after_size len(data)print(f第{i1}次迭代去异常值样本量从 {before_size} → {after_size})if before_size after_size: # 无新异常值停止迭代breakreturn datadf_clean remove_outliers_iqr(df, num_cols, max_iter3)print(f异常值处理完成剩余样本数{len(df_clean)}\n)---- 2.4 分类变量独热编码 ----df_encoded pd.get_dummies(df_clean, columnscat_cols, drop_firstTrue)分离特征矩阵X和标签yX df_encoded.drop([‘ID’, label_col], axis1)y df_encoded[label_col] 3. 数据集划分知识点2 按7:3划分训练集和测试集stratifyy保证正负样本比例和原数据一致X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42, stratifyy)print(f训练集样本数{X_train.shape[0]}“)print(f测试集样本数{X_test.shape[0]}\n”) 4. 数据标准化知识点3避免数据泄露 关键原则先划分数据集再做归一化仅用训练集拟合标准化器测试集只做转换防止测试集的统计信息泄露到训练中scaler StandardScaler()X_train_scaled scaler.fit_transform(X_train) # 训练集拟合转换X_test_scaled scaler.transform(X_test) # 测试集仅转换 5. 模型训练知识点4三行代码建模 第1行实例化逻辑回归模型二分类任务经典模型model LogisticRegression(random_state42, max_iter1000)第2行用训练集训练模型model.fit(X_train_scaled, y_train)第3行输出测试集预测结果y_pred model.predict(X_test_scaled) 6. 模型评估知识点56 ---- 6.1 准确率 ----acc accuracy_score(y_test, y_pred)print(f模型整体准确率{acc:.4f}\n)---- 6.2 混淆矩阵 ----cm confusion_matrix(y_test, y_pred)print(“混淆矩阵”)print(cm)print(f真阴性(TN):{cm[0][0]} | 实际未违约预测未违约)print(f假阳性(FP):{cm[0][1]} | 实际未违约预测违约)print(f假阴性(FN):{cm[1][0]} | 实际违约预测未违约)print(f真阳性(TP):{cm[1][1]} | 实际违约预测违约\n)---- 6.3 分类报告知识点6分类报告解读 ----print(“”*50)print(“分类报告”)print(classification_report(y_test, y_pred))print(“”*50)print(“分类报告指标说明”)print(“1. precision精确率:预测为违约的样本里真实违约的比例代表预测的准度”“)print(“2. recall召回率:真实违约的样本里被正确预测的比例代表对违约用户的查全度””)print(“3. f1-score:精确率和召回率的调和平均数综合衡量模型性能”)print(“4. support:对应类别在真实标签中的样本数量”)print(“5. accuracy:整体准确率所有预测正确的样本占总样本的比例”)print(“6. macro avg:宏平均不考虑样本量对两类指标直接取平均”)print(“7. weighted avg:加权平均按样本量占比加权适合样本不平衡场景”)

相关新闻