1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
| """ 红酒数据集分析:使用SVM和随机森林进行分类 数据清洗、异常值处理、标准化、模型训练与评估 """
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.preprocessing import StandardScaler, RobustScaler from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score from scipy import stats import warnings warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
def load_data(): """加载红酒数据集""" print("=" * 50) print("1. 加载红酒数据集") print("=" * 50) wine = load_wine() X = pd.DataFrame(wine.data, columns=wine.feature_names) y = pd.Series(wine.target, name='target') print(f"数据集形状: X={X.shape}, y={y.shape}") print(f"特征名: {wine.feature_names}") print(f"目标类别: {wine.target_names}") print(f"类别分布:\n{y.value_counts()}") df = X.copy() df['target'] = y return df, X, y, wine.feature_names, wine.target_names
def data_exploration(df): """数据探索性分析""" print("\n" + "=" * 50) print("2. 数据探索性分析") print("=" * 50) print("\n2.1 数据前5行:") print(df.head()) print("\n2.2 数据基本信息:") print(df.info()) print("\n2.3 描述性统计:") print(df.describe()) print("\n2.4 检查缺失值:") missing = df.isnull().sum() print(missing[missing > 0]) if missing.sum() == 0: print("没有缺失值!") fig, axes = plt.subplots(4, 4, figsize=(16, 12)) axes = axes.flatten() for i, col in enumerate(df.columns[:-1]): if i < len(axes): axes[i].hist(df[col], bins=30, edgecolor='black', alpha=0.7) axes[i].set_title(f'{col}分布', fontsize=10) axes[i].set_xlabel(col) axes[i].set_ylabel('频数') plt.tight_layout() plt.savefig('wine_feature_distributions.png', dpi=300) fig, axes = plt.subplots(4, 4, figsize=(16, 12)) axes = axes.flatten() for i, col in enumerate(df.columns[:-1]): if i < len(axes): axes[i].boxplot(df[col]) axes[i].set_title(f'{col}箱线图', fontsize=10) axes[i].set_ylabel(col) plt.tight_layout() plt.savefig('wine_boxplots.png', dpi=300) return df
def handle_outliers(df, feature_names): """异常值检测与处理""" print("\n" + "=" * 50) print("3. 异常值处理") print("=" * 50) df_clean = df.copy() outlier_info = {} for col in feature_names: Q1 = df_clean[col].quantile(0.25) Q3 = df_clean[col].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR outliers = df_clean[(df_clean[col] < lower_bound) | (df_clean[col] > upper_bound)] outlier_info[col] = { 'count': len(outliers), 'percentage': len(outliers) / len(df_clean) * 100, 'lower_bound': lower_bound, 'upper_bound': upper_bound } outlier_df = pd.DataFrame(outlier_info).T print("\n3.1 基于IQR的异常值统计:") print(outlier_df[['count', 'percentage']]) high_outlier_cols = outlier_df[outlier_df['percentage'] > 5].index.tolist() if high_outlier_cols: print(f"\n异常值比例超过5%的特征: {high_outlier_cols}") z_scores = np.abs(stats.zscore(df_clean[feature_names])) outliers_z = (z_scores > 3).sum(axis=0) print("\n3.2 基于Z-score的异常值统计 (|Z| > 3):") for i, col in enumerate(feature_names): if outliers_z[i] > 0: print(f"{col}: {outliers_z[i]} 个异常值 ({outliers_z[i]/len(df_clean)*100:.2f}%)") print("\n3.3 异常值处理: 用中位数替换IQR检测到的异常值") for col in feature_names: Q1 = df_clean[col].quantile(0.25) Q3 = df_clean[col].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR median_val = df_clean[col].median() mask = (df_clean[col] < lower_bound) | (df_clean[col] > upper_bound) if mask.any(): df_clean.loc[mask, col] = median_val print(f"{col}: 替换了 {mask.sum()} 个异常值") print("\n3.4 处理后的异常值检查:") for col in feature_names: Q1 = df_clean[col].quantile(0.25) Q3 = df_clean[col].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR outliers = df_clean[(df_clean[col] < lower_bound) | (df_clean[col] > upper_bound)] if len(outliers) > 0: print(f"{col}: 仍有 {len(outliers)} 个异常值") else: print(f"{col}: 无异常值") return df_clean
def feature_scaling(X_train, X_test): """特征标准化处理""" print("\n" + "=" * 50) print("4. 特征标准化处理") print("=" * 50) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) print("使用StandardScaler进行标准化:") print(f"训练集形状: {X_train_scaled.shape}") print(f"测试集形状: {X_test_scaled.shape}") print(f"训练集均值 (标准化后): {np.mean(X_train_scaled, axis=0)[:5]}...") print(f"训练集标准差 (标准化后): {np.std(X_train_scaled, axis=0)[:5]}...") return X_train_scaled, X_test_scaled, scaler
def train_svm(X_train, y_train, X_test, y_test): """训练SVM模型""" print("\n" + "=" * 50) print("5. SVM模型训练与评估") print("=" * 50) print("\n5.1 基础SVM模型:") svm_basic = SVC(kernel='rbf', random_state=42) svm_basic.fit(X_train, y_train) y_train_pred = svm_basic.predict(X_train) y_test_pred = svm_basic.predict(X_test) train_accuracy = accuracy_score(y_train, y_train_pred) test_accuracy = accuracy_score(y_test, y_test_pred) print(f"训练集准确率: {train_accuracy:.4f}") print(f"测试集准确率: {test_accuracy:.4f}") print("\n5.2 交叉验证 (5折):") cv_scores = cross_val_score(svm_basic, X_train, y_train, cv=5, scoring='accuracy') print(f"交叉验证准确率: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})") print("\n5.3 网格搜索优化超参数...") param_grid = { 'C': [0.1, 1, 10, 100], 'gamma': [0.001, 0.01, 0.1, 1], 'kernel': ['rbf', 'linear'] } grid_search = GridSearchCV(SVC(random_state=42), param_grid, cv=5, scoring='accuracy', n_jobs=-1) grid_search.fit(X_train, y_train) print(f"最佳参数: {grid_search.best_params_}") print(f"最佳交叉验证准确率: {grid_search.best_score_:.4f}") svm_best = grid_search.best_estimator_ y_test_pred_best = svm_best.predict(X_test) test_accuracy_best = accuracy_score(y_test, y_test_pred_best) print(f"优化后测试集准确率: {test_accuracy_best:.4f}") print("\n5.4 优化模型详细评估:") print(classification_report(y_test, y_test_pred_best, target_names=[f'Class {i}' for i in range(3)])) cm = confusion_matrix(y_test, y_test_pred_best) plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=[f'Class {i}' for i in range(3)], yticklabels=[f'Class {i}' for i in range(3)]) plt.title('SVM混淆矩阵') plt.ylabel('真实标签') plt.xlabel('预测标签') plt.tight_layout() plt.savefig('svm_confusion_matrix.png', dpi=300) return svm_best, test_accuracy_best
def train_random_forest(X_train, y_train, X_test, y_test): """训练随机森林模型""" print("\n" + "=" * 50) print("6. 随机森林模型训练与评估") print("=" * 50) print("\n6.1 基础随机森林模型:") rf_basic = RandomForestClassifier(n_estimators=100, random_state=42) rf_basic.fit(X_train, y_train) y_train_pred = rf_basic.predict(X_train) y_test_pred = rf_basic.predict(X_test) train_accuracy = accuracy_score(y_train, y_train_pred) test_accuracy = accuracy_score(y_test, y_test_pred) print(f"训练集准确率: {train_accuracy:.4f}") print(f"测试集准确率: {test_accuracy:.4f}") print("\n6.2 交叉验证 (5折):") cv_scores = cross_val_score(rf_basic, X_train, y_train, cv=5, scoring='accuracy') print(f"交叉验证准确率: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})") feature_importance = pd.DataFrame({ 'feature': [f'Feature {i}' for i in range(X_train.shape[1])], 'importance': rf_basic.feature_importances_ }).sort_values('importance', ascending=False) print("\n6.3 特征重要性 (前10):") print(feature_importance.head(10)) plt.figure(figsize=(10, 6)) plt.barh(feature_importance['feature'][:10][::-1], feature_importance['importance'][:10][::-1]) plt.xlabel('重要性') plt.title('随机森林特征重要性 (前10)') plt.tight_layout() plt.savefig('rf_feature_importance.png', dpi=300) print("\n6.4 网格搜索优化超参数...") param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 10, 20, 30], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } grid_search = GridSearchCV(RandomForestClassifier(random_state=42), param_grid, cv=5, scoring='accuracy', n_jobs=-1) grid_search.fit(X_train, y_train) print(f"最佳参数: {grid_search.best_params_}") print(f"最佳交叉验证准确率: {grid_search.best_score_:.4f}") rf_best = grid_search.best_estimator_ y_test_pred_best = rf_best.predict(X_test) test_accuracy_best = accuracy_score(y_test, y_test_pred_best) print(f"优化后测试集准确率: {test_accuracy_best:.4f}") print("\n6.5 优化模型详细评估:") print(classification_report(y_test, y_test_pred_best, target_names=[f'Class {i}' for i in range(3)])) cm = confusion_matrix(y_test, y_test_pred_best) plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Greens', xticklabels=[f'Class {i}' for i in range(3)], yticklabels=[f'Class {i}' for i in range(3)]) plt.title('随机森林混淆矩阵') plt.ylabel('真实标签') plt.xlabel('预测标签') plt.tight_layout() plt.savefig('rf_confusion_matrix.png', dpi=300) return rf_best, test_accuracy_best
def compare_models(svm_accuracy, rf_accuracy, svm_model, rf_model, X_test, y_test): """模型比较""" print("\n" + "=" * 50) print("7. 模型比较与总结") print("=" * 50) comparison = pd.DataFrame({ '模型': ['SVM', '随机森林'], '测试集准确率': [svm_accuracy, rf_accuracy] }) print("\n模型性能比较:") print(comparison) plt.figure(figsize=(8, 5)) bars = plt.bar(comparison['模型'], comparison['测试集准确率'], color=['skyblue', 'lightgreen']) plt.xlabel('模型') plt.ylabel('准确率') plt.title('SVM vs 随机森林 性能比较') plt.ylim([0, 1.0]) for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height + 0.01, f'{height:.4f}', ha='center', va='bottom') plt.tight_layout() plt.savefig('model_comparison.png', dpi=300) if svm_accuracy > rf_accuracy: best_model_name = 'SVM' best_model = svm_model else: best_model_name = '随机森林' best_model = rf_model print(f"\n最佳模型: {best_model_name} (准确率: {max(svm_accuracy, rf_accuracy):.4f})") return best_model_name, best_model
def main(): """主函数""" print("开始红酒数据集分析任务") print("=" * 60) df, X, y, feature_names, target_names = load_data() df = data_exploration(df) df_clean = handle_outliers(df, feature_names) print("\n" + "=" * 50) print("4. 数据集划分") print("=" * 50) X_clean = df_clean[feature_names] y_clean = df_clean['target'] X_train, X_test, y_train, y_test = train_test_split( X_clean, y_clean, test_size=0.2, random_state=42, stratify=y_clean ) print(f"训练集: {X_train.shape}, {y_train.shape}") print(f"测试集: {X_test.shape}, {y_test.shape}") X_train_scaled, X_test_scaled, scaler = feature_scaling(X_train, X_test) svm_model, svm_accuracy = train_svm(X_train_scaled, y_train, X_test_scaled, y_test) rf_model, rf_accuracy = train_random_forest(X_train_scaled, y_train, X_test_scaled, y_test) best_model_name, best_model = compare_models(svm_accuracy, rf_accuracy, svm_model, rf_model, X_test_scaled, y_test) import joblib joblib.dump(best_model, 'best_wine_model.pkl') joblib.dump(scaler, 'wine_scaler.pkl') print(f"\n最佳模型已保存为 'best_wine_model.pkl'") print(f"标准化器已保存为 'wine_scaler.pkl'") print("\n" + "=" * 60) print("任务完成!") print("=" * 60)
if __name__ == "__main__": main()
|