Beispiel #1
0
def random_effect_2level_model(dataframe):
    """
    Multi-level model_1_sci includes intercept, variable as fixed and the
    interaction term
    random on country level.

        :param dataframe: a data frame with student ID, school ID, country ID,
        science, math, reading, and other five selected variables as
        predictors.
        :return: the model results
    """
    # Random intercept and slope two-level model:
    model_1_sci = Lmer('Science ~ female + (female*ESCS | CountryID)',
                       data=dataframe)
    # model must be fitted in order to get estimate results
    model_1_sci.fit(REML=False)
    # print summary since auto-generated result doesn't include fixed effects
    print(model_1_sci.summary())
    model_1_sci.plot_summary()
    # Visualizing random effect of a predictor
    model_1_sci.plot('female', plot_ci=True, ylabel='Predicted log_science')

    sns.regplot(x='female',
                y='residuals',
                data=model_1_sci.data,
                fit_reg=False)
    # Inspecting overall fit
    sns.regplot(x='fits',
                y='log_science',
                units='CountryID',
                data=model_1_sci.data,
                fit_reg=True)
    return model_1_sci
Beispiel #2
0
def mixeff_multinteraction2level_model(dataframe):
    """
    Multi-level model_5_sci includes intercept, multiple interactions and
    fixed effects,
     and setting ESCS as random on country level.

        :param dataframe: a data frame with student ID, school ID, country ID,
        science, math, reading, and other five selected variables as
        predictors.
        :return: the model results
    """
    # one random effect and multiple interactions between gender and factors
    model_5_sci = Lmer(
        'log_science ~ IBTEACH + WEALTH + ESCS + female + '
        'Sch_science_resource '
        '+ female*ESCS '
        '+ female*WEALTH + female*IBTEACH + (ESCS | CountryID)',
        data=dataframe)
    # model must be fitted in order to get estimate results
    model_5_sci.fit(REML=False)
    # print summary since auto-generated result doesn't include fixed effects
    print(model_5_sci.summary())
    model_5_sci.plot_summary()
    # Visualizing random effect of a predictor
    model_5_sci.plot('ESCS', plot_ci=True, ylabel='Predicted log_science')

    sns.regplot(x='ESCS', y='residuals', data=model_5_sci.data, fit_reg=False)
    # Inspecting overall fit
    sns.regplot(x='fits',
                y='log_science',
                units='CountryID',
                data=model_5_sci.data,
                fit_reg=True)
    return model_5_sci