How to use statsmodels.api for fitting model using OSL

211 Views Asked by At

Below is the code from udemy course:- I tried all the solutions provided in stack overflow but nothing seems to work

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing  import OneHotEncoder

ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(), [3])], remainder = 'passthrough')
X = np.array(ct.fit_transform(X))

from sklearn.model_selection import train_test_split

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)

Y_pred = regressor.predict(X_test) 


import statsmodels.api as lm
X = np.append(arr=np.ones((50,1)).astype(int),values=X,axis=1)
X_opt = X[:,[0,1,2,3,4,5]]
regressor_OLS = lm.OLS(endog = Y, exog = X_opt).fit()
regressor_OLS.summary()

(The previous solutions that were provided in the community are not working)

I am getting an error saying:-

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-a7a61aa40d9b> in <module>()
      3 X = np.append(arr=np.ones((50,1)).astype(int), values=X, axis=1)
      4 X_opt = X[:, [0, 1, 2, 3, 4, 5]]
----> 5 regressor_OSL = sm.OLS(endog=y, exog=X_opt)

8 frames
/usr/local/lib/python3.6/dist-packages/statsmodels/base/data.py in _handle_constant(self, hasconst)
    123             check_implicit = False
    124             ptp_ = np.ptp(self.exog, axis=0)
--> 125             if not np.isfinite(ptp_).all():
    126                 raise MissingDataError('exog contains inf or nans')
    127             const_idx = np.where(ptp_ == 0)[0].squeeze()

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''
1

There are 1 best solutions below

3
On

-just add this line because the result of X_opt it will be float:

 import statsmodels.api as sm
 X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1)
 X_opt = X[:, [0, 1, 2, 3, 4, 5]]
 X_opt = np.array(X_opt, dtype=float) # <-- **this line**  
 regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() 
 regressor_OLS.summary()