fvalue最终将值2

类型转换与运算

例如,在表达2 + 3.14159,+操作符需要操作数具有相同的数据类型。在这种情况下,左操作数是一个整数,与右操作数是一个双。由于双中较高的层次,int被转换为双。因此,该表达式被评估为2±3.14159,其值为5.14159。

一个好的问题是,“为什么是整数树的底部?对于char和短?“。char和短总是含蓄地晋升为整数(或无符号整数)在评价。这就是所谓的扩大。

这个层次可以导致了一些有趣的问题。例如,您可能希望表达对5U - 10 - 5(5U意味着5为无符号整数)。但在这种情况下,符号整数(10)提高到一个无符号整数,和这个表达式的结果是无符号整数4294967291!

许多混合转换按预期工作。例如,int值= 10×2.7的结果27。10是提升到一个浮动,10×2.7的值为27,和27被截断为整数(即编译器会抱怨)。

许多新的程序员尝试这样的事情:浮fvalue = 10 / 4;。然而,因为10和4都是整数,不提倡发生。整数除法是10 / 4的表现,导致2的价值,然后被隐式地转换为2分fvalue!

在你使用的文字值的情况下(如10,或4),更换一个或两个整数的值与一个浮点字面量的值(10或4)将导致两个操作数被转换为浮点值,和师将完成使用浮点运算。

但是如果你使用变量?考虑到这种情况下:

1
2
3
int nValue1 = 10;
int nValue2 = 4;
float fValue = nValue1 / nValue2;

fvalue最终将值2。我们如何告诉编译器,我们想使用浮点除法代替整数除法?答案是用铸铁。

铸造

铸造是一个请求由程序员来做一个显式的类型转换。在标准C++编程,强制转换是通过()操作符,同类型的名称将在。例如:


