statsmodels.stats.mediation.Mediation¶
-
class statsmodels.stats.mediation.Mediation(outcome_model, mediator_model, exposure, mediator=
None, moderators=None, outcome_fit_kwargs=None, mediator_fit_kwargs=None, outcome_predict_kwargs=None)[source]¶ 进行中介分析。
- Parameters:¶
- outcome_model
statsmodelsmodel 用于结果的回归模型。预测变量包括处理/暴露、中介变量以及任何其他感兴趣的变量。
- mediator_model
statsmodelsmodel 中介变量的回归模型。预测变量包括处理/暴露以及任何其他感兴趣的变量。
- exposure
stror(int,int)tuple 处理/暴露变量的名称或列位置。如果给出位置,第一个整数是结果模型中暴露变量的列位置,第二个整数是中介模型中暴露变量的位置。如果给出字符串,它必须是两个回归模型中暴露变量的名称。
- mediator{
str,int} 结果回归模型中中介变量的名称或列位置。如果为 None,则从中介模型公式(如果存在)推断名称。
- moderators
dict 映射变量名称或索引位置到调节变量的值,这些值在计算中介效应时保持固定。如果键是索引位置,它们必须是元组(i, j),其中i是结果模型中的索引,j是中介模型中的索引。否则,键必须是变量名称。
- outcome_fit_kwargsdict-like
拟合结果模型时使用的关键字参数。
- mediator_fit_kwargsdict-like
拟合中介模型时使用的关键字参数。
- outcome_predict_kwargsdict-like
在调用结果模型上的 predict 时使用的关键字参数。
- Returns a ``MediationResults`` object.
- outcome_model
注释
中介者模式类必须实现
get_distribution。参考文献
Imai, Keele, Tingley (2010). 一种因果中介分析的通用方法。心理方法 15:4, 309-334. http://imai.princeton.edu/research/files/BaronKenny.pdf
Tingley, Yamamoto, Hirose, Keele, Imai (2014). mediation : R 用于因果中介分析的软件包。 统计软件杂志 59:5。 http://www.jstatsoft.org/v59/i05/paper
示例
使用公式进行基本的调解分析:
>>> import statsmodels.api as sm >>> import statsmodels.genmod.families.links as links >>> probit = links.probit >>> outcome_model = sm.GLM.from_formula("cong_mesg ~ emo + treat + age + educ + gender + income", ... data, family=sm.families.Binomial(link=Probit())) >>> mediator_model = sm.OLS.from_formula("emo ~ treat + age + educ + gender + income", data) >>> med = Mediation(outcome_model, mediator_model, "treat", "emo").fit() >>> med.summary()一个不使用公式的基本中介分析。这可能比使用公式的方法稍快。如果涉及处理变量或中介变量的任何交互作用,这种方法将不起作用,您必须使用公式。
>>> import patsy >>> outcome = np.asarray(data["cong_mesg"]) >>> outcome_exog = patsy.dmatrix("emo + treat + age + educ + gender + income", data, ... return_type='dataframe') >>> probit = sm.families.links.probit >>> outcome_model = sm.GLM(outcome, outcome_exog, family=sm.families.Binomial(link=Probit())) >>> mediator = np.asarray(data["emo"]) >>> mediator_exog = patsy.dmatrix("treat + age + educ + gender + income", data, ... return_type='dataframe') >>> mediator_model = sm.OLS(mediator, mediator_exog) >>> tx_pos = [outcome_exog.columns.tolist().index("treat"), ... mediator_exog.columns.tolist().index("treat")] >>> med_pos = outcome_exog.columns.tolist().index("emo") >>> med = Mediation(outcome_model, mediator_model, tx_pos, med_pos).fit() >>> med.summary()一个调节的中介分析。 中介效应是针对年龄为20岁的人计算的。
>>> fml = "cong_mesg ~ emo + treat*age + emo*age + educ + gender + income", >>> outcome_model = sm.GLM.from_formula(fml, data, ... family=sm.families.Binomial()) >>> mediator_model = sm.OLS.from_formula("emo ~ treat*age + educ + gender + income", data) >>> moderators = {"age" : 20} >>> med = Mediation(outcome_model, mediator_model, "treat", "emo", ... moderators=moderators).fit()方法
fit([method, n_rep])拟合回归模型以评估中介效应。