活动介绍

如何通过采取正则化的方式来提升泛化能力,在原代码基础上更改

时间: 2025-07-25 08:30:20 浏览: 9
<think>我们面对的是一个过拟合问题(训练集R²=0.9304,验证集R²=0.3448)。用户要求通过正则化方法改进模型,并修改原有代码。 由于没有提供具体模型代码,我将假设用户使用的是常见的回归模型(如线性回归、决策树集成等)。以下分模型类型讨论正则化方法: 1. 线性模型(如线性回归、逻辑回归): 正则化方法:L1正则化(Lasso)、L2正则化(Ridge)、弹性网络(ElasticNet) 在代码中,通常通过设置正则化超参数(alpha, l1_ratio)来实现。 2. 树集成模型(如随机森林、梯度提升树): 正则化方法:控制树复杂度(max_depth, min_samples_split等)、增加子采样比例(subsample)、正则化项(如XGBoost中的gamma, lambda, alpha)等。 3. 神经网络: 正则化方法:L2正则化(权重衰减)、Dropout、Early Stopping等。 由于用户没有指定模型类型,我将提供两种常见场景的示例代码:线性回归(带正则化)和XGBoost(带正则化)。 假设用户原有代码是线性回归(无正则化): 原始代码可能如下: from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) 改为使用正则化(以Ridge回归为例): from sklearn.linear_model import Ridge model = Ridge(alpha=1.0) # alpha是正则化强度 model.fit(X_train, y_train) 或者使用Lasso回归: from sklearn.linear_model import Lasso model = Lasso(alpha=0.01) model.fit(X_train, y_train) 或者使用弹性网络: from sklearn.linear_model import ElasticNet model = ElasticNet(alpha=1.0, l1_ratio=0.5) # l1_ratio控制L1和L2的混合比例 model.fit(X_train, y_train) 假设用户原有代码是XGBoost回归(无正则化): 原始代码可能如下: from xgboost import XGBRegressor model = XGBRegressor() model.fit(X_train, y_train) 改为使用正则化(通过设置超参数): model = XGBRegressor( max_depth=5, # 限制树深度,防止过拟合 min_child_weight=1, # 控制叶子节点的最小权重和,避免过小的叶子 gamma=0.1, # 节点分裂所需的最小损失减少量,越大正则化越强 reg_alpha=0.1, # L1正则化项系数 reg_lambda=1.0, # L2正则化项系数 subsample=0.8, # 样本采样比例 colsample_bytree=0.8, # 特征采样比例 n_estimators=100 ) model.fit(X_train, y_train) 注意:正则化参数需要根据验证集表现进行调整(如网格搜索)。 由于用户没有提供原有模型代码,我无法直接修改,因此给出两种常见模型的示例。用户可根据自己的模型类型选择相应的正则化方法。 另外,除了正则化,还可以考虑: - 特征选择:减少不相关特征 - 增加训练数据 - 交叉验证选择超参数 最后,建议用户使用交叉验证来调整正则化参数,以避免在验证集上过拟合。 生成相关问题: 1. 如何调整正则化参数以达到最佳效果? 2. 除了正则化,还有哪些方法可以防止过拟合? 3. 不同正则化方法(L1, L2, Dropout等)分别适用于哪些模型? 4. 如何评估正则化对模型泛化能力的影响? 5. 在特征选择中,L1正则化是如何帮助特征选择的?</think>### 如何在模型代码中添加正则化方法 根据您的模型性能指标(训练集R²=0.9304 vs 验证集R²=0.3448),过拟合问题非常明显。以下是针对不同模型类型的正则化实现方案,核心思路是通过修改损失函数或添加约束限制模型复杂度: --- #### 1. **线性模型(如线性回归/Ridge/Lasso)** ```python from sklearn.linear_model import Ridge, Lasso, ElasticNet # 原始代码(无正则化) # model = LinearRegression() # 添加L2正则化(Ridge回归) model = Ridge(alpha=0.5) # alpha控制正则化强度 # 添加L1正则化(Lasso回归) model = Lasso(alpha=0.01) # 会产生稀疏解,自动特征选择 # 弹性网络(L1+L2组合) model = ElasticNet(alpha=0.1, l1_ratio=0.5) # l1_ratio控制L1/L2混合比例 ``` **关键参数调优:** - `alpha`:正则化强度(建议范围 $10^{-4}$ 到 $10^2$) - `l1_ratio`:弹性网络中L1占比(0-1) --- #### 2. **树模型(如XGBoost/LightGBM)** ```python # XGBoost正则化 import xgboost as xgb params = { 'reg_alpha': 0.1, # L1正则化系数 'reg_lambda': 0.5, # L2正则化系数 'gamma': 0.1, # 分裂最小损失减少量 'max_depth': 5, # 限制树深度(重要!) 'min_child_weight': 3, 'subsample': 0.8 # 行采样比例 } model = xgb.XGBRegressor(**params) # LightGBM正则化 import lightgbm as lgb params = { 'lambda_l1': 0.1, 'lambda_l2': 0.2, 'min_data_in_leaf': 20, # 叶节点最小样本数 'feature_fraction': 0.7 # 特征采样比例 } model = lgb.LGBMRegressor(**params) ``` --- #### 3. **神经网络(Keras/TensorFlow)** ```python from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.regularizers import l1_l2 model = Sequential([ Dense(64, activation='relu', kernel_regularizer=l1_l2(l1=0.01, l2=0.01)), # 权重正则化 Dropout(0.5), # 随机丢弃50%神经元 Dense(1) ]) model.compile( optimizer='adam', loss='mse', metrics=['mae'] ) # 添加早停法(Early Stopping) from keras.callbacks import EarlyStopping early_stop = EarlyStopping( monitor='val_loss', patience=10, # 连续10次验证损失未改善则停止 restore_best_weights=True ) model.fit(X_train, y_train, validation_split=0.2, callbacks=[early_stop]) ``` --- ### 正则化参数调优策略 1. **网格搜索交叉验证**: ```python from sklearn.model_selection import GridSearchCV param_grid = { 'alpha': [0.001, 0.01, 0.1, 1, 10], 'l1_ratio': [0.2, 0.5, 0.8] # 仅弹性网络需要 } grid = GridSearchCV(ElasticNet(), param_grid, cv=5) grid.fit(X_train, y_train) ``` 2. **学习曲线诊断**: - 观察不同`alpha`值下训练/验证损失曲线 - 选择验证损失开始平稳的拐点值 3. **特征重要性分析**: ```python # 查看Lasso选择的特征 coef = model.coef_ important_features = np.where(coef != 0)[0] ``` --- ### 实施建议 1. **先尝试简单方案**:从Ridge/L2正则化开始(稳定性高) 2. **组合使用技术**: - 树模型:正则化 + 特征采样 + 深度限制 - 神经网络:权重正则化 + Dropout + 早停法 3. **监控验证集性能**: ```python history = model.fit(X_train, y_train, validation_data=(X_val, y_val)) plt.plot(history.history['val_loss']) # 关键监控曲线 ``` > 正则化通过约束模型复杂度,在损失函数中引入惩罚项(如权重范数),有效降低过拟合风险[^1][^3]。参数压缩还能提升模型解释性[^4][^5]。
阅读全文

相关推荐

这个代码结果有点过拟合,测试集得分太高帮我调整一下,其他部分不变,输出完整代码 导入必要的库 import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, cross_val_score from sklearn.ensemble import RandomForestRegressor from sklearn import metrics from sklearn.inspection import PartialDependenceDisplay import shap import seaborn as sns from statsmodels.nonparametric.smoothers_lowess import lowess from matplotlib import rcParams 设置字体与分辨率 plt.rcParams[‘font.sans-serif’] = [‘SimSun’] # 中文宋体 plt.rcParams[‘font.serif’] = [‘Times New Roman’] # 英文字体 plt.rcParams[‘axes.unicode_minus’] = False rcParams[‘figure.dpi’] = 300 设置统一字体大小 plt.rcParams[‘font.size’] = 12 # 默认字体 plt.rcParams[‘axes.labelsize’] = 14 # 坐标轴标签字体 plt.rcParams[‘xtick.labelsize’] = 12 # X轴刻度字体 plt.rcParams[‘ytick.labelsize’] = 12 # Y轴刻度字体 plt.rcParams[‘legend.fontsize’] = 12 # 图例字体 plt.rcParams[‘axes.titlesize’] = 16 # 标题字体 读取数据 data = pd.read_csv(“C:/Users/Administrator/Desktop/08104/LST_121714.csv”) y = data.iloc[:, 0] X = data.iloc[:, 1:] 将TEM作为目标变量y,其他列作为特征X y = data.iloc[:, 0] # 假设TEM在第一列 X = data.iloc[:, 1:] # 其他列为特征 划分训练集和测试集 x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) 1. 确定 n_estimators 参数范围 1.1 粗调树 scores = [] for i in range(1, 301, 10): rtf = RandomForestRegressor(n_estimators=i, n_jobs=-1, random_state=90) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() scores.append(score) best_n_estimators = (scores.index(max(scores)) * 10) + 1 print(f"最大得分: {max(scores):.4f}, 最佳 n_estimators = {best_n_estimators}") plt.figure(figsize=[20, 5]) plt.plot(range(1, 301, 10), scores) plt.xlabel(‘n_estimators’) plt.ylabel(‘CV Score’) plt.title(‘n_estimators 与交叉验证分数的关系’) plt.show() 1.2 精调树 scores = [] for i in range(95, 110): rtf = RandomForestRegressor(n_estimators=i, n_jobs=-1, random_state=90) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() scores.append(score) print(“最大得分: {}, max_n_estimators = {}”.format(max(scores), [*range(95, 110)][scores.index(max(scores))])) plt.figure(figsize=[20, 5]) plt.plot(range(95, 110), scores) plt.xlabel(‘n_estimators’) plt.ylabel(‘CV Score’) plt.title(‘细化 n_estimators 的范围’) plt.show() 2. 确定 max_depth 参数 ScoreAll = [] for i in range(1, 20, 1): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=i,n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_max_depth = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 max_depth = {best_max_depth} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel(‘max_depth’) plt.ylabel(‘CV Score’) plt.title(‘max_depth 与交叉验证分数的关系’) plt.show() 3. 确定 min_samples_split 参数 ScoreAll = [] for i in range(2, 9): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_split=i, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_min_samples_split = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 min_samples_split = {best_min_samples_split} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel(‘min_samples_split’) plt.ylabel(‘CV Score’) plt.title(‘min_samples_split 与交叉验证分数的关系’) plt.show() 4. 确定 min_samples_leaf 参数 ScoreAll = [] for i in range(1, 15): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=i, min_samples_split=2, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_min_samples_leaf = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 min_samples_leaf = {best_min_samples_leaf} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel(‘min_samples_leaf’) plt.ylabel(‘CV Score’) plt.title(‘min_samples_leaf 与交叉验证分数的关系’) plt.show() 5. 确定 max_features 参数 ScoreAll = [] for i in range(1, X.shape[1]+1): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=1, min_samples_split=2, max_features=i, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_max_features = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 max_features = {best_max_features} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel(‘max_features’) plt.ylabel(‘CV Score’) plt.title(‘max_features 与交叉验证分数的关系’) plt.show() 使用最佳参数重新训练模型 random = RandomForestRegressor( n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=1, min_samples_split=2, max_features=14, n_jobs=-1) random.fit(x_train, y_train) best_model = random 计算模型在训练集和测试集上的R²得分 train_score = random.score(x_train, y_train) test_score = random.score(x_test, y_test) print(f"训练集 R^2 得分: {train_score:.4f}“) print(f"测试集 R^2 得分: {test_score:.4f}”) 预测和评估模型 y_pred = random.predict(x_test) MSE = metrics.mean_squared_error(y_test, y_pred) RMSE = np.sqrt(MSE) print(f"(MSE, RMSE) = ({MSE:.4f}, {RMSE:.4f})") 可视化预测结果(测试集) plt.figure(figsize=(40, 6)) plt.plot(y_test.values, label=‘True Values’, color=‘blue’, marker=‘o’, linestyle=‘dashed’) plt.plot(y_pred, label=‘Predictions’, color=‘red’, marker=‘x’, linestyle=‘dashed’) plt.title(‘True vs Predicted LST’) plt.xlabel(‘Sample Index’) plt.ylabel(‘LST’) plt.legend() plt.grid(True) plt.show() 6. 模型解释(使用 SHAP,基于训练集) import shap import matplotlib.pyplot as plt plt.rcParams[‘font.sans-serif’] = [‘SimSun’] # 设置宋体 plt.rcParams[‘axes.unicode_minus’] = False plt.rcParams[‘figure.dpi’] = 300 # 设置图像分辨率 使用训练集进行解释 explainer = shap.TreeExplainer(best_model) shap_values = explainer.shap_values(x_train, check_additivity=False) 1. SHAP 总体重要性图(条形图) shap.summary_plot(shap_values, x_train, plot_type=“bar”, show=True) 2. SHAP 总体重要性图(散点图) shap.summary_plot(shap_values, x_train, show=True) 3. 单个样本的 SHAP 力图(以第一个训练样本为例) shap.force_plot(explainer.expected_value, shap_values[0], x_train.iloc[0], matplotlib=True) from sklearn.inspection import PartialDependenceDisplay import matplotlib.pyplot as plt 设置画布和坐标轴 fig, ax = plt.subplots(figsize=(8, 6), dpi=300) 绘制 PDP 图,曲线加粗 display = PartialDependenceDisplay.from_estimator( estimator=best_model, X=x_train, features=[‘NDVI’], ax=ax, line_kw={‘linewidth’: 2} ) 设置坐标轴中文标签 ax.set_xlabel(“NDVI”, fontsize=14) ax.set_ylabel(“预测值”, fontsize=14) 加粗坐标轴边框线 for spine in ax.spines.values(): spine.set_linewidth(1.8) # 可根据需要调整粗细 其他设置 plt.grid(True) plt.tight_layout() plt.show() import shap import matplotlib.pyplot as plt from sklearn.inspection import PartialDependenceDisplay 计算 SHAP 值(使用训练集) explainer = shap.TreeExplainer(best_model) shap_values = explainer.shap_values(x_train) 获取特征重要性平均绝对值并排序 shap_importance = np.abs(shap_values).mean(axis=0) top_10_indices = np.argsort(shap_importance)[-10:][::-1] # 从高到低 top_10_features = x_train.columns[top_10_indices] 遍历绘制 PDP 图 for feature in top_10_features: fig, ax = plt.subplots(figsize=(8, 6), dpi=300)

你举得这个代码还能叠加优化算法优化吗? % 使用RNN进行燃料电池性能预测 % 首先导入数据 try data = readtable('average_FC1_Motive_part_sampled.xlsx'); catch ME error('无法读取数据文件: %s', ME.message); end time = data{2:end, 1}; % 第一列为时间 outputs = data{2:end, 2:3}; % 第2、3列为输出电压和功率 inputs = data{2:end, 4:end}; % 从第4列为输入特征 % 数据预处理 % 使用z-score标准化 inputs_mean = mean(inputs); inputs_std = std(inputs); inputs_norm = (inputs - inputs_mean) ./ (inputs_std + eps); % 添加eps防止除零 outputs_mean = mean(outputs); outputs_std = std(outputs); outputs_norm = (outputs - outputs_mean) ./ (outputs_std + eps); % 参数设置 lag = 20; % 滑动窗口步长(时间序列长度) pred_dim = 1; % 向后预测步数(单步预测) datasize = length(time); % 训练数据尺寸 % 确认输入特征维度 input_size = size(inputs, 2); % 实际输入特征维度 fprintf('输入特征维度: %d\n', input_size); % 创建滑动窗口数据 fprintf('创建滑动窗口数据...\n'); total_samples = datasize - lag - pred_dim + 1; X = cell(total_samples, 1); Y = zeros(total_samples, size(outputs, 2)); % 调整数据格式:将每个样本从 [lag, input_size] 转置为 [input_size, lag] for i = 1:total_samples input_seq = inputs_norm(i:i+lag-1, :).'; % 转置为 [input_size, lag] output_seq = outputs_norm(i+lag:i+lag+pred_dim-1, :); X{i} = input_seq; % 每个序列样本的维度应为 [input_size, lag] Y(i, :) = output_seq; % 输出为预测的电压和功率 end % 数据集分割(75%训练,25%测试) train_rate = 0.75; train_size = floor(train_rate * total_samples); test_size = total_samples - train_size; % 创建训练集和测试集 train_x = X(1:train_size); train_y = Y(1:train_size, :); test_x = X(train_size+1:total_samples); test_y = Y(train_size+1:total_samples, :); % 验证训练数据的维度 sample_dim = size(train_x{1}); fprintf('样本维度检查: 特征维度 = %d, 序列长度 = %d\n', sample_dim(1), sample_dim(2)); % 训练集和测试集的时间轴 train_time = time(lag+1:lag+train_size); test_time = time(lag+train_size+1:lag+total_samples); fprintf('数据集分割完成: 训练集=%d, 测试集=%d\n', train_size, test_size); % 构建RNN模型 fprintf('构建RNN模型...\n'); output_size = size(outputs, 2); num_hidden_units = 128; layers = [ sequenceInputLayer(input_size, 'Name', 'input') % LSTM层 lstmLayer(num_hidden_units, 'OutputMode', 'last', 'Name', 'lstm') % 全连接层 fullyConnectedLayer(output_size, 'Name', 'fc') regressionLayer('Name', 'regression') ]; % 设置训练选项 options = trainingOptions('adam', ... 'MiniBatchSize', 64, ... 'MaxEpochs', 100, ... 'InitialLearnRate', 0.001, ... 'Shuffle', 'every-epoch', ... 'Verbose', false, ... 'Plots', 'training-progress', ... 'GradientThreshold', 1, ... 'LearnRateSchedule', 'piecewise', ... 'LearnRateDropFactor', 0.5, ... 'LearnRateDropPeriod', 20); % 训练模型 fprintf('开始训练模型...\n'); net = trainNetwork(train_x, train_y, layers, options); % 模型预测 fprintf('模型预测中...\n'); train_y_hat = predict(net, train_x); test_y_hat = predict(net, test_x); % 反标准化预测结果 train_y_hat = train_y_hat .* repmat(outputs_std, size(train_y_hat, 1), 1) + repmat(outputs_mean, size(train_y_hat, 1), 1); test_y_hat = test_y_hat .* repmat(outputs_std, size(test_y_hat, 1), 1) + repmat(outputs_mean, size(test_y_hat, 1), 1); train_y = train_y .* repmat(outputs_std, size(train_y, 1), 1) + repmat(outputs_mean, size(train_y, 1), 1); test_y = test_y .* repmat(outputs_std, size(test_y, 1), 1) + repmat(outputs_mean, size(test_y, 1), 1); % 计算误差指标 fprintf('\n=== 性能评估结果 ===\n'); for j = 1:output_size if j == 1 output_name = '电压'; else output_name = '功率'; end % 计算训练集误差 actual = train_y(:, j); predicted = train_y_hat(:, j); % 计算误差指标 ape = abs((actual - predicted) ./ actual) * 100; % APE (%) mape = mean(ape); % MAPE (%) mpe = mean((actual - predicted)./actual) * 100; % MPE (%) fprintf('\n%s预测评估:\n', output_name); fprintf('MAPE = %.2f%%\n', mape); fprintf('MPE = %.2f%%\n', mpe); % 可视化预测结果 figure('Position', [100 0 800 600], 'Color', 'w'); plot(train_time, actual, 'k-', 'LineWidth', 1.5); hold on; plot(train_time, predicted, 'r-', 'LineWidth', 1.5); xlabel('时间'); ylabel(output_name); title([output_name '预测结果与实际值对比']); legend('实际值', '预测值'); grid on; % 保存误差数据 if j == 1 voltage_ape = ape; else power_ape = ape; end end % 保存所有预测结果到Excel fprintf('\n保存预测结果到Excel文件...\n'); % 创建表格(修正维度不匹配问题) voltage_actual = train_y(:, 1); voltage_predicted = train_y_hat(:, 1); power_actual = train_y(:, 2); power_predicted = train_y_hat(:, 2); % 关键修正:使用train_time(:)确保列向量维度一致 results_table = table(train_time(:), voltage_actual, voltage_predicted, power_actual, power_predicted, ... 'VariableNames', {'时间', '实际电压', '预测电压', '实际功率', '预测功率'}); writetable(results_table, 'FC_prediction_results.xlsx');

这个代码结果有点过拟合帮我调整一下 # 导入必要的库 import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, cross_val_score from sklearn.ensemble import RandomForestRegressor from sklearn import metrics from sklearn.inspection import PartialDependenceDisplay import shap import seaborn as sns from statsmodels.nonparametric.smoothers_lowess import lowess from matplotlib import rcParams # 设置字体与分辨率 plt.rcParams['font.sans-serif'] = ['SimSun'] # 中文宋体 plt.rcParams['font.serif'] = ['Times New Roman'] # 英文字体 plt.rcParams['axes.unicode_minus'] = False rcParams['figure.dpi'] = 300 # 设置统一字体大小 plt.rcParams['font.size'] = 12 # 默认字体 plt.rcParams['axes.labelsize'] = 14 # 坐标轴标签字体 plt.rcParams['xtick.labelsize'] = 12 # X轴刻度字体 plt.rcParams['ytick.labelsize'] = 12 # Y轴刻度字体 plt.rcParams['legend.fontsize'] = 12 # 图例字体 plt.rcParams['axes.titlesize'] = 16 # 标题字体 # 读取数据 data = pd.read_csv("C:/Users/Administrator/Desktop/08104/LST_121714.csv") y = data.iloc[:, 0] X = data.iloc[:, 1:] # 将TEM作为目标变量y,其他列作为特征X y = data.iloc[:, 0] # 假设TEM在第一列 X = data.iloc[:, 1:] # 其他列为特征 # 划分训练集和测试集 x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # 1. 确定 n_estimators 参数范围 # 1.1 粗调树 scores = [] for i in range(1, 301, 10): rtf = RandomForestRegressor(n_estimators=i, n_jobs=-1, random_state=90) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() scores.append(score) best_n_estimators = (scores.index(max(scores)) * 10) + 1 print(f"最大得分: {max(scores):.4f}, 最佳 n_estimators = {best_n_estimators}") plt.figure(figsize=[20, 5]) plt.plot(range(1, 301, 10), scores) plt.xlabel('n_estimators') plt.ylabel('CV Score') plt.title('n_estimators 与交叉验证分数的关系') plt.show() # 1.2 精调树 scores = [] for i in range(95, 110): rtf = RandomForestRegressor(n_estimators=i, n_jobs=-1, random_state=90) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() scores.append(score) print("最大得分: {}, max_n_estimators = {}".format(max(scores), [*range(95, 110)][scores.index(max(scores))])) plt.figure(figsize=[20, 5]) plt.plot(range(95, 110), scores) plt.xlabel('n_estimators') plt.ylabel('CV Score') plt.title('细化 n_estimators 的范围') plt.show() # 2. 确定 max_depth 参数 ScoreAll = [] for i in range(1, 20, 1): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=i,n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_max_depth = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 max_depth = {best_max_depth} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel('max_depth') plt.ylabel('CV Score') plt.title('max_depth 与交叉验证分数的关系') plt.show() # 3. 确定 min_samples_split 参数 ScoreAll = [] for i in range(2, 9): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_split=i, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_min_samples_split = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 min_samples_split = {best_min_samples_split} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel('min_samples_split') plt.ylabel('CV Score') plt.title('min_samples_split 与交叉验证分数的关系') plt.show() # 4. 确定 min_samples_leaf 参数 ScoreAll = [] for i in range(1, 15): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=i, min_samples_split=2, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_min_samples_leaf = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 min_samples_leaf = {best_min_samples_leaf} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel('min_samples_leaf') plt.ylabel('CV Score') plt.title('min_samples_leaf 与交叉验证分数的关系') plt.show() # 5. 确定 max_features 参数 ScoreAll = [] for i in range(1, X.shape[1]+1): rtf = RandomForestRegressor(n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=1, min_samples_split=2, max_features=i, n_jobs=-1) score = cross_val_score(rtf, x_train, y_train, cv=10).mean() ScoreAll.append([i, score]) ScoreAll = np.array(ScoreAll) best_max_features = int(ScoreAll[np.argmax(ScoreAll[:, 1]), 0]) print(f"最优参数 max_features = {best_max_features} 及最高得分: {np.max(ScoreAll[:, 1]):.4f}") plt.figure(figsize=[20, 5]) plt.plot(ScoreAll[:, 0], ScoreAll[:, 1]) plt.xlabel('max_features') plt.ylabel('CV Score') plt.title('max_features 与交叉验证分数的关系') plt.show() # 使用最佳参数重新训练模型 random = RandomForestRegressor( n_estimators=103, random_state=90, max_depth=9, min_samples_leaf=1, min_samples_split=2, max_features=14, n_jobs=-1) random.fit(x_train, y_train) best_model = random # 计算模型在训练集和测试集上的R²得分 train_score = random.score(x_train, y_train) test_score = random.score(x_test, y_test) print(f"训练集 R^2 得分: {train_score:.4f}") print(f"测试集 R^2 得分: {test_score:.4f}") # 预测和评估模型 y_pred = random.predict(x_test) MSE = metrics.mean_squared_error(y_test, y_pred) RMSE = np.sqrt(MSE) print(f"(MSE, RMSE) = ({MSE:.4f}, {RMSE:.4f})") # 可视化预测结果(测试集) plt.figure(figsize=(40, 6)) plt.plot(y_test.values, label='True Values', color='blue', marker='o', linestyle='dashed') plt.plot(y_pred, label='Predictions', color='red', marker='x', linestyle='dashed') plt.title('True vs Predicted LST') plt.xlabel('Sample Index') plt.ylabel('LST') plt.legend() plt.grid(True) plt.show() # 6. 模型解释(使用 SHAP,基于训练集) import shap import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimSun'] # 设置宋体 plt.rcParams['axes.unicode_minus'] = False plt.rcParams['figure.dpi'] = 300 # 设置图像分辨率 # 使用训练集进行解释 explainer = shap.TreeExplainer(best_model) shap_values = explainer.shap_values(x_train, check_additivity=False) # 1. SHAP 总体重要性图(条形图) shap.summary_plot(shap_values, x_train, plot_type="bar", show=True) # 2. SHAP 总体重要性图(散点图) shap.summary_plot(shap_values, x_train, show=True) # 3. 单个样本的 SHAP 力图(以第一个训练样本为例) shap.force_plot(explainer.expected_value, shap_values[0], x_train.iloc[0], matplotlib=True) from sklearn.inspection import PartialDependenceDisplay import matplotlib.pyplot as plt # 设置画布和坐标轴 fig, ax = plt.subplots(figsize=(8, 6), dpi=300) # 绘制 PDP 图,曲线加粗 display = PartialDependenceDisplay.from_estimator( estimator=best_model, X=x_train, features=['NDVI'], ax=ax, line_kw={'linewidth': 2} ) # 设置坐标轴中文标签 ax.set_xlabel("NDVI", fontsize=14) ax.set_ylabel("预测值", fontsize=14) # 加粗坐标轴边框线 for spine in ax.spines.values(): spine.set_linewidth(1.8) # 可根据需要调整粗细 # 其他设置 plt.grid(True) plt.tight_layout() plt.show() import shap import matplotlib.pyplot as plt from sklearn.inspection import PartialDependenceDisplay # 计算 SHAP 值(使用训练集) explainer = shap.TreeExplainer(best_model) shap_values = explainer.shap_values(x_train) # 获取特征重要性平均绝对值并排序 shap_importance = np.abs(shap_values).mean(axis=0) top_10_indices = np.argsort(shap_importance)[-10:][::-1] # 从高到低 top_10_features = x_train.columns[top_10_indices] # 遍历绘制 PDP 图 for feature in top_10_features: fig, ax = plt.subplots(figsize=(8, 6), dpi=300) # 绘制 PDP display = PartialDependenceDisplay.from_estimator( estimator=best_model, X=x_train, features=[feature], ax=ax, line_kw={'linewidth': 2.0} ) # 设置中文标签 ax.set_xlabel(feature, fontsize=14) ax.set_ylabel("预测值", fontsize=14) # 加粗四边框 for spine in ax.spines.values(): spine.set_linewidth(1.2) # 网格与布局 plt.grid(True) plt.tight_layout() plt.show()

