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

我开始学习机器学习,并且正在尝试实现线性回归的向后消元法。这里是我的代码:

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

回答:

问题在于你的代码中x的类型是dtype=object而不是dtype=float,也就是说x不是数值变量,因此不能作为回归器使用。一旦x被转换为float类型,你的代码就能正常运行了。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注