多元逐步回归算法

article/2025/9/3 9:06:12
先谈一下个人对多元逐步回归的理解:多元逐步回归的最本质的核心是最小二乘原理,本方法中调用smf方法。# encoding: utf-8"""
功能:多元逐步回归
描述:基于python实现多元逐步回归的功能
作者:CHEN_C_W (草木陈)
时间:2019年4月12日(星期五) 凌晨
地点:杭州
参考:https://www.cnblogs.com/lantingg/p/9535010.html
"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from statsmodels.formula import api as smf
class FeatureSelection():
def stepwise(self, df, response, intercept=True, normalize=False, criterion='bic',f_pvalue_enter=.05, p_value_enter=.05, direction='backward', show_step=True,criterion_enter=None, criterion_remove=None, max_iter=200, **kw):"""逐步回归。参数----df : dataframe分析用数据框,response为第一列。response : str回归分析相应变量。intercept : bool, 默认是True模型是否有截距项。criterion : str, 默认是'bic'逐步回归优化规则。f_pvalue_enter : float, 默认是.05当选择criterion=’ssr‘时,模型加入或移除变量的f_pvalue阈值。p_value_enter : float, 默认是.05当选择derection=’both‘时,移除变量的pvalue阈值。direction : str, 默认是'backward'逐步回归方向。show_step : bool, 默认是True是否显示逐步回归过程。criterion_enter : float, 默认是None当选择derection=’both‘或'forward'时,模型加入变量的相应的criterion阈值。criterion_remove : float, 默认是None当选择derection='backward'时,模型移除变量的相应的criterion阈值。max_iter : int, 默认是200模型最大迭代次数。"""criterion_list = ['bic', 'aic', 'ssr', 'rsquared', 'rsquared_adj']if criterion not in criterion_list:raise IOError('请输入正确的criterion, 必须是以下内容之一:', '\n', criterion_list)direction_list = ['backward', 'forward', 'both']if direction not in direction_list:raise IOError('请输入正确的direction, 必须是以下内容之一:', '\n', direction_list)# 默认p_enter参数p_enter = {'bic': 0.0, 'aic': 0.0, 'ssr': 0.05, 'rsquared': 0.05, 'rsquared_adj': -0.05}if criterion_enter:  # 如果函数中对p_remove相应key传参,则变更该参数p_enter[criterion] = criterion_enter# 默认p_remove参数p_remove = {'bic': 0.01, 'aic': 0.01, 'ssr': 0.1, 'rsquared': 0.05, 'rsquared_adj': -0.05}if criterion_remove:  # 如果函数中对p_remove相应key传参,则变更该参数p_remove[criterion] = criterion_removeif normalize:  # 如果需要标准化数据intercept = False  # 截距强制设置为0df_std = StandardScaler().fit_transform(df)df = pd.DataFrame(df_std, columns=df.columns, index=df.index)""" forward """if direction == 'forward':remaining = list(df.columns)  # 自变量集合remaining.remove(response)selected = []  # 初始化选入模型的变量列表# 初始化当前评分,最优新评分if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, remaining[0])else:formula = "{} ~ {} - 1".format(response, remaining[0])result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合current_score = eval('result.' + criterion)best_new_score = eval('result.' + criterion)if show_step:print('\nstepwise starting:\n')iter_times = 0# 当变量未剔除完,并且当前评分更新时进行循环while remaining and (current_score == best_new_score) and (iter_times < max_iter):scores_with_candidates = []  # 初始化变量以及其评分列表for candidate in remaining:  # 在未剔除的变量中每次选择一个变量进入模型,如此循环if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected + [candidate]))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected + [candidate]))result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合fvalue = result.fvaluef_pvalue = result.f_pvaluescore = eval('result.' + criterion)scores_with_candidates.append((score, candidate, fvalue, f_pvalue))  # 记录此次循环的变量、评分列表if criterion == 'ssr':  # 这几个指标取最小值进行优化scores_with_candidates.sort(reverse=True)  # 对评分列表进行降序排序best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()  # 提取最小分数及其对应变量if ((current_score - best_new_score) > p_enter[criterion]) and (best_new_f_pvalue < f_pvalue_enter):  # 如果当前评分大于最新评分remaining.remove(best_candidate)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.append(best_candidate)  # 将最新最优分对应的变量放入已选变量列表current_score = best_new_score  # 更新当前评分if show_step:  # 是否显示逐步回归过程print('Adding %s, SSR = %.3f, Fstat = %.3f, FpValue = %.3e' %(best_candidate, best_new_score, best_new_fvalue, best_new_f_pvalue))elif (current_score - best_new_score) >= 0 and (best_new_f_pvalue < f_pvalue_enter) and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (best_new_f_pvalue < f_pvalue_enter) and iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))elif criterion in ['bic', 'aic']:  # 这几个指标取最小值进行优化scores_with_candidates.sort(reverse=True)  # 对评分列表进行降序排序best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()  # 提取最小分数及其对应变量if (current_score - best_new_score) > p_enter[criterion]:  # 如果当前评分大于最新评分remaining.remove(best_candidate)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.append(best_candidate)  # 将最新最优分对应的变量放入已选变量列表current_score = best_new_score  # 更新当前评分# print(iter_times)if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (current_score - best_new_score) >= 0 and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))else:scores_with_candidates.sort()best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()if (best_new_score - current_score) > p_enter[criterion]:remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreprint(iter_times, flush=True)if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (best_new_score - current_score) >= 0 and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))iter_times += 1if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected))self.stepwise_model = smf.ols(formula, df).fit()  # 最优模型拟合if show_step:  # 是否显示逐步回归过程print('\nLinear regression model:', '\n  ', self.stepwise_model.model.formula)print('\n', self.stepwise_model.summary())""" backward """if direction == 'backward':remaining, selected = set(df.columns), set(df.columns)  # 自变量集合remaining.remove(response)selected.remove(response)  # 初始化选入模型的变量列表# 初始化当前评分,最优新评分if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected))result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合current_score = eval('result.' + criterion)worst_new_score = eval('result.' + criterion)if show_step:print('\nstepwise starting:\n')iter_times = 0# 当变量未剔除完,并且当前评分更新时进行循环while remaining and (current_score == worst_new_score) and (iter_times < max_iter):scores_with_eliminations = []  # 初始化变量以及其评分列表for elimination in remaining:  # 在未剔除的变量中每次选择一个变量进入模型,如此循环if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected - set(elimination)))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected - set(elimination)))result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合fvalue = result.fvaluef_pvalue = result.f_pvaluescore = eval('result.' + criterion)scores_with_eliminations.append((score, elimination, fvalue, f_pvalue))  # 记录此次循环的变量、评分列表if criterion == 'ssr':  # 这几个指标取最小值进行优化scores_with_eliminations.sort(reverse=False)  # 对评分列表进行降序排序worst_new_score, worst_elimination, worst_new_fvalue, worst_new_f_pvalue = scores_with_eliminations.pop()  # 提取最小分数及其对应变量if ((worst_new_score - current_score) < p_remove[criterion]) and (worst_new_f_pvalue < f_pvalue_enter):  # 如果当前评分大于最新评分remaining.remove(worst_elimination)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.remove(worst_elimination)  # 从已选变量列表中剔除最新最优分对应的变量current_score = worst_new_score  # 更新当前评分if show_step:  # 是否显示逐步回归过程print('Removing %s, SSR = %.3f, Fstat = %.3f, FpValue = %.3e' %(worst_elimination, worst_new_score, worst_new_fvalue, worst_new_f_pvalue))elif criterion in ['bic', 'aic']:  # 这几个指标取最小值进行优化scores_with_eliminations.sort(reverse=False)  # 对评分列表进行降序排序worst_new_score, worst_elimination, worst_new_fvalue, worst_new_f_pvalue = scores_with_eliminations.pop()  # 提取最小分数及其对应变量if (worst_new_score - current_score) < p_remove[criterion]:  # 如果评分变动不显著remaining.remove(worst_elimination)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.remove(worst_elimination)  # 从已选变量列表中剔除最新最优分对应的变量current_score = worst_new_score  # 更新当前评分if show_step:  # 是否显示逐步回归过程print('Removing %s, %s = %.3f' % (worst_elimination, criterion, worst_new_score))else:scores_with_eliminations.sort(reverse=True)worst_new_score, worst_elimination, worst_new_fvalue, worst_new_f_pvalue = scores_with_eliminations.pop()if (current_score - worst_new_score) < p_remove[criterion]:remaining.remove(worst_elimination)selected.remove(worst_elimination)current_score = worst_new_scoreif show_step:  # 是否显示逐步回归过程print('Removing %s, %s = %.3f' % (worst_elimination, criterion, worst_new_score))iter_times += 1if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected))self.stepwise_model = smf.ols(formula, df).fit()  # 最优模型拟合if show_step:  # 是否显示逐步回归过程print('\nLinear regression model:', '\n  ', self.stepwise_model.model.formula)print('\n', self.stepwise_model.summary())""" both """if direction == 'both':remaining = list(df.columns)  # 自变量集合remaining.remove(response)selected = []  # 初始化选入模型的变量列表# 初始化当前评分,最优新评分if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, remaining[0])else:formula = "{} ~ {} - 1".format(response, remaining[0])result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合current_score = eval('result.' + criterion)best_new_score = eval('result.' + criterion)if show_step:print('\nstepwise starting:\n')# 当变量未剔除完,并且当前评分更新时进行循环iter_times = 0while remaining and (current_score == best_new_score) and (iter_times < max_iter):scores_with_candidates = []  # 初始化变量以及其评分列表for candidate in remaining:  # 在未剔除的变量中每次选择一个变量进入模型,如此循环if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected + [candidate]))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected + [candidate]))result = smf.ols(formula, df).fit()  # 最小二乘法回归模型拟合fvalue = result.fvaluef_pvalue = result.f_pvaluescore = eval('result.' + criterion)scores_with_candidates.append((score, candidate, fvalue, f_pvalue))  # 记录此次循环的变量、评分列表if criterion == 'ssr':  # 这几个指标取最小值进行优化scores_with_candidates.sort(reverse=True)  # 对评分列表进行降序排序best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()    # 提取最小分数及其对应变量if ((current_score - best_new_score) > p_enter[criterion]) and (best_new_f_pvalue < f_pvalue_enter):  # 如果当前评分大于最新评分remaining.remove(best_candidate)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.append(best_candidate)  # 将最新最优分对应的变量放入已选变量列表current_score = best_new_score  # 更新当前评分if show_step:  # 是否显示逐步回归过程print('Adding %s, SSR = %.3f, Fstat = %.3f, FpValue = %.3e' %(best_candidate, best_new_score, best_new_fvalue, best_new_f_pvalue))elif (current_score - best_new_score) >= 0 and (best_new_f_pvalue < f_pvalue_enter) and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (best_new_f_pvalue < f_pvalue_enter) and iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))elif criterion in ['bic', 'aic']:  # 这几个指标取最小值进行优化scores_with_candidates.sort(reverse=True)  # 对评分列表进行降序排序best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()  # 提取最小分数及其对应变量if (current_score - best_new_score) > p_enter[criterion]:  # 如果当前评分大于最新评分remaining.remove(best_candidate)  # 从剩余未评分变量中剔除最新最优分对应的变量selected.append(best_candidate)  # 将最新最优分对应的变量放入已选变量列表current_score = best_new_score  # 更新当前评分if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (current_score - best_new_score) >= 0 and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))else:scores_with_candidates.sort()best_new_score, best_candidate, best_new_fvalue, best_new_f_pvalue = scores_with_candidates.pop()if (best_new_score - current_score) > p_enter[criterion]:  # 当评分差大于p_enterremaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif (best_new_score - current_score) >= 0 and iter_times == 0:  # 当评分差大于等于0,且为第一次迭代remaining.remove(best_candidate)selected.append(best_candidate)current_score = best_new_scoreif show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (best_candidate, criterion, best_new_score))elif iter_times == 0:  # 当评分差小于p_enter,且为第一次迭代selected.append(remaining[0])remaining.remove(remaining[0])if show_step:  # 是否显示逐步回归过程print('Adding %s, %s = %.3f' % (remaining[0], criterion, best_new_score))if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected))result = smf.ols(formula, df).fit()  # 最优模型拟合if iter_times >= 1:  # 当第二次循环时判断变量的pvalue是否达标if result.pvalues.max() > p_value_enter:var_removed = result.pvalues[result.pvalues == result.pvalues.max()].index[0]p_value_removed = result.pvalues[result.pvalues == result.pvalues.max()].values[0]selected.remove(result.pvalues[result.pvalues == result.pvalues.max()].index[0])if show_step:  # 是否显示逐步回归过程print('Removing %s, Pvalue = %.3f' % (var_removed, p_value_removed))iter_times += 1if intercept:  # 是否有截距formula = "{} ~ {} + 1".format(response, ' + '.join(selected))else:formula = "{} ~ {} - 1".format(response, ' + '.join(selected))self.stepwise_model = smf.ols(formula, df).fit()  # 最优模型拟合if show_step:  # 是否显示逐步回归过程print('\nLinear regression model:', '\n  ', self.stepwise_model.model.formula)print('\n', self.stepwise_model.summary())# 最终模型选择的变量if intercept:self.stepwise_feat_selected_ = list(self.stepwise_model.params.index[1:])else:self.stepwise_feat_selected_ = list(self.stepwise_model.params.index)return self
def main():print('main方法进入了......')# url = "http://data.princeton.edu/wws509/datasets/salary.dat"# data = pd.read_csv(url, sep='\\s+')data = np.random.rand(200, 4)df = pd.DataFrame({'A': data[:, 0], 'B': data[:, 1], 'C': data[:, 2], 'D': data[:, 3]})print('测试data大小', df.shape)print(df.head())FeatureSelection().stepwise(df=df, response='A', max_iter=200, criterion='ssr')  # criterion='ssr'是为了移除不合适特征# 注:输入数据的结果如下图所示if __name__ == "__main__":main()