大家在看

recommend-type

高频双调谐谐振放大电路设计3MHz+电压200倍放大.zip

高频双调谐谐振放大电路设计3MHz+电压200倍放大.zip
recommend-type

只输入固定-vc实现windows多显示器编程的方法

P0.0 只输入固定 P0.1 P0CON.1 P0.2 P0CON.2 PORT_SET.PORT_REFEN P0.3 P0CON.3 自动“偷”从C2的交易应用程序在. PORT_SET.PORT_CLKEN PORT_SET.PORT_CLKOUT[0] P0.4 P0CON.4 C2调试的LED驱动器的时钟输入,如果作为 未启用. P0.5 PORT_CTRL.PORT_LED[1:0] 输出港口被迫为.阅读 实际LED驱动器的状态(开/关) 用户应阅读 RBIT_DATA.GPIO_LED_DRIVE 14只脚 不能用于在开发系统中,由于C2交易扰 乱输出. 参考区间的时钟频率 对抗 控制控制 评论评论 NVM的编程电压 VPP = 6.5 V 矩阵,和ROFF工业* PORT_CTRL 2 GPIO 1 矩阵,和ROFF工业* PORT_CTRL 3 参考 clk_ref GPIO 矩阵 4 C2DAT 产量 CLK_OUT GPIO 5 C2CLK LED驱动器 1 2 工业* PORT_CTRL 1 2 3 1 2 6 产量 CLK_OUT GPIO 1 2 1 1 1 PORT_SET.PORT_CLKEN PORT_SET.PORT_CLKOUT[1] P0.6 P0CON.6 P0.7 P0CON.7 P1.0 P1CON.0 P1.1 P1CON.1 7 8 9 GPIO GPIO GPIO 14只脚 14只脚 14只脚 *注:工业注:工业 代表“独立报”设置. “ 矩阵矩阵 and Roff 模式控制模拟垫电路. 116 修订版修订版1.0
recommend-type

半导体Semi ALD Tungsten W and TiN for Advanced Contact Application

ALD Tungsten, W and TiN for Advanced Contact Application
recommend-type

声纹识别数据集 IDMT-ISA-ELECTRIC-ENGINE

包含发动机正常、高负荷、损坏三种状态.wav声音片段,每种状态包含几百个片段,每个片段时长3S,可用于声纹类型识别,包含数据集介绍文档。
recommend-type

StepInt3-Plugin-x64:StepInt3插件(x64)-x64dbg的插件

StepInt3插件(x64)-x64dbg的插件 有关此插件的x86版本,请访问 概述 一个插件来解决int3断点异常 特征 自动跳过int3断点异常 从插件菜单启用/禁用的选项 如何安装 如果当前正在运行x64dbg(x64dbg 64位),请停止并退出。 将StepInt3.dp64复制到x64dbg\x64\plugins文件夹中。 启动x64dbg 信息 由撰写 使用 RadASM项目(.rap)用于管理和编译插件。 RadASM IDE可以在下载 该插件的x64版本使用 要构建此x64版本,还需要。 x64dbg x64dbg github x64dbg开关

最新推荐

recommend-type

tensorflow使用L2 regularization正则化修正overfitting过拟合方式

L1正则化则倾向于产生稀疏权重,某些特征的权重会完全变为0,因此在特征选择上有一定优势,但可能导致模型的表达能力下降。 在TensorFlow中实现L2正则化,可以通过`tf.nn.l2_loss()`函数计算权重的平方和,然后将其...
recommend-type

