AttributeError: module 'statsmodels.formula.api' has no attribute 'OLS'
Asked Answered
A

6

17

I am trying to use Ordinary Least Squares for multivariable regression. But it says that there is no attribute 'OLS' from statsmodels. formula. api library. I am following the code from a lecture on Udemy The code is as follows:

import statsmodels.formula.api as sm
X_opt = X[:,[0,1,2,3,4,5]]
#OrdinaryLeastSquares
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit(

The error is as follows:

AttributeError                            Traceback (most recent call last)
<ipython-input-19-3bdb0bc861c6> in <module>()
      2 X_opt = X[:,[0,1,2,3,4,5]]
      3 #OrdinaryLeatSquares
----> 4 regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()

AttributeError: module 'statsmodels.formula.api' has no attribute 'OLS'
Adamok answered 4/6, 2019 at 18:57 Comment(2)
you can check the version of statsmodels, is it >= 0.5.0? Something like print (statsmodels.__version__)Waterrepellent
Use import statsmodels.api as sm. The formula.api now has only the formula interface to models which are lower case like olsHupp
Z
29

Just for completeness, the code should look like this if statsmodels.version is 0.10.0:

import statsmodels.api as sm
X_opt = X[:,[0,1,2,3,4,5]]
#OrdinaryLeastSquares
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
Zhukov answered 25/7, 2019 at 23:53 Comment(0)
M
16

Use this import.

import statsmodels.api as sm
Mendymene answered 24/9, 2019 at 11:3 Comment(0)
F
14

I have tried the above mentioned methods and while

import statsmodels.api as sm

the import works for me. When I run the next piece of code

X_opt = X[:, [0, 1, 2, 3, 4, 5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()

it gives me this error.

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

If you are getting the above mentioned error, you can solve it by specifying dtype for the np.array.

Replace

X_opt = X[:, [0, 1, 2, 3, 4, 5]]

with

X_opt = np.array(X[:, [0, 1, 2, 3, 4, 5]], dtype=float)
Fabled answered 1/1, 2020 at 19:32 Comment(0)
P
3

This is the working solution that I tried today.
use this in the import

import statsmodels.api as sm

and your rest of the fix is mentioned below

X_opt = X[:, [0, 1, 2, 3, 4, 5]]
X_opt = X_opt.astype(np.float64)
regressor_OLS = sm.OLS(Y, X_opt).fit()

This should work because it did work for me.

Priapus answered 13/5, 2020 at 18:6 Comment(0)
I
2

Try this instead, worked for me:

import statsmodels.regression.linear_model as sm
Irritability answered 19/8, 2019 at 12:55 Comment(0)
H
0

As @Josef mentions in the comment, use ols() instead of OLS(), OLS() truly does not exist there.

Helmer answered 9/11, 2021 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.