import pandas as pd import numpy as np import statsmodels.api as sm import statsmodels.formula.api as smf import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from sklearn.model_selection import KFold, cross_val_score, GridSearchCV from sklearn.metrics import r2_score, mean_squared_error from sklearn.preprocessing import StandardScaler, PolynomialFeatures from sklearn.linear_model import Ridge, Lasso, ElasticNet from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.svm import SVR from sklearn.feature_selection import SelectKBest, f_regression, mutual_info_regression import warnings warnings.filterwarnings('ignore') # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 读取处理后的数据 df = pd.read_excel('分层去重后数据.xlsx') # 一、增强的数据预处理 print("=" * 50) print("第一步:增强的数据预处理") print("=" * 50) # 检查数据基本信息 print(f"数据形状: {df.shape}") print(f"孕妇数量: {df['孕妇代码'].nunique()}") print(f"各孕周阶段记录数量:") print(df['孕周阶段'].value_counts()) # 1. 更严格的异常检测与处理 def enhanced_outlier_detection(data, column, method='iqr', threshold=2.0): """ 增强版异常检测 method: 'iqr'或'zscore' threshold: 对于iqr是倍数,对于zscore是标准差数 """ if method == 'iqr': Q1 = data[column].quantile(0.25) Q3 = data[column].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - threshold * IQR upper_bound = Q3 + threshold * IQR return data[(data[column] >= lower_bound) & (data[column] <= upper_bound)] else: # zscore z_scores = np.abs(stats.zscore(data[column])) return data[z_scores < threshold] # 对关键变量应用更严格的异常处理 df_clean = df.copy() for col in ['Y染色体浓度', '孕妇BMI', '检测孕周']: df_clean = enhanced_outlier_detection(df_clean, col, method='iqr', threshold=1.8) print(f"异常处理后数据记录数: {len(df_clean)}") # 2. 多种数据转换尝试 def try_transformations(data, column): """尝试多种数据转换方法""" transformations = { '原始': data[column], '对数': np.log1p(data[column]), '平方根': np.sqrt(data[column]), 'Box-Cox': stats.boxcox(data[column] + 1)[0] if min(data[column]) > 0 else data[column] } # 计算每种转换的偏度和峰度 results = {} for name, transformed in transformations.items(): skewness = stats.skew(transformed.dropna()) kurtosis = stats.kurtosis(transformed.dropna()) results[name] = {'偏度': skewness, '峰度': kurtosis} return pd.DataFrame(results) # 对Y染色体浓度尝试多种转换 transformation_results = try_transformations(df_clean, 'Y染色体浓度') print("Y染色体浓度不同转换方法的偏度和峰度:") print(transformation_results) # 选择最佳转换(偏度最接近0的) best_transform = transformation_results.T['偏度'].abs().idxmin() print(f"选择的最佳转换方法: {best_transform}") if best_transform == '对数': df_clean['Y染色体浓度_transformed'] = np.log1p(df_clean['Y染色体浓度']) elif best_transform == '平方根': df_clean['Y染色体浓度_transformed'] = np.sqrt(df_clean['Y染色体浓度']) elif best_transform == 'Box-Cox': df_clean['Y染色体浓度_transformed'] = stats.boxcox(df_clean['Y染色体浓度'] + 1)[0] else: df_clean['Y染色体浓度_transformed'] = df_clean['Y染色体浓度'] # 可视化转换效果 plt.figure(figsize=(10, 5)) plt.subplot(1, 2, 1) sns.histplot(df_clean['Y染色体浓度'], kde=True) plt.title('Y染色体浓度原始分布') plt.subplot(1, 2, 2) sns.histplot(df_clean['Y染色体浓度_transformed'], kde=True) plt.title(f'Y染色体浓度{best_transform}转换后分布') plt.tight_layout() plt.show() # 对孕周进行中心化处理 mean_gestational_week = df_clean['检测孕周'].mean() df_clean['检测孕周_centered'] = df_clean['检测孕周'] - mean_gestational_week print(f"孕周均: {mean_gestational_week:.2f}") # 二、增强的特征工程 print("=" * 50) print("第二步:增强的特征工程") print("=" * 50) # 创建更多有意义的特征 def create_advanced_features(data): """创建高级特征""" df_enhanced = data.copy() # BMI分类 df_enhanced['BMI类别'] = pd.cut(df_enhanced['孕妇BMI'], bins=[0, 18.5, 25, 30, 100], labels=['偏瘦', '正常', '超重', '肥胖']) # 孕周阶段细化 df_enhanced['孕周阶段细化'] = pd.cut(df_enhanced['检测孕周'], bins=[0, 12, 16, 20, 24, 30], labels=['早孕早期', '早孕晚期', '中孕早期', '中孕晚期', '晚孕期']) # 年龄分组 df_enhanced['年龄分组'] = pd.cut(df_enhanced['年龄'], bins=[0, 25, 30, 35, 40, 100], labels=['25以下', '25-30', '30-35', '35-40', '40以上']) # 创建多项式特征 df_enhanced['孕周平方'] = df_enhanced['检测孕周'] ** 2 df_enhanced['BMI立方'] = df_enhanced['孕妇BMI'] ** 3 # 创建更多交互项 df_enhanced['年龄_BMI交互'] = df_enhanced['年龄'] * df_enhanced['孕妇BMI'] df_enhanced['年龄_孕周交互'] = df_enhanced['年龄'] * df_enhanced['检测孕周'] df_enhanced['BMI_孕周交互'] = df_enhanced['孕妇BMI'] * df_enhanced['检测孕周_centered'] return df_enhanced df_enhanced = create_advanced_features(df_clean) # 三、特征选择优化 print("=" * 50) print("第三步:特征选择优化") print("=" * 50) # 准备特征数据 X_all = df_enhanced.select_dtypes(include=[np.number]).dropna() X_all = X_all.drop(['Y染色体浓度', 'Y染色体浓度_transformed'], axis=1, errors='ignore') y = df_enhanced['Y染色体浓度_transformed'] print(f"可用特征数量: {X_all.shape[1]}") # 使用多种方法进行特征选择 def advanced_feature_selection(X, y, k=10): """使用多种方法进行特征选择""" # 方差分析筛选 selector_anova = SelectKBest(score_func=f_regression, k='all') selector_anova.fit(X, y) anova_scores = pd.DataFrame({ '特征': X.columns, 'ANOVA得分': selector_anova.scores_ }).sort_values('ANOVA得分', ascending=False) # 互信息筛选 selector_mi = SelectKBest(score_func=mutual_info_regression, k='all') selector_mi.fit(X, y) mi_scores = pd.DataFrame({ '特征': X.columns, '互信息得分': selector_mi.scores_ }).sort_values('互信息得分', ascending=False) # 随机森林重要性 rf = RandomForestRegressor(n_estimators=100, random_state=42) rf.fit(X, y) rf_importance = pd.DataFrame({ '特征': X.columns, '随机森林重要性': rf.feature_importances_ }).sort_values('随机森林重要性', ascending=False) return anova_scores, mi_scores, rf_importance # 执行特征选择 anova_scores, mi_scores, rf_importance = advanced_feature_selection(X_all, y) print("ANOVA特征得分前10:") print(anova_scores.head(10)) print("\n互信息特征得分前10:") print(mi_scores.head(10)) print("\n随机森林特征重要性前10:") print(rf_importance.head(10)) # 选择最佳特征(取三种方法的前5名) top_features_anova = set(anova_scores.head(5)['特征']) top_features_mi = set(mi_scores.head(5)['特征']) top_features_rf = set(rf_importance.head(5)['特征']) # 取三种方法的并集 selected_features = list(top_features_anova.union(top_features_mi).union(top_features_rf)) print(f"\n最终选择的特征: {selected_features}") X_selected = X_all[selected_features] # 四、模型优化与选择 print("=" * 50) print("第四步:模型优化与选择") print("=" * 50) # 尝试多种回归模型 def compare_models(X, y, cv=5): """比较多种回归模型""" models = { '线性回归': sm.OLS(y, sm.add_constant(X)).fit(), '岭回归': Ridge(alpha=1.0), 'Lasso回归': Lasso(alpha=0.1), '梯度提升': GradientBoostingRegressor(n_estimators=100, random_state=42), '随机森林': RandomForestRegressor(n_estimators=100, random_state=42) } results = {} for name, model in models.items(): if name == '线性回归': # 对于statsmodels模型,直接使用R&sup2; results[name] = { 'R&sup2;': model.rsquared, '调整R&sup2;': model.rsquared_adj, 'AIC': model.aic, 'BIC': model.bic } else: # 对于sklearn模型,使用交叉验证 cv_scores = cross_val_score(model, X, y, cv=cv, scoring='r2') results[name] = { 'R&sup2;': cv_scores.mean(), 'R&sup2;标准差': cv_scores.std(), 'AIC': None, 'BIC': None } return pd.DataFrame(results).T # 比较不同模型 model_comparison = compare_models(X_selected, y) print("不同模型性能比较:") print(model_comparison.sort_values('R&sup2;', ascending=False)) # 选择最佳模型 best_model_name = model_comparison['R&sup2;'].idxmax() print(f"\n选择的最佳模型: {best_model_name}") # 优化最佳模型的超参数 def optimize_hyperparameters(X, y, model_type='gradient_boosting'): """优化模型的超参数""" if model_type == 'gradient_boosting': param_grid = { 'n_estimators': [50, 100, 200], 'learning_rate': [0.01, 0.05, 0.1], 'max_depth': [3, 4, 5], 'min_samples_split': [2, 5, 10] } model = GradientBoostingRegressor(random_state=42) elif model_type == 'random_forest': param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 5, 10], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } model = RandomForestRegressor(random_state=42) else: # 线性模型不需要超参数优化 return None grid_search = GridSearchCV( model, param_grid, cv=5, scoring='r2', n_jobs=-1, verbose=0 ) grid_search.fit(X, y) print(f"最佳参数: {grid_search.best_params_}") print(f"最佳分数: {grid_search.best_score_:.4f}") return grid_search.best_estimator_ # 根据选择的模型类型进行优化 if best_model_name in ['梯度提升', '随机森林']: model_type = 'gradient_boosting' if best_model_name == '梯度提升' else 'random_forest' best_model = optimize_hyperparameters(X_selected, y, model_type) else: # 对于线性模型,直接使用statsmodels的结果 best_model = sm.OLS(y, sm.add_constant(X_selected)).fit() # 五、模型评估与验证 print("=" * 50) print("第五步:模型评估与验证") print("=" * 50) # 分层交叉验证 patient_ids = df_enhanced['孕妇代码'].unique() kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_results = [] for fold, (train_idx, test_idx) in enumerate(kf.split(patient_ids)): train_patients = patient_ids[train_idx] test_patients = patient_ids[test_idx] train_data = df_enhanced[df_enhanced['孕妇代码'].isin(train_patients)] test_data = df_enhanced[df_enhanced['孕妇代码'].isin(test_patients)] X_train = train_data[selected_features] X_test = test_data[selected_features] y_train = train_data['Y染色体浓度_transformed'] y_test = test_data['Y染色体浓度_transformed'] # 训练模型 if hasattr(best_model, 'fit'): # sklearn模型 best_model.fit(X_train, y_train) y_pred = best_model.predict(X_test) else: # statsmodels模型 model = sm.OLS(y_train, sm.add_constant(X_train)).fit() y_pred = model.predict(sm.add_constant(X_test)) # 计算指标 r2 = r2_score(y_test, y_pred) rmse = np.sqrt(mean_squared_error(y_test, y_pred)) cv_results.append({'fold': fold + 1, 'R&sup2;': r2, 'RMSE': rmse}) print(f"Fold {fold + 1}: R&sup2; = {r2:.4f}, RMSE = {rmse:.4f}") cv_df = pd.DataFrame(cv_results) print(f"\n交叉验证平均结果: R&sup2; = {cv_df['R&sup2;'].mean():.4f} (±{cv_df['R&sup2;'].std():.4f}), " f"RMSE = {cv_df['RMSE'].mean():.4f} (±{cv_df['RMSE'].std():.4f})") # 六、最终模型训练与结果分析 print("=" * 50) print("第六步:最终模型训练与结果分析") print("=" * 50) # 使用全部数据训练最终模型 if hasattr(best_model, 'fit'): # sklearn模型 best_model.fit(X_selected, y) y_pred = best_model.predict(X_selected) final_r2 = r2_score(y, y_pred) # 获取特征重要性(如果可用) if hasattr(best_model, 'feature_importances_'): feature_importance = pd.DataFrame({ '特征': X_selected.columns, '重要性': best_model.feature_importances_ }).sort_values('重要性', ascending=False) print("\n特征重要性排序:") print(feature_importance) else: # statsmodels模型 final_model = best_model y_pred = final_model.predict(sm.add_constant(X_selected)) final_r2 = final_model.rsquared print("\n最终模型摘要:") print(final_model.summary()) # 模型显著性检验 print(f"F统计量: {final_model.fvalue:.4f}, p: {final_model.f_pvalue:.6f}") if final_model.f_pvalue < 0.05: print("✅ 整体模型显著 (p < 0.05)") else: print("❌ 整体模型不显著 (p ≥ 0.05)") print(f"\n最终模型R&sup2;: {final_r2:.4f}") # 可视化最终结果 plt.figure(figsize=(15, 10)) # 1. 模型预测与实际对比 plt.subplot(2, 3, 1) plt.scatter(y, y_pred) plt.plot([y.min(), y.max()], [y.min(), y.max()], 'r--') plt.xlabel('实际') plt.ylabel('预测') plt.title('预测与实际对比') # 2. 残差图 plt.subplot(2, 3, 2) residuals = y - y_pred plt.scatter(y_pred, residuals) plt.axhline(y=0, color='r', linestyle='--') plt.xlabel('预测') plt.ylabel('残差') plt.title('残差图') # 3. 残差分布 plt.subplot(2, 3, 3) sns.histplot(residuals, kde=True) plt.xlabel('残差') plt.title('残差分布') # 4. 特征重要性(如果可用) if 'feature_importance' in locals(): plt.subplot(2, 3, 4) plt.barh(range(len(feature_importance)), feature_importance['重要性']) plt.yticks(range(len(feature_importance)), feature_importance['特征']) plt.xlabel('特征重要性') plt.title('特征重要性排序') # 5. 交叉验证结果 plt.subplot(2, 3, 5) plt.bar(range(len(cv_df)), cv_df['R&sup2;']) plt.axhline(y=cv_df['R&sup2;'].mean(), color='r', linestyle='--', label='平均R&sup2;') plt.xlabel('交叉验证折数') plt.ylabel('R&sup2;') plt.title('交叉验证结果') plt.legend() plt.tight_layout() plt.show() # 保存最终结果 results_df = pd.DataFrame({ '实际': y, '预测': y_pred, '残差': residuals }) results_df.to_excel('模型预测结果.xlsx', index=False) print("预测结果已保存到 '模型预测结果.xlsx'") # 模型解释 print("\n模型解释:") if hasattr(best_model, 'feature_importances_') and 'feature_importance' in locals(): top_feature = feature_importance.iloc[0] print(f"- 最重要的特征是 '{top_feature['特征']}',重要性为 {top_feature['重要性']:.4f}") elif hasattr(final_model, 'params'): # 对于线性模型,解释系数 for feature, coef in final_model.params.items(): if feature != 'const': direction = "正" if coef > 0 else "负" print(f"- 特征 '{feature}' 对Y染色体浓度有{direction}向影响 (系数: {coef:.4f})") print(f"\n模型性能总结:") print(f"- 最终R&sup2;: {final_r2:.4f}") print(f"- 交叉验证平均R&sup2;: {cv_df['R&sup2;'].mean():.4f} (±{cv_df['R&sup2;'].std():.4f})") print(f"- 交叉验证平均RMSE: {cv_df['RMSE'].mean():.4f} (±{cv_df['RMSE'].std():.4f})") 这是我有错误的代码
最新发布
09-07
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm import scipy.stats as stats from sklearn.preprocessing import StandardScaler, PowerTransformer from sklearn.model_selection import train_test_split, cross_val_score from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet from sklearn.metrics import r2_score, mean_squared_error from sklearn.feature_selection import RFE, SelectKBest, f_regression from statsmodels.stats.outliers_influence import variance_inflation_factor from sklearn.pipeline import Pipeline from sklearn.compose import TransformedTargetRegressor import warnings warnings.filterwarnings('ignore') # 设置图表风格 sns.set_style("whitegrid") plt.rcParams['font.size'] = 12 plt.rcParams['figure.figsize'] = (10, 6) # 1. 读取Excel数据 def load_data(file_path, sheet_name=0): """加载Excel数据""" df = pd.read_excel(file_path, sheet_name=sheet_name) print(f"数据形状: {df.shape}") print("\n前5行数据:") print(df.head()) print("\n数据基本信息:") print(df.info()) print("\n描述性统计:") print(df.describe()) return df # 2. 数据预处理和探索性分析 def preprocess_and_explore(df, target_col): """数据预处理和探索性分析""" # 创建副本以避免修改原始数据 df_clean = df.copy() # 检查缺失 print("缺失统计:") missing_data = df_clean.isnull().sum() print(missing_data[missing_data > 0]) # 处理缺失 - 根据情况选择适当方法 # 这里使用中位数填充数列,众数填充分类列 for col in df_clean.columns: if df_clean[col].isnull().sum() > 0: if df_clean[col].dtype in ['int64', 'float64']: df_clean[col].fillna(df_clean[col].median(), inplace=True) else: df_clean[col].fillna(df_clean[col].mode()[0], inplace=True) # 识别并处理异常 - 使用IQR方法 numerical_cols = df_clean.select_dtypes(include=[np.number]).columns for col in numerical_cols: 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 # 将异常替换为边界 df_clean[col] = np.where(df_clean[col] < lower_bound, lower_bound, df_clean[col]) df_clean[col] = np.where(df_clean[col] > upper_bound, upper_bound, df_clean[col]) # 分离特征和目标变量 X = df_clean.drop(columns=[target_col]) y = df_clean[target_col] # 识别分类变量并创建虚拟变量 categorical_cols = X.select_dtypes(include=['object']).columns if len(categorical_cols) > 0: print(f"\n分类变量: {list(categorical_cols)}") X = pd.get_dummies(X, columns=categorical_cols, drop_first=True) # 探索性数据分析 print("\n=== 探索性数据分析 ===") # 目标变量分布 plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) sns.histplot(y, kde=True) plt.title('目标变量分布') # 正态性检验 stat, p_value = stats.normaltest(y) plt.subplot(1, 2, 2) stats.probplot(y, dist="norm", plot=plt) plt.title(f'Q-Q图 (p-value: {p_value:.4f})') plt.tight_layout() plt.show() # 相关性热力图 correlation_matrix = pd.concat([X, y], axis=1).corr() plt.figure(figsize=(12, 10)) sns.heatmap(correlation_matrix, annot=True, cmap='RdBu_r', center=0, square=True, fmt='.2f', cbar_kws={"shrink": .8}) plt.title('变量相关性热力图') plt.tight_layout() plt.show() # 与目标变量相关性最高的特征 target_corr = correlation_matrix[target_col].drop(target_col).sort_values(ascending=False) print("\n与目标变量相关性最高的特征:") print(target_corr.head(10)) return X, y, df_clean # 3. 特征工程和选择 def feature_engineering_and_selection(X, y): """特征工程和选择""" # 计算方差膨胀因子(VIF)检测多重共线性 vif_data = pd.DataFrame() vif_data["Feature"] = X.columns vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])] print("\n方差膨胀因子(VIF):") print(vif_data.sort_values("VIF", ascending=False)) # 移除高VIF的特征(VIF > 10) high_vif_features = vif_data[vif_data["VIF"] > 10]["Feature"] if len(high_vif_features) > 0: print(f"\n移除高VIF特征: {list(high_vif_features)}") X = X.drop(columns=high_vif_features) # 使用递归特征消除(RFE)选择最重要的特征 estimator = LinearRegression() selector = RFE(estimator, n_features_to_select=min(10, X.shape[1]), step=1) selector = selector.fit(X, y) selected_features = X.columns[selector.support_] print(f"\nRFE选择的特征 ({len(selected_features)}个):") print(list(selected_features)) X_selected = X[selected_features] return X_selected, selector # 4. 模型构建和优化 def build_and_optimize_model(X, y): """构建和优化模型""" # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # 标准化特征 scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # 尝试不同的回归模型 models = { '线性回归': LinearRegression(), '岭回归': Ridge(alpha=1.0), 'Lasso回归': Lasso(alpha=0.1), '弹性网络': ElasticNet(alpha=0.1, l1_ratio=0.5) } results = {} for name, model in models.items(): # 使用交叉验证评估模型 cv_scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring='r2') # 在训练集上拟合模型 model.fit(X_train_scaled, y_train) # 在测试集上评估 y_pred = model.predict(X_test_scaled) test_r2 = r2_score(y_test, y_pred) test_rmse = np.sqrt(mean_squared_error(y_test, y_pred)) results[name] = { 'CV R2': cv_scores.mean(), 'CV R2标准差': cv_scores.std(), '测试集R2': test_r2, '测试集RMSE': test_rmse, '模型': model } # 显示模型比较结果 results_df = pd.DataFrame(results).T print("\n模型性能比较:") print(results_df[['CV R2', 'CV R2标准差', '测试集R2', '测试集RMSE']]) # 选择最佳模型 best_model_name = results_df['测试集R2'].idxmax() best_model = results[best_model_name]['模型'] print(f"\n最佳模型: {best_model_name}") return best_model, scaler, X_train, X_test, y_train, y_test, results_df # 5. 详细模型诊断 def detailed_model_diagnostics(X, y, model, scaler, feature_names): """详细模型诊断""" # 使用statsmodels进行详细分析 X_scaled = scaler.transform(X) X_with_const = sm.add_constant(X_scaled) sm_model = sm.OLS(y, X_with_const).fit() print(sm_model.summary()) # 创建诊断图表 fitted_values = sm_model.fittedvalues residuals = sm_model.resid fig, axes = plt.subplots(2, 2, figsize=(15, 12)) # 残差 vs 拟合 axes[0, 0].scatter(fitted_values, residuals, alpha=0.6) axes[0, 0].axhline(y=0, color='r', linestyle='--') axes[0, 0].set_xlabel('拟合') axes[0, 0].set_ylabel('残差') axes[0, 0].set_title('残差 vs 拟合') # Q-Q图 sm.qqplot(residuals, line='45', fit=True, ax=axes[0, 1]) axes[0, 1].set_title('残差Q-Q图') # 残差分布 axes[1, 0].hist(residuals, bins=30, edgecolor='black', alpha=0.7) axes[1, 0].set_xlabel('残差') axes[1, 0].set_ylabel('频率') axes[1, 0].set_title('残差分布') # 预测 vs 实际 axes[1, 1].scatter(y, fitted_values, alpha=0.6) max_val = max(y.max(), fitted_values.max()) min_val = min(y.min(), fitted_values.min()) axes[1, 1].plot([min_val, max_val], [min_val, max_val], 'r--') axes[1, 1].set_xlabel('实际') axes[1, 1].set_ylabel('预测') axes[1, 1].set_title('预测 vs 实际') plt.tight_layout() plt.show() # 特征重要性图 if hasattr(model, 'coef_'): coefficients = model.coef_ else: # 对于statsmodels模型 coefficients = sm_model.params[1:] # 排除截距项 feature_importance = pd.DataFrame({ 'Feature': feature_names, 'Coefficient': coefficients }) feature_importance = feature_importance.sort_values('Coefficient', key=abs, ascending=False) plt.figure(figsize=(10, 8)) colors = ['red' if x < 0 else 'blue' for x in feature_importance['Coefficient']] plt.barh(feature_importance['Feature'], feature_importance['Coefficient'], color=colors) plt.xlabel('系数大小') plt.title('特征重要性(系数大小)') plt.tight_layout() plt.show() return sm_model # 6. 模型解释和结果展示 def explain_model(sm_model, feature_names, X_original): """模型解释和结果展示""" # 创建解释性数据框 results_df = pd.DataFrame({ '特征': ['截距'] + list(feature_names), '系数': sm_model.params, '标准误': sm_model.bse, 't': sm_model.tvalues, 'P>|t|': sm_model.pvalues, '置信区间下限': sm_model.conf_int()[0], '置信区间上限': sm_model.conf_int()[1] }) print("模型系数和统计显著性:") print(results_df.round(4)) # 计算标准化系数(Beta系数) # 首先计算特征和目标的标准差 X_std = X_original.std() y_std = y.std() # 排除截距项 coefficients = sm_model.params[1:] beta_coefficients = coefficients * (X_std / y_std) beta_df = pd.DataFrame({ '特征': feature_names, '标准化系数(Beta)': beta_coefficients }).sort_values('标准化系数(Beta)', key=abs, ascending=False) print("\n标准化系数(Beta):") print(beta_df.round(4)) return results_df, beta_df # 主函数 def main(): """主函数""" # 1. 加载数据 file_path = 'your_data.xlsx' # 替换为你的Excel文件路径 target_col = 'Y' # 替换为你的目标变量列名 df = load_data(file_path) # 2. 数据预处理和探索性分析 X, y, df_clean = preprocess_and_explore(df, target_col) # 3. 特征工程和选择 X_selected, selector = feature_engineering_and_selection(X, y) # 4. 模型构建和优化 best_model, scaler, X_train, X_test, y_train, y_test, results_df = build_and_optimize_model(X_selected, y) # 5. 详细模型诊断 sm_model = detailed_model_diagnostics( X_selected, y, best_model, scaler, X_selected.columns ) # 6. 模型解释 results_df, beta_df = explain_model(sm_model, X_selected.columns, X_selected) # 7. 最终模型评估 print("\n=== 最终模型评估 ===") print(f"训练R&sup2;: {sm_model.rsquared:.4f}") print(f"调整后R&sup2;: {sm_model.rsquared_adj:.4f}") print(f"F统计量: {sm_model.fvalue:.2f} (p-value: {sm_model.f_pvalue:.4e})") print(f"AIC: {sm_model.aic:.2f}") print(f"BIC: {sm_model.bic:.2f}") # 8. 保存结果 # 将结果保存到Excel with pd.ExcelWriter('regression_analysis_results.xlsx') as writer: df_clean.to_excel(writer, sheet_name='清洗后数据', index=False) results_df.to_excel(writer, sheet_name='模型系数', index=False) beta_df.to_excel(writer, sheet_name='标准化系数', index=False) pd.DataFrame({'指标': ['R&sup2;', '调整R&sup2;', 'AIC', 'BIC'], '': [sm_model.rsquared, sm_model.rsquared_adj, sm_model.aic, sm_model.bic]}).to_excel( writer, sheet_name='模型指标', index=False) print("\n分析完成! 结果已保存到 'regression_analysis_results.xlsx'") if __name__ == "__main__": main() 解释该代码
09-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值