活动介绍
file-type

Matlab中Logit.zip的Logistic回归分析程序精确度研究

版权申诉
552B | 更新于2024-12-14 | 8 浏览量 | 5 评论 | 0 下载量 举报 收藏
download 限时特惠:#14.90
Logistic回归是一种广泛应用于分类问题的统计方法,特别适用于因变量为二分类的情况,如是/否、成功/失败等。通过Logit.m文件中的程序,用户可以在MATLAB环境中进行Logistic回归分析,并且可以获得模型的精确度评估。 在讲解Logistic回归之前,我们先了解一些基础概念。Logistic回归的核心在于一个称为Logit函数的数学函数,它是Sigmoid函数的逆函数,用于将数据映射到[0,1]区间内,从而适用于概率计算。Logistic回归模型通过使用Logit函数将线性回归模型的结果转换为概率,因此能处理分类任务。 在MATLAB中,Logistic回归的实现涉及以下步骤: 1. 数据准备:收集并处理数据,确保数据适合进行Logistic回归分析。 2. 模型建立:使用Logit函数定义模型结构,通常形式为logit(P) = ln[P/(1-P)] = β0 + β1x1 + β2x2 + ... + βnxn,其中P是事件发生的概率,β0是截距项,β1至βn是自变量x1至xn的系数。 3. 参数估计:利用极大似然估计(MLE)等方法求解回归系数β0至βn。 4. 模型检验:对模型进行检验,判断模型的拟合优度和预测能力。 5. 预测和评估:使用模型对新数据进行概率预测,并评估模型的精确度。 在Logit.m文件中,上述过程被封装成MATLAB代码,用户可以通过简单地调用Logit函数并传入相应的参数(例如自变量和因变量的数据矩阵)来实现Logistic回归分析。完成分析后,可以得到模型参数、预测概率以及模型的精确度等信息。 精确度是评估分类模型性能的重要指标之一,它衡量的是模型预测正确的样本数量占总样本数量的比例。在Logit.m文件中,精确度的计算可能涉及到混淆矩阵的构建,混淆矩阵是一种特定格式的表格,可以清楚地展示模型预测结果与实际结果之间的关系。 除了精确度之外,Logistic回归模型的评估还可以通过其他指标完成,比如: - 准确率(Accuracy):正确分类的样本数与总样本数之比。 - 召回率(Recall):正确预测为正类的样本数占实际正类样本数的比例。 - 精确率(Precision):正确预测为正类的样本数占预测为正类样本数的比例。 - F1分数(F1 Score):精确率和召回率的调和平均数。 - ROC曲线(Receiver Operating Characteristic Curve)和AUC值(Area Under Curve):反映模型对正负类区分能力的曲线图和统计量。 在使用Logit.m文件时,用户应该熟悉MATLAB编程基础,包括矩阵操作、函数使用等,以便能够正确调用程序并处理分析结果。此外,用户还需要有一定的统计学基础,以便理解Logistic回归分析的原理和输出结果的含义。"

相关推荐

filetype

import os import pandas as pd import numpy as np import statsmodels.api as sm def build_logistic_regression(): """构建逻辑回归模型并输出OR值分析结果""" try: # 1. 路径配置 desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop') # 特征工程文件 fe_file1 = os.path.join(desktop_path, "C:/Users\Ran\Desktop\特征工程_附件1.xlsx") fe_file2 = os.path.join(desktop_path, "C:/Users\Ran\Desktop\特征工程_附件2.xlsx") # 原始处理文件 raw_file1 = os.path.join(desktop_path, "C:/Users\Ran\Desktop\处理后附件1.xlsx") raw_file2 = os.path.join(desktop_path, "C:/Users\Ran\Desktop\处理后附件2.xlsx") # 验证文件存在性 for f in [fe_file1, fe_file2, raw_file1, raw_file2]: if not os.path.exists(f): raise FileNotFoundError(f"必要文件 {f} 未找到") # 2. 读取特征工程处理数据 fe_df1 = pd.read_excel(fe_file1) fe_df2 = pd.read_excel(fe_file2) # 3. 读取原始处理数据 raw_df1 = pd.read_excel(raw_file1) raw_df2 = pd.read_excel(raw_file2) # 4. 定义特征工程标记列 fe_columns = { 'transport_duration': ['转运时长'], 'vital_fluctuation': [col for col in fe_df1.columns if '_波动指数' in col], 'pipe_load': ['高危管道负荷'], 'z_score': [col for col in fe_df1.columns if col in ['年龄', '体重', '收缩压', '心率', '转运时长']] } # 5. 合并数据(保留特征工程结果,补充原始指标) def merge_data(fe_df, raw_df): # 保留特征工程处理列 fe_cols = fe_df.columns.tolist() # 提取原始数据中未处理的列 raw_cols = [col for col in raw_df.columns if col not in fe_cols and col != '住院号'] # 合并数据 merged = pd.merge( fe_df, raw_df[['住院号'] + raw_cols], on='住院号', how='left' ) return merged merged_df1 = merge_data(fe_df1, raw_df1) merged_df2 = merge_data(fe_df2, raw_df2) # 6. 数据整合 final_df = pd.concat([merged_df1, merged_df2]).drop_duplicates(subset=['住院号']) # 7. 模型准备 X = final_df.select_dtypes(include=[np.number]) y = final_df['病情变化'].astype(int) # 假设目标变量存在 # 8. 模型训练 X = sm.add_constant(X) model = sm.Logit(y, X).fit(disp=0) # 9. 结果处理 results_df = pd.DataFrame({ 'OR值': np.exp(model.params), '95%CI_lower': np.exp(model.conf_int()[0]), '95%CI_upper': np.exp(model.conf_int()[1]), 'P值': model.pvalues }) # 10. 结果输出 output_path = os.path.join(desktop_path, '逻辑回归结果.xlsx') results_df.to_excel(output_path) print(f"✅ 分析完成,结果已保存至: {output_path}") print("📊 已识别特征工程列:", fe_columns) except Exception as e: print(f"❌ 操作失败: {str(e)}") return False return True if __name__ == "__main__": build_logistic_regression() 在这个代码上改

filetype