注:本文所用的测试是用随机数所求,所以逐步回归的结果大部分并没有通过检验

       方法是基于python3.6版本开发,里面的py包不同版本可能存在差异,使用时需要谨慎。

 

 


http://chatgpt.dhexx.cn/article/LSNRhBwi.shtml

相关文章

【模型开发】逐步回归

1.定义 当变量中含有对被解释变量影响不大的解释变量时&#xff0c;可能因为误差平方和的自由度减小而使方差的估计增大&#xff0c;从而影响回归预测的精度&#xff0c;适当的选择一个变量建立一个最优的回归方程十分重要。 逐步回归&#xff08;Stepwise Regression&#xff…

matlab逐步回归分析法,天大matlab大作业逐步回归分析方法.doc

天大matlab大作业逐步回归分析方法.doc 逐步回归分析方法在实际中&#xff0c;影响Y的因素很多&#xff0c;这些因素可能存在多重共线性(相关性)&#xff0c;这就对系数的估计带来不合理的解释&#xff0c;从而影响对Y的分析和预测。“最优”的回归方程就是包含所有对Y有影响的…

【R语言数据科学】(十九):变量选择(一)逐步回归法

【R语言数据科学】 🌸个人主页:JOJO数据科学📝个人介绍:统计学top3高校统计学硕士在读💌如果文章对你有帮助,欢迎✌关注、👍点赞、✌收藏、👍订阅专栏✨本文收录于【R语言数据科学】本系列主要介绍R语言在数据科学领域的应用包括: R语言编程基础、R语言可视化、R…

