简体   繁体   中英

Running GLM with StatsModels in Python

I try to replicate using my own data the example in the documentation:

>>> import numpy as np
>>> import statsmodels.api as sm
>>> data = sm.datasets.longley.load()
>>> data.exog = sm.add_constant(data.exog)
>>> ols_resid = sm.OLS(data.endog, data.exog).fit().resid
>>> res_fit = sm.OLS(ols_resid[1:], ols_resid[:-1]).fit()
>>> rho = res_fit.params
>>> from scipy.linalg import toeplitz
>>> order = toeplitz(np.arange(16))
>>> sigma = rho**order
>>> gls_model = sm.GLS(data.endog, data.exog, sigma=sigma)
>>> gls_results = gls_model.fit()
>>> print(gls_results.summary())

My data:

type(exog)
numpy.ndarray
type(endog)
numpy.ndarray
exog.shape
(58, 3)
endog.shape
(58, )
endog[0:5]
array([1.        , 1.01541323, 1.15995317, 1.08084594, 1.25125068])
exog[0:5,:]
array([[1.0, 1.0, 1.0],
       [1.0, 1.0230000000000243, 1.0465290000000498],
       [1.0, 1.085402999999738, 1.1780996724084314],
       [1.0, 1.1331607319999735, 1.2840532445467157],
       [1.0, 1.1988840544557957, 1.4373229760283672]], dtype=object)
ols_resid = sm.OLS(endog, exog).fit().resid
TypeError: No loop matching the specified signature and casting
was found for ufunc svd_n_s

I don't understand the error message. In my view, I am replicating faithfully the example in the documentation.

The design matrix, exog has dtype=object for which numeric operations are not defined.

You need to convert exog to float, eg

exog = exog.astype(np.float64)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM