Переменные класса доступа в пакете Python - PullRequest
1 голос
/ 28 июня 2019

Я работаю через пакет python, который использует несколько функций в одном классе и хотел бы получить доступ к одной из переменных функций классов. Как, если возможно, я могу это сделать?

Я разбил класс и функции на отдельные куски кода, но, учитывая пакет, есть ли способ для меня назвать класс скрытым или нет?

    'def fit_scores(self, balance=True, nmodels=None):
    """
    Fits logistic regression model(s) used for
    generating propensity scores
    Parameters
    ----------
    balance : bool
        Should balanced datasets be used?
        (n_control == n_test)
    nmodels : int
        How many models should be fit?
        Score becomes the average of the <nmodels> models if nmodels > 1
    Returns
    -------
    None
    """
    # reset models if refitting
    if len(self.models) > 0:
        self.models = []
    if len(self.model_accuracy) > 0:
        self.model_accuracy = []
    if not self.formula:
        # use all columns in the model
        self.formula = '{} ~ {}'.format(self.yvar, '+'.join(self.xvars))
    if balance:
        if nmodels is None:
            # fit multiple models based on imbalance severity (rounded up to nearest tenth)
            minor, major = [self.data[self.data[self.yvar] == i] for i in (self.minority, self.majority)]
            nmodels = int(np.ceil((len(major) / len(minor)) / 10) * 10)
        self.nmodels = nmodels
        i = 0
        errors = 0
        while i < nmodels and errors < 5:
            uf.progress(i+1, nmodels,
                        prestr="Fitting Models on Balanced Samples")

            # sample from majority to create balance dataset
            df = self.balanced_sample()
            df = pd.concat([uf.drop_static_cols(df[df[self.yvar] == 1], yvar=self.yvar),
                            uf.drop_static_cols(df[df[self.yvar] == 0], yvar=self.yvar)])
            y_samp, X_samp = patsy.dmatrices(self.formula, data=df, return_type='dataframe')
            X_samp.drop(self.yvar, axis=1, errors='ignore', inplace=True)

            glm = GLM(y_samp, X_samp, family=sm.families.Binomial())
            try:
                res = glm.fit()
                self.model_accuracy.append(self._scores_to_accuracy(res, X_samp, y_samp))
                self.models.append(res)
                i += 1
            except Exception as e:
                errors += 1 # to avoid infinite loop for misspecified matrix
                print('Error: {}'.format(e))

        print("\nAverage Accuracy:", "{}%".
              format(round(np.mean(self.model_accuracy) * 100, 2)))
    else:
        # ignore any imbalance and fit one model
        print('Fitting 1 (Unbalanced) Model...')
        glm = GLM(self.y, self.X, family=sm.families.Binomial())
        res = glm.fit()
        self.model_accuracy.append(self._scores_to_accuracy(res, self.X, self.y))
        self.models.append(res)
        print("\nAccuracy", round(np.mean(self.model_accuracy[0]) * 100, 2))'

Я бы хотел позвонить res Чтобы я мог получить доступ к print(res.summary) или любому другому разделу пакета statsmodel.

...