第八章 变量选择与正则化 – 岭回归分析

- **岭回归**是在最小二乘法的基础上加入了一个正则化项,即`L2`范数乘以一个非负参数`alpha`(也称为`λ`或正则化系数)。在Python中,可以使用`sklearn.linear_model.Ridge`来实现,其中`alpha`的值可以手动设定...
recommend-type

kernel-4.19.90-52.29.v2207.ky10.x86-64.rpm

kernel-4.19.90-52.29.v2207.ky10.x86-64.rpm
recommend-type

2025年检验检测机构评审准则宣贯试题(附答案).pdf

2025年检验检测机构评审准则宣贯试题(附答案).pdf
recommend-type

STM32F4 SDIO应用示例代码

STM32F4 SDIO应用示例代码
recommend-type

多数据源管理与分表实践:MybatisPlus与ShardingJdbc整合

根据给定的文件信息,我们可以详细地解读其中涉及到的关键知识点,这些知识点包括Mybatis Plus的使用、ShardingJdbc的数据分片策略、Swagger的API文档生成能力,以及如何通过注解方式切换数据源。以下是详细的知识点分析: ### Mybatis Plus Mybatis Plus是一个Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,为简化开发、提高效率而生。Mybatis Plus提供了如CRUD、分页、多数据源等一些列增强功能,并且可以与Spring、Spring Boot无缝集成。 #### 使用Mybatis Plus的优势: 1. **简化CRUD操作**:Mybatis Plus自带通用的Mapper和Service,减少代码量,提高开发效率。 2. **支持多种数据库**:支持主流的数据库如MySQL、Oracle、SQL Server等。 3. **逻辑删除**:可以在数据库层面实现记录的软删除功能,无需手动在业务中进行判断。 4. **分页插件**:提供默认的分页功能,支持自定义SQL、Lambda表达式等。 5. **性能分析插件**:方便分析SQL性能问题。 6. **代码生成器**:可以一键生成实体类、Mapper、Service和Controller代码,进一步提高开发效率。 #### 关键点: - **代码生成器**:位于`com.example.demo.common.codegenerator`包下的`GeneratorConfig`类中,用户需要根据实际的数据库配置更改数据库账号密码。 ### ShardingJdbc ShardingJDBC是当当网开源的轻量级Java框架,它在JDBC的层次提供了数据分片的能力。通过ShardingJDBC,可以在应用层面进行分库分表、读写分离、分布式主键等操作。 #### 分库分表: - 通过ShardingJDBC可以配置分库分表的策略,例如按照某个字段的值来决定记录应该保存在哪个分库或分表中。 - **Sharding策略**:可以定义多种分片策略,如模运算、查找表、时间范围等。 #### 关键点: - **注解切换数据源**:文件中提到通过注解的方式切换数据源,这允许开发者在编写代码时通过简单注解即可控制数据访问的路由规则。 ### Swagger Swagger是一个规范且完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。Swagger文件可让机器读取以了解远程服务的功能,并且可以作为浏览器插件,以便用户与远程服务互动。 #### 使用Swagger的优势: 1. **API文档自动生成**:Swagger可以根据代码中的注释直接生成文档。 2. **动态接口测试**:可以动态地对API接口进行测试。 3. **交互式文档**:提供交互式的API文档,可以实时地在线测试API。 #### 关键点: - **动态文档**:项目中集成Swagger后,可以在开发过程中动态更新API文档,便于团队协作和文档维护。 ### 如何使用 1. **准备工作**:在解压之前,需要更改数据源的IP、账号和密码,并执行resources下的SQL脚本。 2. **数据源配置**:在实际使用中,需要根据实际情况更改GeneratorConfig类中的dataSourceConfig()的数据库账号密码。 3. **代码生成**:启动代码生成器,根据设定的模板和策略生成相应的代码,包含实体类、Mapper、Service和Controller等。 4. **分库分表配置**:配置ShardingJDBC的分库分表策略,包括分片键和分片算法等。 5. **API文档**:集成Swagger,自动生成API文档并提供动态测试功能。 ### 结语 通过本文件所描述的内容,我们可以了解到如何利用Mybatis Plus、ShardingJdbc、Swagger这三大工具配合实现复杂的数据库操作和维护,以及如何通过注解在不同数据源之间灵活切换。用户在使用时应严格按照文件中的指示进行操作,确保数据库连接信息的正确配置,并结合代码生成器快速搭建项目基础结构。同时,应充分理解ShardingJdbc的分库分表策略,以及Swagger的API文档管理功能,以优化开发流程和提高工作效率。如果以上内容使用得当,这将是一个能够有效提升项目开发和维护质量的强大工具集。
recommend-type

BLE广播机制深度解析:XN297_TO_BLE.zip中的创新实践与应用指南

# 摘要 本文全面分析了蓝牙低功耗(BLE)广播机制的理论与实践应用,特别关注了XN297_TO_BLE.zip的开发与优化。通过详细探讨BLE广播的工作原理、数据包结构、以及XN297_TO_BLE.zip的设计理念与架构,本文为开发者提供了深入了解和实践BLE技术的框架。文中不仅介绍了如何搭建开发环境和编程实践,还深入讨论了
recommend-type

我用的就是idea的内置maven呀

<think>好的,用户现在提到他们使用的是IDEA的内置Maven,但之前遇到了“mvn不是内部或外部命令”的问题。我需要仔细分析可能的场景和用户的需求。 首先,用户可能是在IDEA内部使用Maven时没有问题,但在外部命令行中使用mvn命令时遇到了问题。这说明用户可能混淆了IDEA内置Maven和系统环境变量配置的关系。内置的Maven只在IDEA内部有效,并不会自动配置系统的环境变量,因此当用户在命令行中直接运行mvn时,系统找不到该命令,导致报错。 接下来,我需要确定用户的具体使用场景。用户可能是在尝试通过命令行执行Maven命令,或者是在其他需要系统环境变量支持的地方使用mvn。
recommend-type

环保主题植树节PPT模板设计赏析

标题“清新淡雅绿色环保植树节ppt模板”和描述“茂密的一棵卡通树,散落的绿叶,藤蔓线条,清新淡雅,绿色环保,312植树节ppt模板”共同体现了该PPT模板的设计风格和主题。该模板旨在宣传和庆祝植树节,同时强调了环保的理念。以下是对标题和描述中所蕴含知识点的详细说明: 1. 植树节的概念 植树节,是为了提高人们对森林资源的认识、倡导植树造林而设定的节日。不同国家的植树节日期可能不同,而在中国,“312”植树节(每年的3月12日)被广泛认知和庆祝。这个节日起源于20世纪初,是纪念孙中山先生的逝世纪念日,并逐渐演变为全民植树造林的活动日。 2. 绿色环保理念 绿色环保是指在人类活动中,采取相应的措施减少对环境的破坏,保护地球的自然资源和生态系统。这包括节能减排、资源循环利用、减少废弃物产生、提高能源效率等方面。该PPT模板采用“清新淡雅”的视觉元素,通过卡通形象和自然元素来传递环保的理念,使人们对环保有更深的认同感。 3. 卡通风格设计 模板使用了卡通风格来呈现内容,卡通风格设计通常更加生动、活泼,易于吸引观众的注意力,尤其适合儿童及青少年教育和宣传场合。卡通化的树木和藤蔓线条,可以更好地将植树节这一主题与观众尤其是年轻一代进行连接。 4. 清新淡雅的设计风格 “清新淡雅”是一种设计理念,强调色彩的温和、简洁的布局和舒适的视觉体验。在设计中,它通常表现为使用柔和的色调、简单的图形和没有过多装饰的版面,以创造出一种宁静、舒适的感觉。这种风格的模板适合用于教育、公益宣传等场合,易于传达温暖、积极的信息。 5. PPT模板的应用 PPT(PowerPoint演示文稿)是微软公司开发的一款演示软件,广泛用于商业汇报、教育授课、会议演讲和各类展示活动。一个精心设计的PPT模板可以提高演示的专业性和观赏性,同时通过统一的风格和格式,帮助使用者节省准备演示的时间和精力。模板中预设的版式、字体和配色可以被用户根据自己的需求进行调整和补充内容。 结合以上知识点,可以得出这个植树节PPT模板的设计意图和使用价值。它不仅具有美化演示文稿的作用,而且通过其环保主题和设计风格,传达了植树造林、保护环境的重要性。模板的视觉元素如卡通树木和藤蔓线条等,使得环保理念的表达更为直观和亲民,适合在植树节等环保主题活动上使用。
recommend-type

BLE调试必备:XN297_TO_BLE.zip故障排除与性能监控手册

# 摘要 本文详细介绍了BLE技术的基础知识,并针对XN297_TO_BLE.zip这一软件包进行了深入分析。通过对安装、配置、故障排查、性能优化、高级功能实现及案例研究等方面的探讨,提供了全面的实施指导和最佳实践。文章首先概括了BLE技术的核心要点,随后重点阐述了XN297_TO_BLE.zip的安装、初始配置以及功能验证,特别是在连接故障诊断、数据同步问题解决、性能