如何在Python中使用statsmodels.api.OLS

2024-06-25 23:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经开始学习机器学习,我正在尝试实现线性回归反向消除。 代码如下:

import statsmodels.api as sm
x = sm.add_constant(x)
x_opt = x[:,[0,1,2,3,4,5]]
regressor_OLS = sm.OLS(endog=y,exog=x_opt)

以下是错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\regression\linear_model.py", line 859, in __init__
    hasconst=hasconst, **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\regression\linear_model.py", line 702, in __init__
    weights=weights, hasconst=hasconst, **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\regression\linear_model.py", line 190, in __init__
    super(RegressionModel, self).__init__(endog, exog, **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\model.py", line 236, in __init__
    super(LikelihoodModel, self).__init__(endog, exog, **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\model.py", line 77, in __init__
    **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\model.py", line 100, in _handle_data
    data = handle_data(endog, exog, missing, hasconst, **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\data.py", line 672, in handle_data
    **kwargs)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\data.py", line 87, in __init__
    self._handle_constant(hasconst)
  File "C:\Users\ewasy\AppData\Local\Programs\Python\Python37\lib\site-packages\statsmodels\base\data.py", line 132, in _handle_constant
    if not np.isfinite(exog_max).all():
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''

以下是变量x中的两行:

array([[1.0, 0.0, 1.0, 2.016411493158463, 0.560752914530775,2.153943088571744],
       [1.0, 0.0, 0.0, 1.9558603364325031, 1.0828065830760816,1.9236003956421444]], dtype=object)

以下是变量y中的两行:

array([[2.01120333],[1.99942997]])

Tags: inpyinitlibpackageslocallinesite
2条回答

问题是在您的代码中x具有dtype=object而不是dtype=float,即x不是数字变量,因此不能用作回归器。一旦x被转换成float,您的代码就可以工作了

import statsmodels.api as sm

def model(X,y):
    X=sm.add_constant(X)
    lm_model=sm.OLS(y,X).fit()
    print(lm_model.summary())
    return X

X_train1=model(X_train_rfe,y_train)

如果您想查看基本的详细ML问题:https://github.com/ds-souvik/Machine-Learning-Basic-Intermediate-Expert./tree/master/10%20Linear%20Regression-%20BoomBikes%20Bike%20Sharing%20Service%20Business%20Case

相关问题 更多 >