
1. 美赛数学建模速成指南从模型选择到代码实现数学建模竞赛是检验学生综合运用数学知识解决实际问题能力的重要舞台。作为一名参加过多次数学建模竞赛的老手我深知在有限时间内完成高质量的建模方案是多么具有挑战性。特别是在美国大学生数学建模竞赛MCM/ICM这样的国际赛事中如何在短时间内选择合适的模型并快速实现代码往往决定了最终成绩的高低。这篇文章将分享我在美赛备战和实战中总结出的模型选择方法和代码实现技巧。不同于教科书式的理论讲解这里提供的都是可以直接应用于竞赛实战的干货。我们将从实际问题出发探讨如何根据题目特点快速锁定合适的数学模型并给出可直接复用的Python和MATLAB代码示例。2. 模型选择方法论2.1 问题分类与模型匹配数学建模竞赛题目通常可以分为几大类优化问题、预测问题、评价问题和机理分析问题。每种类型对应着不同的模型选择策略优化类问题如资源分配、路径规划等线性规划LP整数规划IP非线性规划NLP动态规划DP遗传算法GA预测类问题如趋势预测、市场分析等时间序列分析ARIMA回归分析机器学习模型随机森林、SVM等神经网络LSTM等评价类问题如风险评估、方案选择等层次分析法AHP模糊综合评价TOPSIS法熵权法机理分析问题如物理过程模拟等微分方程模型偏微分方程模型元胞自动机多智能体系统提示在实际竞赛中很多问题都是复合型的需要组合多种模型来解决。不要被单一模型限制思路。2.2 模型选择的五个关键因素选择模型时我通常会考虑以下五个维度问题适配性模型是否能准确描述问题本质数据要求现有数据是否满足模型输入条件实现复杂度在有限时间内能否完成模型实现结果可解释性评委是否能理解模型的输出创新空间是否有改进和创新的余地举个例子在2021年美赛C题关于黄蜂种群控制中我们面临的是典型的生物种群动态问题。经过分析我们排除了简单的线性回归模型最终选择了改进的Lotka-Volterra模型因为它能更好地描述捕食者-猎物关系同时留有足够的创新空间。3. 常用模型代码实现3.1 优化模型实现示例线性规划Python-PuLP库from pulp import * # 创建问题实例 prob LpProblem(Simple_LP_Problem, LpMinimize) # 定义决策变量 x1 LpVariable(x1, 0, None) x2 LpVariable(x2, 0, None) # 定义目标函数 prob 3*x1 5*x2, Objective_Function # 添加约束条件 prob 2*x1 3*x2 12, Constraint_1 prob -x1 x2 3, Constraint_2 prob x1 4, Constraint_3 # 求解问题 prob.solve() # 输出结果 print(Status:, LpStatus[prob.status]) for v in prob.variables(): print(v.name, , v.varValue) print(Objective value , value(prob.objective))遗传算法MATLAB实现% 定义适应度函数 function y simple_fitness(x) y 100*(x(1)^2 - x(2))^2 (1 - x(1))^2; end % 设置遗传算法参数 options optimoptions(ga, PopulationSize, 50,... MaxGenerations, 100,... FunctionTolerance, 1e-6,... PlotFcn, gaplotbestf); % 定义变量边界 lb [-5 -5]; ub [5 5]; % 运行遗传算法 [x, fval] ga(simple_fitness, 2, [], [], [], [], lb, ub, [], options); % 显示结果 disp([最优解: x1 , num2str(x(1)), , x2 , num2str(x(2))]); disp([最优值: , num2str(fval)]);3.2 预测模型实现示例时间序列ARIMAPythonimport pandas as pd import numpy as np from statsmodels.tsa.arima.model import ARIMA import matplotlib.pyplot as plt # 生成示例数据 np.random.seed(42) data np.random.normal(loc0, scale1, size100) data np.cumsum(data) 100 # 随机游走过程 # 拟合ARIMA(1,1,1)模型 model ARIMA(data, order(1,1,1)) model_fit model.fit() # 预测未来10个时间点 forecast model_fit.forecast(steps10) # 绘制结果 plt.figure(figsize(10,6)) plt.plot(data, labelActual) plt.plot(range(len(data), len(data)10), forecast, labelForecast, colorred) plt.legend() plt.title(ARIMA Model Forecast) plt.show() # 输出模型摘要 print(model_fit.summary())LSTM神经网络Python-Kerasfrom keras.models import Sequential from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler import numpy as np # 生成示例数据 def create_dataset(data, look_back1): X, Y [], [] for i in range(len(data)-look_back-1): X.append(data[i:(ilook_back), 0]) Y.append(data[ilook_back, 0]) return np.array(X), np.array(Y) # 示例数据 data np.array([[i*0.1 np.random.normal(scale0.05)] for i in range(100)]) scaler MinMaxScaler(feature_range(0,1)) data scaler.fit_transform(data) # 准备训练数据 look_back 3 X, Y create_dataset(data, look_back) X np.reshape(X, (X.shape[0], X.shape[1], 1)) # 创建LSTM模型 model Sequential() model.add(LSTM(50, input_shape(look_back,1))) model.add(Dense(1)) model.compile(lossmean_squared_error, optimizeradam) # 训练模型 model.fit(X, Y, epochs100, batch_size1, verbose2) # 预测 train_predict model.predict(X) train_predict scaler.inverse_transform(train_predict) Y scaler.inverse_transform([Y])4. 模型实现中的常见问题与解决方案4.1 数据预处理陷阱问题1数据尺度不一致导致模型收敛困难不同特征量纲差异过大会导致某些模型如KNN、神经网络难以收敛。解决方案from sklearn.preprocessing import StandardScaler scaler StandardScaler() X_scaled scaler.fit_transform(X)问题2时间序列中的缺失值处理直接删除或简单填充可能导致信息失真。推荐方法# 线性插值 data[value] data[value].interpolate(methodlinear) # 或者使用前向填充 data[value] data[value].fillna(methodffill)4.2 模型调参技巧网格搜索与随机搜索对比from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from sklearn.ensemble import RandomForestRegressor # 网格搜索 param_grid { n_estimators: [50, 100, 200], max_depth: [None, 10, 20], min_samples_split: [2, 5, 10] } grid_search GridSearchCV( estimatorRandomForestRegressor(), param_gridparam_grid, cv5, n_jobs-1 ) grid_search.fit(X_train, y_train) # 随机搜索更适合参数空间大的情况 random_search RandomizedSearchCV( estimatorRandomForestRegressor(), param_distributionsparam_grid, n_iter20, cv5, n_jobs-1 ) random_search.fit(X_train, y_train)4.3 结果可视化技巧多模型结果对比图import matplotlib.pyplot as plt models [Model A, Model B, Model C] scores [0.85, 0.92, 0.88] plt.figure(figsize(8,5)) bars plt.bar(models, scores, color[#1f77b4, #ff7f0e, #2ca02c]) # 添加数值标签 for bar in bars: height bar.get_height() plt.text(bar.get_x() bar.get_width()/2., height, f{height:.2f}, hacenter, vabottom) plt.ylim(0.7, 1.0) plt.ylabel(Accuracy Score) plt.title(Model Performance Comparison) plt.grid(axisy, linestyle--, alpha0.7) plt.show()动态可视化适用于时间序列from matplotlib.animation import FuncAnimation fig, ax plt.subplots(figsize(10,6)) line, ax.plot([], [], lw2) ax.set_xlim(0, 100) ax.set_ylim(min(data)-1, max(data)1) ax.grid() def init(): line.set_data([], []) return line, def animate(i): x range(i1) y data[:i1] line.set_data(x, y) return line, ani FuncAnimation(fig, animate, frames100, init_funcinit, blitTrue) plt.show()5. 美赛实战经验分享5.1 三天时间管理策略第一天问题分析与模型设计上午仔细阅读题目确定问题类型和需求下午收集数据确定初步模型框架晚上完成模型理论部分开始简单实现第二天模型实现与初步结果上午完成主要代码实现下午获取初步结果开始调整参数晚上优化模型准备可视化素材第三天论文撰写与完善上午完成论文主体内容下午完善图表和结果分析晚上检查全文准备提交5.2 团队协作技巧版本控制使用Git管理代码和文档git init git add . git commit -m Initial model implementation分工明确一人负责建模一人负责编程一人负责论文定期同步每4小时简短会议同步进展5.3 论文写作要点摘要最后写但最重要。包含问题重述建模思路主要结果创新点假设明确且合理最好能验证灵敏度分析展示模型鲁棒性优缺点客观分析体现批判性思维6. 代码优化与性能提升6.1 向量化计算低效实现result [] for i in range(len(a)): result.append(a[i] * b[i])高效向量化实现import numpy as np a np.array(a) b np.array(b) result a * b # 向量化运算6.2 并行计算使用multiprocessingfrom multiprocessing import Pool def process_data(chunk): # 处理数据块 return processed_chunk if __name__ __main__: data [...] # 大数据集 chunk_size len(data) // 4 chunks [data[i:ichunk_size] for i in range(0, len(data), chunk_size)] with Pool(4) as p: results p.map(process_data, chunks) final_result np.concatenate(results)6.3 内存优化使用生成器处理大数据def data_generator(file_path, chunk_size1000): with open(file_path) as f: while True: chunk [] for _ in range(chunk_size): line f.readline() if not line: if chunk: yield chunk return chunk.append(float(line.strip())) yield chunk # 使用示例 for chunk in data_generator(large_data.txt): process(chunk)7. 模型验证与评估7.1 交叉验证实现时间序列交叉验证from sklearn.model_selection import TimeSeriesSplit tscv TimeSeriesSplit(n_splits5) for train_index, test_index in tscv.split(X): X_train, X_test X[train_index], X[test_index] y_train, y_test y[train_index], y[test_index] model.fit(X_train, y_train) score model.score(X_test, y_test) print(fFold score: {score:.4f})7.2 评估指标选择回归问题常用指标from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score mae mean_absolute_error(y_true, y_pred) mse mean_squared_error(y_true, y_pred) rmse np.sqrt(mse) r2 r2_score(y_true, y_pred) print(fMAE: {mae:.4f}) print(fRMSE: {rmse:.4f}) print(fR²: {r2:.4f})分类问题常用指标from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score accuracy accuracy_score(y_true, y_pred) precision precision_score(y_true, y_pred) recall recall_score(y_true, y_pred) f1 f1_score(y_true, y_pred) print(fAccuracy: {accuracy:.4f}) print(fPrecision: {precision:.4f}) print(fRecall: {recall:.4f}) print(fF1 Score: {f1:.4f})8. 高级建模技巧8.1 集成学习方法随机森林与XGBoost对比from sklearn.ensemble import RandomForestRegressor from xgboost import XGBRegressor from sklearn.model_selection import cross_val_score # 随机森林 rf RandomForestRegressor(n_estimators100, random_state42) rf_scores cross_val_score(rf, X, y, cv5, scoringr2) # XGBoost xgb XGBRegressor(n_estimators100, random_state42) xgb_scores cross_val_score(xgb, X, y, cv5, scoringr2) print(fRandom Forest R²: {rf_scores.mean():.4f} (±{rf_scores.std():.4f})) print(fXGBoost R²: {xgb_scores.mean():.4f} (±{xgb_scores.std():.4f}))8.2 贝叶斯优化使用Hyperopt进行超参数优化from hyperopt import fmin, tpe, hp, Trials def objective(params): model RandomForestRegressor( n_estimatorsint(params[n_estimators]), max_depthint(params[max_depth]), min_samples_splitint(params[min_samples_split]), random_state42 ) score cross_val_score(model, X_train, y_train, cv3, scoringr2).mean() return -score # 因为fmin是最小化目标函数 space { n_estimators: hp.quniform(n_estimators, 50, 300, 10), max_depth: hp.quniform(max_depth, 3, 15, 1), min_samples_split: hp.quniform(min_samples_split, 2, 20, 1) } trials Trials() best fmin(fnobjective, spacespace, algotpe.suggest, max_evals50, trialstrials) print(Best parameters:, best)9. 模型部署与报告生成9.1 模型持久化保存和加载模型import joblib # 保存模型 joblib.dump(model, model.pkl) # 加载模型 loaded_model joblib.load(model.pkl)9.2 自动化报告生成使用Jupyter Notebook转PDF# 在Jupyter Notebook中执行 !jupyter nbconvert --to pdf report.ipynb使用Python生成动态报告from jinja2 import Template import pdfkit # 报告模板 template Template( h1Model Report/h1 pstrongModel Type:/strong {{ model_type }}/p pstrongAccuracy:/strong {{ accuracy }}/p img src{{ plot_path }} width600 ) # 填充数据 html template.render( model_typeRandom Forest, accuracy0.92, plot_pathresults/plot.png ) # 生成PDF pdfkit.from_string(html, report.pdf)10. 实战案例分析10.1 2022年美赛C题解决方案问题描述分析加密货币市场趋势并制定交易策略我们的解决方案数据收集使用API获取历史交易数据import requests import pandas as pd url https://api.coingecko.com/api/v3/coins/bitcoin/market_chart params { vs_currency: usd, days: 365 } response requests.get(url, paramsparams) data response.json() prices pd.DataFrame(data[prices], columns[timestamp, price])特征工程构建技术指标# 计算移动平均 prices[MA_7] prices[price].rolling(window7).mean() prices[MA_30] prices[price].rolling(window30).mean() # 计算RSI delta prices[price].diff() gain (delta.where(delta 0, 0)).rolling(window14).mean() loss (-delta.where(delta 0, 0)).rolling(window14).mean() rs gain / loss prices[RSI] 100 - (100 / (1 rs))模型构建LSTM策略组合# LSTM预测 model Sequential() model.add(LSTM(50, return_sequencesTrue, input_shape(look_back, n_features))) model.add(LSTM(50)) model.add(Dense(1)) model.compile(optimizeradam, lossmse) # 交易策略 def trading_strategy(predictions, threshold0.02): signals [] for i in range(1, len(predictions)): if predictions[i] predictions[i-1] * (1 threshold): signals.append(BUY) elif predictions[i] predictions[i-1] * (1 - threshold): signals.append(SELL) else: signals.append(HOLD) return signals10.2 2021年美赛D题解决方案问题描述音乐影响分析关键创新点音频特征提取import librosa def extract_features(file_path): y, sr librosa.load(file_path) features { tempo: librosa.beat.tempo(yy, srsr)[0], chroma_stft: np.mean(librosa.feature.chroma_stft(yy, srsr)), rmse: np.mean(librosa.feature.rms(yy)), spectral_centroid: np.mean(librosa.feature.spectral_centroid(yy, srsr)), spectral_bandwidth: np.mean(librosa.feature.spectral_bandwidth(yy, srsr)), rolloff: np.mean(librosa.feature.spectral_rolloff(yy, srsr)), zero_crossing_rate: np.mean(librosa.feature.zero_crossing_rate(y)), harmony: np.mean(librosa.effects.harmonic(y)), percussive: np.mean(librosa.effects.percussive(y)) } return features音乐情感分析模型from sklearn.ensemble import GradientBoostingClassifier from sklearn.preprocessing import LabelEncoder # 假设我们有带标签的音乐数据集 features [] labels [] for file_path, emotion_label in dataset: features.append(extract_features(file_path)) labels.append(emotion_label) # 转换为DataFrame df pd.DataFrame(features) df[label] labels # 编码标签 le LabelEncoder() df[label] le.fit_transform(df[label]) # 训练模型 model GradientBoostingClassifier() model.fit(df.drop(label, axis1), df[label])可视化分析import seaborn as sns # 特征相关性分析 plt.figure(figsize(12,8)) sns.heatmap(df.corr(), annotTrue, cmapcoolwarm) plt.title(Feature Correlation Matrix) plt.show() # 情感分布 plt.figure(figsize(8,5)) sns.countplot(xlabel, datadf) plt.title(Emotion Label Distribution) plt.show()11. 模型组合与集成11.1 投票集成方法分类问题硬投票from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC # 定义基分类器 clf1 LogisticRegression(random_state42) clf2 DecisionTreeClassifier(random_state42) clf3 SVC(probabilityTrue, random_state42) # 创建投票分类器 voting_clf VotingClassifier( estimators[(lr, clf1), (dt, clf2), (svc, clf3)], votinghard ) voting_clf.fit(X_train, y_train) score voting_clf.score(X_test, y_test) print(fVoting Classifier Accuracy: {score:.4f})11.2 堆叠集成方法回归问题堆叠示例from sklearn.ensemble import StackingRegressor from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.svm import SVR # 定义基学习器 estimators [ (knn, KNeighborsRegressor()), (svr, SVR()) ] # 创建堆叠回归器 stacking_reg StackingRegressor( estimatorsestimators, final_estimatorLinearRegression(), cv5 ) stacking_reg.fit(X_train, y_train) score stacking_reg.score(X_test, y_test) print(fStacking Regressor R²: {score:.4f})12. 模型解释性技术12.1 SHAP值分析解释模型预测import shap # 创建解释器 explainer shap.Explainer(model) shap_values explainer(X_test) # 特征重要性图 shap.summary_plot(shap_values, X_test) # 单个预测解释 shap.plots.waterfall(shap_values[0])12.2 LIME局部解释from lime import lime_tabular # 创建解释器 explainer lime_tabular.LimeTabularExplainer( training_datanp.array(X_train), feature_namesX_train.columns, class_names[Negative, Positive], modeclassification ) # 解释单个实例 exp explainer.explain_instance( data_rowX_test.iloc[0], predict_fnmodel.predict_proba ) # 显示结果 exp.show_in_notebook()13. 非结构化数据处理13.1 文本特征提取TF-IDF向量化from sklearn.feature_extraction.text import TfidfVectorizer corpus [ This is the first document., This document is the second document., And this is the third one., Is this the first document? ] vectorizer TfidfVectorizer() X vectorizer.fit_transform(corpus) print(vectorizer.get_feature_names_out()) print(X.shape)13.2 图像特征提取使用预训练CNN提取特征from keras.applications.vgg16 import VGG16, preprocess_input from keras.preprocessing import image import numpy as np # 加载预训练模型不含顶层 model VGG16(weightsimagenet, include_topFalse) # 加载并预处理图像 img_path example.jpg img image.load_img(img_path, target_size(224, 224)) x image.img_to_array(img) x np.expand_dims(x, axis0) x preprocess_input(x) # 提取特征 features model.predict(x) print(features.shape)14. 实时数据处理14.1 流数据处理框架使用PySpark处理数据流from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * # 创建Spark会话 spark SparkSession.builder.appName(StreamProcessing).getOrCreate() # 定义schema schema StructType([ StructField(timestamp, TimestampType(), True), StructField(value, DoubleType(), True) ]) # 读取数据流 stream_df spark.readStream.schema(schema).csv(data/stream/) # 数据处理 processed_df stream_df.withWatermark(timestamp, 1 minute) \ .groupBy(window(timestamp, 5 minutes)) \ .agg(avg(value).alias(avg_value)) # 启动流查询 query processed_df.writeStream \ .outputMode(complete) \ .format(console) \ .start() query.awaitTermination()14.2 实时预测服务使用Flask构建APIfrom flask import Flask, request, jsonify import joblib import numpy as np app Flask(__name__) # 加载模型 model joblib.load(model.pkl) app.route(/predict, methods[POST]) def predict(): data request.get_json() features np.array(data[features]).reshape(1, -1) prediction model.predict(features) return jsonify({prediction: prediction.tolist()}) if __name__ __main__: app.run(host0.0.0.0, port5000)15. 模型监控与维护15.1 性能衰减检测滑动窗口评估import pandas as pd def monitor_model_performance(y_true, y_pred, window_size100): results [] for i in range(len(y_true) - window_size 1): y_true_window y_true[i:iwindow_size] y_pred_window y_pred[i:iwindow_size] accuracy np.mean(y_true_window y_pred_window) results.append(accuracy) plt.figure(figsize(10,5)) plt.plot(results) plt.axhline(np.mean(results), colorr, linestyle--) plt.title(Model Performance Over Time) plt.ylabel(Accuracy) plt.xlabel(Window) plt.show() return results15.2 数据漂移检测统计检验方法from scipy import stats def detect_data_drift(train_data, new_data, alpha0.05): drift_detected False report {} for col in train_data.columns: # 对于数值特征使用KS检验 if np.issubdtype(train_data[col].dtype, np.number): stat, p stats.ks_2samp(train_data[col], new_data[col]) report[col] { test: KS, statistic: stat, p_value: p, drift: p alpha } if p alpha: drift_detected True # 对于分类特征使用卡方检验 else: freq_train train_data[col].value_counts(normalizeTrue) freq_new new_data[col].value_counts(normalizeTrue) all_cats list(set(freq_train.index) | set(freq_new.index)) observed pd.concat([ freq_train.reindex(all_cats, fill_value0), freq_new.reindex(all_cats, fill_value0) ], axis1).values chi2, p, _, _ stats.chi2_contingency(observed) report[col] { test: Chi-square, statistic: chi2, p_value: p, drift: p alpha } if p alpha: drift_detected True return drift_detected, report16. 模型部署实战16.1 Docker容器化部署Dockerfile示例FROM python:3.8-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD [gunicorn, --bind, 0.0.0.0:5000, app:app]构建和运行docker build -t model-api . docker run -p 5000:5000 model-api16.2 模型服务化使用FastAPI构建高性能APIfrom fastapi import FastAPI from pydantic import BaseModel import joblib import numpy as np app FastAPI() class InputData(BaseModel): features: list[float] model joblib.load(model.pkl) app.post(/predict) async def predict(data: InputData): features np.array(data.features).reshape(1, -1) prediction model.predict(features) return {prediction: prediction.tolist()[0]} if __name__ __main__: import uvicorn uvicorn.run(app, host0.0.0.0, port8000)17. 持续学习与模型更新17.1 在线学习实现部分拟合更新模型from sklearn.linear_model import SGDClassifier # 初始化模型 model SGDClassifier(losslog_loss) # 初始训练 model.partial_fit(X_initial, y_initial, classesnp.unique(y)) # 增量更新 for X_batch, y_batch in data_stream: model.partial_fit(X_batch, y_batch) current_score model.score(X_test, y_test) print(fCurrent accuracy: {current_score:.4f})17.2 模型版本控制使用MLflow跟踪实验import mlflow import mlflow.sklearn with mlflow.start_run(): # 记录参数 mlflow.log_param(n_estimators, 100) mlflow.log_param(max_depth, 10) # 训练模型 model RandomForestClassifier(n_estimators100, max_depth10) model.fit(X_train, y_train) # 评估模型 accuracy model.score(X_test, y_test) mlflow.log_metric(accuracy, accuracy) # 保存模型 mlflow.sklearn.log_model(model, model) print(fModel accuracy: {accuracy:.4f}) print(fRun ID: {mlflow.active_run().info.run_uuid})18. 模型压缩与优化18.1 模型量化TensorFlow模型量化import tensorflow as tf # 训练原始模型 model create_model() model.fit(X_train, y_train, epochs10) # 量化模型 converter tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations [tf.lite.Optimize.DEFAULT] quantized_model converter.convert() # 保存量化模型 with open(quantized_model.tflite, wb) as f: f.write(quantized_model)18.2 模型剪枝使用TensorFlow Model Optimization Toolkitimport tensorflow_model_optimization as tfmot # 定义要剪枝的层 prune_low_magnitude tfmot.sparsity.keras.prune_low_magnitude # 剪枝参数 pruning_params { pruning_schedule: tfmot.sparsity.keras.PolynomialDecay( initial_sparsity0.50, final_sparsity0.90, begin_step0, end_step1000 ) } # 应用剪枝 model create_model() model_for_pruning prune_low_magnitude(model, **pruning_params) # 重新编译模型 model_for_pruning.compile(optimizeradam, losssparse_categorical_crossentropy, metrics[accuracy]) # 训练剪枝模型 model_for_pruning.fit(X_train, y_train, epochs10)19. 可解释AI技术19.1 特征重要性分析Permutation Importancefrom sklearn.inspection import permutation_importance result permutation_importance( model, X_test, y_test, n_repeats10, random_state42 ) sorted_idx result.importances_mean.argsort() plt.figure(figsize(10,6)) plt.boxplot(result.importances[sorted_idx].T, vertFalse, labelsX_test.columns[sorted_idx]) plt.title(Permutation Importance) plt.show()19.2 决策路径可视化决策树可视化from sklearn.tree import plot_tree plt.figure(figsize(20,10)) plot_tree(model, feature_namesX.columns, class_names[Negative, Positive], filledTrue