【问题标题】:How to use statsmodels.api for fitting model using OSL如何使用 statsmodels.api 使用 OSL 拟合模型
【发布时间】:2020-07-29 23:31:19
【问题描述】:

以下是 udemy 课程的代码:- 我尝试了堆栈溢出中提供的所有解决方案,但似乎没有任何效果

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()

(以前在社区提供的解决方案都不起作用)

我收到一条错误消息:-

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

【问题讨论】:

    标签: statsmodels olsmultiplelinearregression


    【解决方案1】:

    -只需添加这一行,因为 X_opt 的结果将是浮动的:

     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()
    

    【讨论】:

    • 为了帮助问题的作者和其他人,最好能解释一下为什么你的行有帮助。
    • 因为结果不能是整数,所以必须转换为浮点数才能显示准确的数字。
    • 谢谢!如果您编辑答案并将解释复制到答案中会更好。
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2015-12-01
    • 2021-07-29
    • 1970-01-01
    • 2017-11-27
    • 2018-02-18
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多