import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression, LogisticRegressionCV from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, roc_auc_score, classification_report import statsmodels.api as sm from pygam import LogisticGAM, s import matplotlib.pyplot as plt import seaborn as sns # 设置中文显示 plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"] plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 plt.rcParams['figure.dpi'] = 300 # 提高图像分辨率 # 1. 数据读取与预处理 def load_and_preprocess_data(file_path): # 读取数据 data = pd.read_excel(file_path) # 处理缺失值 print(f"原始数据形状: {data.shape}") data = data.dropna() print(f"删除缺失值后的数据形状: {data.shape}") # 选取参与分析的字段 selected_vars = ['心率(次/分)', '血氧饱和度(%)', '呼吸频率(次/分)', '体温(℃)', 'GCS评分(分)', '转运时长(min)', '转运距离(km)', '转运人员', '镇静剂使用', '呼吸支持', '年龄', 'APACHE II评分', '既往高血压史', '病情变化'] data = data[selected_vars].copy() # 对分类变量进行编码 data['转运人员'] = pd.Categorical(data['转运人员']).codes data['呼吸支持'] = pd.Categorical(data['呼吸支持']).codes return data # 2. 基础逻辑回归模型 def build_logistic_regression(X_train, y_train, X_test, y_test): print("\n===== 基础逻辑回归模型 =====") # 建立模型 logreg = LogisticRegression(max_iter=1000, random_state=42) logreg.fit(X_train, y_train) # 预测与评估 y_pred = logreg.predict(X_test) y_pred_proba = logreg.predict_proba(X_test)[:, 1] print(f"准确率: {accuracy_score(y_test, y_pred):.4f}") print(f"AUC值: {roc_auc_score(y_test, y_pred_proba):.4f}") # 输出系数和OR值 coefficients = logreg.coef_[0] odds_ratios = np.exp(coefficients).round(4) feature_names = X_train.columns result_df = pd.DataFrame({ '特征': feature_names, '系数': coefficients.round(4), 'OR值': odds_ratios }) print("\n特征系数与OR值:") print(result_df.to_string(index=False)) # 计算拟合优度 X_train_with_constant = sm.add_constant(X_train) logit_model = sm.Logit(y_train, X_train_with_constant) result = logit_model.fit(disp=False) print(f"\n逻辑回归模型拟合优度(似然比统计量 G^2):{round(result.llr, 4)}") return logreg, result_df, y_pred_proba # 3. 弹性网络逻辑回归模型 def build_elastic_net(X_train, y_train, X_test, y_test): print("\n===== 弹性网络逻辑回归模型 =====") # 建立模型 elastic_net = LogisticRegressionCV( cv=5, penalty='elasticnet', solver='saga', l1_ratios=[.1, .5, .7, .9, .95, .99, 1], max_iter=1000, random_state=42 ) elastic_net.fit(X_train, y_train) # 预测与评估 y_pred = elastic_net.predict(X_test) y_pred_proba = elastic_net.predict_proba(X_test)[:, 1] print(f"准确率: {accuracy_score(y_test, y_pred):.4f}") print(f"AUC值: {roc_auc_score(y_test, y_pred_proba):.4f}") # 输出系数和OR值 coefficients = elastic_net.coef_[0] odds_ratios = np.exp(coefficients).round(4) feature_names = X_train.columns result_df = pd.DataFrame({ '特征': feature_names, '系数': coefficients.round(4), 'OR值': odds_ratios }) print("\n特征系数与OR值:") print(result_df.to_string(index=False)) return elastic_net, result_df, y_pred_proba # 4. 非线性关系扩展(分段模型) def build_segmented_model(data): print("\n===== 非线性分段模型 =====") # 添加分段特征 # GCS评分阈值:8分 gcs_threshold = 8 data['GCS_分段'] = (data['GCS评分(分)'] < gcs_threshold).astype(int) data['GCS_交互'] = data['GCS_分段'] * (data['GCS评分(分)'] - gcs_threshold) # 转运时长阈值:20分钟 time_threshold = 20 data['转运时长_分段'] = (data['转运时长(min)'] > time_threshold).astype(int) data['转运时长_交互'] = data['转运时长_分段'] * (data['转运时长(min)'] - time_threshold) # 年龄阈值:65岁 age_threshold = 65 data['年龄_分段'] = (data['年龄'] > age_threshold).astype(int) data['年龄_交互'] = data['年龄_分段'] * (data['年龄'] - age_threshold) # 划分特征和目标变量 X_new = data.drop('病情变化', axis=1) y = data['病情变化'] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X_new, y, test_size=0.2, random_state=42 ) # 建立分段逻辑回归模型 segmented_model = LogisticRegression(max_iter=1000, random_state=42) segmented_model.fit(X_train, y_train) # 预测与评估 y_pred = segmented_model.predict(X_test) y_pred_proba = segmented_model.predict_proba(X_test)[:, 1] print(f"准确率: {accuracy_score(y_test, y_pred):.4f}") print(f"AUC值: {roc_auc_score(y_test, y_pred_proba):.4f}") # 输出阈值相关特征的系数 threshold_features = ['GCS评分(分)', 'GCS_分段', 'GCS_交互', '转运时长(min)', '转运时长_分段', '转运时长_交互', '年龄', '年龄_分段', '年龄_交互'] coef_df = pd.DataFrame({ '特征': threshold_features, '系数': [segmented_model.coef_[0][X_new.columns.get_loc(f)] for f in threshold_features] }) print("\n阈值相关特征系数:") print(coef_df.to_string(index=False)) return segmented_model, X_train, X_test, y_train, y_test, y_pred_proba # 5. GAM模型 def build_gam_model(X_train, y_train, X_test, y_test): print("\n===== 广义相加模型(GAM) =====") # 确定非线性特征的索引(GCS评分、年龄、转运时长) feature_names = X_train.columns gcs_idx = list(feature_names).index('GCS评分(分)') age_idx = list(feature_names).index('年龄') time_idx = list(feature_names).index('转运时长(min)') # 构建GAM模型:线性项 + 平滑项 gam = LogisticGAM( s(gcs_idx, n_splines=5) + # GCS评分的平滑项 s(age_idx, n_splines=5) + # 年龄的平滑项 s(time_idx, n_splines=5) + # 转运时长的平滑项 np.arange(X_train.shape[1]) # 其他特征作为线性项 ) # 拟合模型 gam.fit(X_train.values, y_train.values) # 预测与评估 y_pred_proba = gam.predict_proba(X_test.values) y_pred = (y_pred_proba > 0.5).astype(int) print(f"准确率: {accuracy_score(y_test, y_pred):.4f}") print(f"AUC值: {roc_auc_score(y_test, y_pred_proba):.4f}") # 输出模型摘要 print("\nGAM模型摘要:") print(gam.summary()) return gam, feature_names, y_pred_proba # 6. 模型可视化 def visualize_results(data, logreg_proba, elastic_proba, segmented_proba, gam_proba, gam, feature_names, X_test, y_test): # 创建图形 fig = plt.figure(figsize=(20, 16)) # 1. 模型预测概率对比 ax1 = fig.add_subplot(2, 2, 1) sns.kdeplot(logreg_proba, label='基础逻辑回归', ax=ax1) sns.kdeplot(elastic_proba, label='弹性网络', ax=ax1) sns.kdeplot(segmented_proba, label='分段模型', ax=ax1) sns.kdeplot(gam_proba, label='GAM模型', ax=ax1) ax1.set_title('各模型预测概率分布') ax1.set_xlabel('病情变化概率') ax1.legend() # 2. 特征重要性对比(基于系数绝对值) ax2 = fig.add_subplot(2, 2, 2) logreg_coef = np.abs(logreg.coef_[0]) elastic_coef = np.abs(elastic_net.coef_[0]) indices = np.argsort(logreg_coef)[-10:] # 取最重要的10个特征 features = [feature_names[i] for i in indices] width = 0.35 x = np.arange(len(features)) ax2.bar(x - width/2, logreg_coef[indices], width, label='基础逻辑回归') ax2.bar(x + width/2, elastic_coef[indices], width, label='弹性网络') ax2.set_xticks(x) ax2.set_xticklabels(features, rotation=90) ax2.set_title('特征重要性对比(系数绝对值)') ax2.legend() # 3. GAM模型平滑函数可视化 - GCS评分 ax3 = fig.add_subplot(2, 2, 3) gcs_idx = list(feature_names).index('GCS评分(分)') XX = gam.generate_X_grid(term=gcs_idx) pdep, confi = gam.partial_dependence(term=gcs_idx, X=XX, width=0.95) ax3.plot(XX[:, gcs_idx], pdep) ax3.fill_between(XX[:, gcs_idx], confi[:, 0], confi[:, 1], alpha=0.3) ax3.axvline(x=8, color='r', linestyle='--', label='阈值=8分') ax3.set_title('GCS评分的非线性效应') ax3.set_xlabel('GCS评分(分)') ax3.set_ylabel('对log odds的影响') ax3.legend() # 4. GAM模型平滑函数可视化 - 转运时长 ax4 = fig.add_subplot(2, 2, 4) time_idx = list(feature_names).index('转运时长(min)') XX = gam.generate_X_grid(term=time_idx) pdep, confi = gam.partial_dependence(term=time_idx, X=XX, width=0.95) ax4.plot(XX[:, time_idx], pdep) ax4.fill_between(XX[:, time_idx], confi[:, 0], confi[:, 1], alpha=0.3) ax4.axvline(x=20, color='r', linestyle='--', label='阈值=20分钟') ax4.set_title('转运时长的非线性效应') ax4.set_xlabel('转运时长(min)') ax4.set_ylabel('对log odds的影响') ax4.legend() plt.tight_layout() plt.savefig('医疗转运模型结果可视化.png', bbox_inches='tight') plt.show() # 额外绘制年龄的非线性效应 plt.figure(figsize=(10, 6)) age_idx = list(feature_names).index('年龄') XX = gam.generate_X_grid(term=age_idx) pdep, confi = gam.partial_dependence(term=age_idx, X=XX, width=0.95) plt.plot(XX[:, age_idx], pdep) plt.fill_between(XX[:, age_idx], confi[:, 0], confi[:, 1], alpha=0.3) plt.axvline(x=65, color='r', linestyle='--', label='阈值=65岁') plt.title('年龄的非线性效应') plt.xlabel('年龄') plt.ylabel('对log odds的影响') plt.legend() plt.tight_layout() plt.savefig('年龄非线性效应.png', bbox_inches='tight') plt.show() # 主函数 if __name__ == "__main__": # 加载数据 data = load_and_preprocess_data(r"C:\Users\Ran\Desktop\医疗转运模拟数据.xlsx") # 准备基础模型数据 X = data.drop('病情变化', axis=1) y = data['病情变化'] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # 建立并评估各模型 logreg, logreg_results, logreg_proba = build_logistic_regression( X_train, y_train, X_test, y_test ) elastic_net, elastic_results, elastic_proba = build_elastic_net( X_train, y_train, X_test, y_test ) segmented_model, X_train_seg, X_test_seg, y_train_seg, y_test_seg, segmented_proba = build_segmented_model( data.copy() ) gam, feature_names, gam_proba = build_gam_model( X_train_seg, y_train_seg, X_test_seg, y_test_seg ) # 可视化结果 visualize_results( data, logreg_proba, elastic_proba, segmented_proba, gam_proba, gam, feature_names, X_test_seg, y_test_seg ) print("\n===== 模型比较总结 =====") print(f"基础逻辑回归 AUC: {roc_auc_score(y_test, logreg_proba):.4f}") print(f"弹性网络回归 AUC: {roc_auc_score(y_test, elastic_proba):.4f}") print(f"分段模型 AUC: {roc_auc_score(y_test_seg, segmented_proba):.4f}") print(f"GAM模型 AUC: {roc_auc_score(y_test_seg, gam_proba):.4f}") 改一下GAM部分 GAM模型的建立 在本问对患者转运过程中病情变化影响因素的分析中,GAM(广义相加模型)用于综合捕捉线性与非线性关系,其核心原理是将线性回归的纯线性特征组合扩展为线性项+平滑项的混合形式,既能保留线性特征的解释性,又能通过平滑函数灵活拟合非线性特征的曲线关系。 对线性特征用参数项,对非线性特征用平滑函数,涉及公式如下: log\left(\frac{p}{1-p}\right)=\beta_0+\sum\beta_jx_j+s_1\left(\mathrm{GCS}\right)+s2年龄+s_3转运时长 其中,s_k为平滑函数,用于拟合非线性特征:通过s_1\left(\mathrm{GCS}\right)捕捉“GCS<8 分时风险骤增”的阈值效应,通过s_2年龄刻画 “65 岁后风险加速上升” 的趋势,通过s_3转运时长呈现 “>20 分钟后风险增速翻倍” 的累积效应。 及以下相关部分的代码