4.1程序控制流图

程序控制流图&#xff0c;简称流图&#xff0c;是对程序流程图进行简化后得到的&#xff0c;它可以更加突出的表示程序控制流的结构。 控制流图中包括两种图形符号&#xff1a; 节点控制流线 复合条件要分解为简单条件 判定节点&#xff08;谓词节点&#xff09; 由判定节点发…

流程控制(上)

大家好&#xff0c;我是Python领域的博主。 如果你是编程爱好者可以小编一起学习&#xff0c;在这里我每天都会发Python的基础知识&#xff0c;以及相关的代码。 如果文章有什么错误的地方&#xff0c;请不吝赐教。 觉得博主文章写的还错的话&#xff0c;请三连支持一下博主哦 …

使用soot和graphviz画Java的控制流图

辛苦两天了&#xff0c;啥也不说&#xff0c;先来张图&#xff1a; 看着可真漂亮&#xff0c;O(∩_∩)O哈哈~ 实验环境是Ubuntu。 1.JDK的版本必须是1.7或者以下&#xff0c;JDK1.8不行&#xff0c;总会报错&#xff0c; 2.下载sootclasses-2.5.0.jar包&#xff1a;http://d…

软件测试----------------- 控制流图 圈复杂度 独立路径 测试用例

最近在学软件测试&#xff0c;学到了画&#xff0c;控制流图 圈复杂度 独立路径 测试用例&#xff0c;这里&#xff0c;有些不理解&#xff0c;就网上查了下&#xff0c;发现好多老哥写错了&#xff0c;大佬写的甚至收费79。 我试着写写&#xff0c;如果有不足的&#xff0c;大…

LLVM CFG控制流图可视化

LLVM CFG控制流图可视化 准备 安装必要组件 sudo apt-get install -y graphviz-doc libgraphviz-dev graphviz示例程序 /// file 1.c int x 10; int y 11; int main(){int z 12; for (int i 0;i < 10;i){z * x * y;} return 0; }生成LLVM IR 文件 clang -S -em…

白盒测试--控制流测试(白盒测试,逻辑覆盖,路径测试(基路径测试、循环测试),控制流图)

文章目录 白盒测试概念白盒测试方法--控制流测试语句覆盖判定覆盖&#xff08;分支覆盖&#xff09;条件覆盖判定-条件覆盖条件组合覆盖路径覆盖 路径测试基路径测试循环测试 控制流图基本控制流图复合逻辑下的控制流图图矩阵环形复杂度 白盒测试概念 又叫结构测试&#xff0c…

控制流分析(Control Flow Analysis)

控制流(Control Flow)&#xff1a;操作的序列 控制流分析(Control Flow Analysis)&#xff1a;通过分析程序去发现每一过程内控制流层次结构。 控制流分析的原因&#xff1a; 控制流分析(CFA)能够帮助我们理解控制流图&#xff08;control-flow graphs,CFG&#xff09;的结构…

程序流图画法详解

