【python、R如何实现逐步回归(前向、后向、双向)】

1. python 实现代码

#################################### 逐步回归
def stepwise_select(data,label,cols_all,method='forward'):
    '''
    args:
        data:数据源,df
        label:标签,str
        cols_all:逐步回归的全部字段
        methrod:方法,forward:向前,backward:向后,both:双向
    return:
        select_col:最终保留的字段列表,list 
        summary:模型参数
        AIC:aic
    '''
    import statsmodels.api as sm
    
    ######################## 1.前向回归
    # 前向回归:从一个变量都没有开始,一个变量一个变量的加入到模型中,直至没有可以再加入的变量结束
    if method == 'forward':  
        add_col = [] 
        AIC_None_value = np.inf
        while cols_all:
            # 单个变量加入,计算aic
            AIC = {
   }
            for col in cols_all:
                print(col)
                X_col = add_col.copy()
                X_col.append(col)
                X = sm.add_constant(data[X_col])
                y = data[label]
                LR = sm.Logit(y, X).fit()
                AIC[col] = LR.aic
            AIC_min_value = min(AIC.values())   
            AIC_min_key = min(AIC,key=AIC.get)
            # 如果最小的aic小于不加该变量时的aic,则加入变量,否则停止
            if AIC_min_value 
### 如何在Python中执行逐步回归检验 逐步回归是一种用于特征选择的方法,旨在构建一个最优的线性回归模型。该方法通过迭代地增加或删除变量来优化模型性能。Python 中可以利用 `stepwise_selection` 函数实现这一过程。 为了在 Python 中执行逐步回归测试,通常会采用如下方式: 定义一个函数来进行向选择、后向消除或者双向淘汰。这里提供了一个基于 P-values 和 Adjusted R-Squared 的简单实现方案[^1]: ```python import statsmodels.api as sm import pandas as pd def stepwise_selection(X, y, initial_list=[], threshold_in=0.01, threshold_out=0.05, verbose=True): """ Perform a forward-backward feature selection based on p-value from statsmodels.api.OLS. Arguments: X {pandas.DataFrame} -- A data frame with all available features. y {pandas.Series} -- The target variable. Keyword Arguments: initial_list {list} -- Initial list of features (default: {[]}) threshold_in {float} -- Include a feature if its p < threshold_in (default: {0.01}) threshold_out {float} -- Exclude a feature if its p > threshold_out (default: {0.05}) verbose {bool} -- Whether to prints the sequence of inclusions and exclusions (default: {True}) Returns: included {list} -- List of selected variables. """ included = list(initial_list) while True: changed=False # Forward step excluded = list(set(X.columns)-set(included)) new_pval = pd.Series(index=excluded,dtype=float) for new_column in excluded: model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included+[new_column]]))).fit() new_pval[new_column] = model.pvalues[new_column] best_pval = new_pval.min() if best_pval<threshold_in: best_feature = new_pval.idxmin() included.append(best_feature) changed=True if verbose: print('Add {:30} with p-value {:.6}'.format(best_feature,best_pval)) # Backward step model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit() # use all coefs except intercept pvalues = model.pvalues.iloc[1:] worst_pval = pvalues.max() # null if pvalues is empty if worst_pval>threshold_out: changed=True worst_feature = pvalues.argmax() included.remove(worst_feature) if verbose: print('Drop {:30} with p-value {:.6}'.format(worst_feature,worst_pval)) if not changed: break return included ``` 此代码片段展示了如何创建一个自定义功能以自动化的方式挑选最合适的预测因子集合。给定一组潜在解释变量 \(X\) 及响应变量 \(y\), 上述算法将返回最终选定的一组列名作为输入数据框中的索引列表。 值得注意的是,在实际应用过程中可能还需要考虑其他因素如共线性和交叉验证等,以便进一步提高所选子集的质量和稳定性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值