filetype

``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest, f_classif from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report, roc_curve, auc, confusion_matrix import statsmodels.api as sm from sklearn.metrics import precision_score, roc_curve plt.style.use('ggplot') # 读取数据 file_path = r'C:\Users\29930\Desktop\插补数据.csv' data = pd.read_csv(file_path,encoding='GBK') data['性别'] = data['性别'].map({'男': 0, '女': 1}) # 编码性别列 arr = data.to_numpy() # 转换为NumPy数组 # 查看前几行数据 print(data.head()) # 检查是否有缺失值 print(data.isnull().sum()) # 填充缺失值(如果有的话) data.ffill(inplace=True) # 分离特征和目标变量 X = data.drop(columns=['慢阻肺']) # 假设第一列为COPD标签 y = data['慢阻肺'] # 标准化数值型特征 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 将标准化后的数据转回DataFrame格式以便后续操作 X_scaled_df = pd.DataFrame(X_scaled, columns=X.columns) # 使用SelectKBest进行单变量选择 selector = SelectKBest(score_func=f_classif, k='all') # 先全部选出来查看得分情况 fit = selector.fit(X_scaled_df, y) # 打印每个特征的重要性评分 feature_scores = pd.DataFrame(list(zip(X_scaled_df.columns, fit.scores_)), columns=['Feature','Score']) feature_scores.sort_values(by='Score', ascending=False, inplace=True) print(feature_scores) # 绘制特征重要性图 plt.figure(figsize=(10, 6)) sns.barplot(x="Score", y="Feature", data=feature_scores) plt.title('Feature Importance Scores') plt.show() # 选择最重要的几个特征 selected_features = feature_scores[feature_scores.Score >= feature_scores.Score.quantile(0.75)].Feature.tolist() # 选取前75%分位数以上的特征 X_selected = X_scaled_df[selected_features] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=42) # 定义逻辑回归模型 logreg = LogisticRegression(solver='liblinear') # 超参数调优 - 这里我们只对正则化强度C做网格搜索 param_grid = {'C': [0.01, 0.1, 1, 10, 100]} grid_search = GridSearchCV(logreg, param_grid, cv=5, scoring='accuracy') grid_search.fit(X_train, y_train) # 输出最佳参数组合及对应的成绩 best_logreg = grid_search.best_estimator_ print("Best parameters:", grid_search.best_params_) print("Best CV Score:", grid_search.best_score_) # 在测试集上应用最优模型 y_pred = best_logreg.predict(X_test) # 计算性能指标 acc = accuracy_score(y_test, y_pred) report = classification_report(y_test, y_pred) conf_mat = confusion_matrix(y_test, y_pred) print(f"Accuracy: {acc:.4f}") print(report) # 绘制混淆矩阵热力图 plt.figure(figsize=(8, 6)) sns.heatmap(conf_mat, annot=True, fmt='d', cmap='Blues') plt.xlabel('Predicted Label') plt.ylabel('True Label') plt.title('Confusion Matrix Heatmap') plt.show() # ROC曲线 fpr, tpr, _ = roc_curve(y_test, best_logreg.decision_function(X_test)) roc_auc = auc(fpr, tpr) plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC Curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.legend(loc="lower right") plt.show() # 添加常数项 X_const = sm.add_constant(X_selected) # 构建OLS线性回归模型(用于展示线性关系) model = sm.Logit(y, X_const).fit() print(model.summary()) # 获取最终模型方程 coefs = list(best_logreg.coef_[0]) + [best_logreg.intercept_[0]] features_with_intercept = ['const'] + selected_features formula_parts = [] for coef, feat in zip(coefs, features_with_intercept): formula_parts.append(f"{coef:+.4f}*{feat}") final_formula = " + ".join(formula_parts) print("\nFinal Early Screening Formula:") print(final_formula.replace('+', ' + ').replace('-', ' - '))```各类图像不能显示中文

资源评论
用户头像
朱王勇
2025.05.23
内容涵盖了logistic分析的核心概念,并提供了基于Matlab的实现方法,很实用。
用户头像
甜甜不加糖
2025.03.25
对研究logistic回归或想在Matlab中深入实践的学者来说,这是一份宝贵的资料。
用户头像
阿葱的葱白
2025.02.24
该文档是关于Matlab中logistic回归分析的程序,适用于想要提高分析精确度的专业人士。
用户头像
MsingD
2025.02.09
文档详细介绍了logit的运用,适合Matlab用户学习和应用logistic回归技术。
用户头像
大禹倒杯茶
2025.01.12
如果需要进行logistic回归分析,此Matlab资源是个不错的选择,特别是对精确度有要求的场景。
小贝德罗
  • 粉丝: 112
上传资源 快速赚钱