程序流图一般是软件评测师考试中的第一道大题&#xff0c;同时也是必考大题&#xff0c;多层嵌套的循环程序绘制流程图时十分繁琐&#xff0c;本人在经过练习真题以及查阅资料后有了一些绘制控制流图的小经验&#xff0c;如有不对请指出。下面以2017年的软件评测师下午第一套真…

对Python控制流图(Control Flow Graph)-(CFG)的一些探索

对Python控制流图&#xff08;Control Flow Graph&#xff09;-&#xff08;CFG&#xff09;的一些探索 粗浅的了解 1.定义 控制流图(Control Flow Graph, CFG)也叫控制流程图&#xff0c;是一个过程或程序的抽象表现&#xff0c;是用在编译器中的一个抽象数据结构&#xff…

中间表示- 控制流图

基本概念 基本块&#xff1a;是语句的一个序列&#xff0c;从第一条执行到最后一条 不能从中间进入&#xff0c;不能从中间退出&#xff0c;即跳转指令只能出现在最后 控制流图&#xff1a;控制流图是一个有向图G(V&#xff0c;E) 节点V&#xff1a;是基本块边E&#xff1a…

控制流图分类

The if Statement if (x < y) {y 0;x x 1; } else {x y; } if (x < y) {y 0;x x 1; } The if-return Statement if (x < y) {return; } print (x); return; 注意&#xff1a;2到3 没有边 while and for Loops x 0; while (x < y) {y f (x, y);x x …

【浅析】程序分析中的数据流图(data flow graph)和控制流图(control flow graph)

文章目录 前言1、data flow graphs2、Control Flow Graph小结 前言 创作开始时间&#xff1a;2021年4月9日09:17:11 如题。看了一些网页文献&#xff0c;大概对这两种流图有了一定的理解&#xff0c;这里简单地记录一下&#xff0c;尤其是一些例子&#xff0c;感觉比较直观。…

软件测试之控制流图以及环形复杂度独立路径求解问题

首先需要明确的是&#xff0c;控制流图并不等于流程图&#xff0c;可以理解为控制流图的出现是为了后续的环形复杂度的计算和写出独立路径和配以相应的测试用例。 所以控制流图是核心&#xff0c;画图的时候务必谨慎再谨慎&#xff0c;要不然可能你后面的全部崩盘。 控制流图考…

【程序分析】函数调用图 | 控制流图 | 过程间控制流图 | 数据流图 | 值流图

CG&#xff08;call graph&#xff09;和CFG&#xff08;control-flow graph&#xff09;都是表示程序控制流的有向图。 1 函数调用图&#xff1a;CG&#xff08;call graph&#xff09; 一个CG是表示整个程序中方法&#xff08;函数&#xff09;之间调用关系的图&#xff0c…

LLVM CFG/DFG控制流图和数据流图可视化

1.引言 由于最近在学习数据流分析的相关知识&#xff0c;记录一下利用LLVM生成CFG和DFG的学习过程&#xff0c;参考文献和网址放在文章末尾。 2.实验环境 操作系统&#xff1a;Ubuntu 20.04.3 LTS 64bit&#xff1b; 硬件设备&#xff1a;Intel Celeron(R) CPU N34…

控制流图、圈复杂度

继续上次的测试作业&#xff0c;学习完程序插装的概念&#xff0c;今天学习测试的静态分析方法&#xff1a;绘制控制流图与计算圈复杂度。 一、控制流图&#xff1a; 一个过程或程序的抽象表现&#xff0c;常以数据结构链的形式表示。 二、圈复杂度&#xff1a; 复杂度越高&…

软件评测师必考题-控制流图

控制流图的基本知识 首先我们得清楚控制流图中的几个判断循环是如何表示的&#xff1a; 判断节点的嵌套 清楚了上面表示方法&#xff0c;你还是很难画出复杂的控制流图&#xff0c;而软考的控制流图往往是2个或多个判断节点嵌套在一起。其实只要把嵌套的节点想象成被嵌套节点…