簡體   English   中英

摘要中的錯誤引發 NotImplementedError

[英]error in summary raise NotImplementedError

這是我的 Ridge 回歸代碼,當嘗試 output 摘要時,它給出了一個錯誤

import pandas as pd
import numpy as np
from scipy import stats # для расчетов
import matplotlib.pyplot as plt
import statsmodels . api as sm # для построения модели
data = pd.read_csv("C:/Users/katya/Desktop/regressii/dan11.csv", sep =';')
y = data.values[:, 0] 
X = data.values[:, 1:]
print(X)
model = sm.OLS(y, X)
results = model.fit_regularized(method='elastic_net', alpha=1.0, L1_wt=0.0)
print(results.summary())

錯誤回溯(最近調用最后一次):文件“c:\Users\katya\Desktop\regressii\strach.py”,第 12 行,打印(results.summary())文件“C:\Users\katya\AppData\ Local\Programs\Python\Python310\lib\site-packages\statsmodels\base\model.py", line 1177, 總結 raise NotImplementedError NotImplementedError

請幫忙出出主意

免責聲明:我從未使用過這個庫。

乍一看,它確實看起來只是沒有實現(因此可能是庫中的錯誤)。

OLS.fit_regularized 的文檔: https://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLS.fit_regularized.html

這表示返回了 RegularizedResults。

源代碼似乎在這里: https://www.statsmodels.org/dev/_modules/statsmodels/base/elastic.net.html

你可以看到:

class RegularizedResults(Results):
    """
    Results for models estimated using regularization

    Parameters
    ----------
    model : Model
        The model instance used to estimate the parameters.
    params : ndarray
        The estimated (regularized) parameters.
    """
    def __init__(self, model, params):
        super(RegularizedResults, self).__init__(model, params)

    @cache_readonly
    def fittedvalues(self):
        """
        The predicted values from the model at the estimated parameters.
        """
        return self.model.predict(self.params)

對於 Results base class,代碼在這里: https://www.statsmodels.org/dev/_modules/statsmodels/base/model.html看起來像

class Results(object):
    """
    Class to contain model results

    Parameters
    ----------
    model : class instance
        the previously specified model instance
    params : ndarray
        parameter estimates from the fit model
    """
    def __init__(self, model, params, **kwd):
        self.__dict__.update(kwd)
        self.initialize(model, params, **kwd)
        self._data_attr = []
        # Variables to clear from cache
        self._data_in_cache = ['fittedvalues', 'resid', 'wresid']

    def initialize(self, model, params, **kwargs):
        """
        Initialize (possibly re-initialize) a Results instance.

        Parameters
        ----------
        model : Model
            The model instance.
        params : ndarray
            The model parameters.
        **kwargs
            Any additional keyword arguments required to initialize the model.
        """
        self.params = params
        self.model = model
        if hasattr(model, 'k_constant'):
            self.k_constant = model.k_constant


    def _transform_predict_exog(self, exog, transform=True):

        is_pandas = _is_using_pandas(exog, None)
        exog_index = None
        if is_pandas:
            if exog.ndim == 2 or self.params.size == 1:
                exog_index = exog.index
            else:
                exog_index = [exog.index.name]

        if transform and hasattr(self.model, 'formula') and (exog is not None):
            # allow both location of design_info, see #7043
            design_info = (getattr(self.model, "design_info", None) or
                           self.model.data.design_info)
            from patsy import dmatrix
            if isinstance(exog, pd.Series):
                # we are guessing whether it should be column or row
                if (hasattr(exog, 'name') and isinstance(exog.name, str) and
                        exog.name in design_info.describe()):
                    # assume we need one column
                    exog = pd.DataFrame(exog)
                else:
                    # assume we need a row
                    exog = pd.DataFrame(exog).T
            orig_exog_len = len(exog)
            is_dict = isinstance(exog, dict)
            try:
                exog = dmatrix(design_info, exog, return_type="dataframe")
            except Exception as exc:
                msg = ('predict requires that you use a DataFrame when '
                       'predicting from a model\nthat was created using the '
                       'formula api.'
                       '\n\nThe original error message returned by patsy is:\n'
                       '{0}'.format(str(str(exc))))
                raise exc.__class__(msg)
            if orig_exog_len > len(exog) and not is_dict:
                if exog_index is None:
                    warnings.warn('nan values have been dropped', ValueWarning)
                else:
                    exog = exog.reindex(exog_index)
            exog_index = exog.index

        if exog is not None:
            exog = np.asarray(exog)
            if exog.ndim == 1 and (self.model.exog.ndim == 1 or
                                   self.model.exog.shape[1] == 1):
                exog = exog[:, None]
            exog = np.atleast_2d(exog)  # needed in count model shape[1]

        return exog, exog_index

    def predict(self, exog=None, transform=True, *args, **kwargs):
        """
        Call self.model.predict with self.params as the first argument.

        Parameters
        ----------
        exog : array_like, optional
            The values for which you want to predict. see Notes below.
        transform : bool, optional
            If the model was fit via a formula, do you want to pass
            exog through the formula. Default is True. E.g., if you fit
            a model y ~ log(x1) + log(x2), and transform is True, then
            you can pass a data structure that contains x1 and x2 in
            their original form. Otherwise, you'd need to log the data
            first.
        *args
            Additional arguments to pass to the model, see the
            predict method of the model for the details.
        **kwargs
            Additional keywords arguments to pass to the model, see the
            predict method of the model for the details.

        Returns
        -------
        array_like
            See self.model.predict.

        Notes
        -----
        The types of exog that are supported depends on whether a formula
        was used in the specification of the model.

        If a formula was used, then exog is processed in the same way as
        the original data. This transformation needs to have key access to the
        same variable names, and can be a pandas DataFrame or a dict like
        object that contains numpy arrays.

        If no formula was used, then the provided exog needs to have the
        same number of columns as the original exog in the model. No
        transformation of the data is performed except converting it to
        a numpy array.

        Row indices as in pandas data frames are supported, and added to the
        returned prediction.
        """
        exog, exog_index = self._transform_predict_exog(exog,
                                                        transform=transform)

        predict_results = self.model.predict(self.params, exog, *args,
                                             **kwargs)

        if exog_index is not None and not hasattr(predict_results,
                                                  'predicted_values'):
            if predict_results.ndim == 1:
                return pd.Series(predict_results, index=exog_index)
            else:
                return pd.DataFrame(predict_results, index=exog_index)
        else:
            return predict_results


    def summary(self):
        """
        Summary

        Not implemented
        """
        raise NotImplementedError

祝你好運解決你的問題。 也許對圖書館有更多了解的人可以提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM