【发布时间】:2019-04-17 20:07:59
【问题描述】:
我正在尝试将一组特征拟合到 statsmodel 的 OLS 线性回归模型。
我一次添加一些功能。使用前两个功能,它可以正常工作。但是当我不断添加新功能时,它给了我一个错误。
Traceback (most recent call last):
File "read_xml.py", line 337, in <module>
model = sm.OLS(Y, X).fit()
...
File "D:\pythonprojects\testproj\test_env\lib\site-packages\statsmodels\base\data.py", line 132, in _handle_constant
if not np.isfinite(ptp_).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 = X.astype(float)
然后弹出一个不同的错误。
Traceback (most recent call last):
File "read_xml.py", line 339, in <module>
print(model.summary())
...
File "D:\pythonprojects\testproj\test_env\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1824, in sf
place(output, (1-cond0)+np.isnan(x), self.badvalue)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
我的代码如下所示。
new_df0 = pd.concat([df_lex[0], summary_df[0]], axis = 0, join = 'inner')
new_df1 = pd.concat([df_lex[1], summary_df[1]], axis = 0, join = 'inner')
data = pd.concat([new_df0, new_df1], axis = 1)
print(data.shape)
X = data.values[0:6,:]
Y = data.values[6,:]
Y = Y.reshape(1,88)
X = X.T
Y = Y.T
X = X.astype(float)
model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
print(model.summary())
model = sm.OLS(Y,X).fit() 中触发的第一个错误
model.summary()中触发的第二个错误
但是对于其他一些功能,没有错误。
new_df0 = pd.concat([df_len[0], summary_df[0]], axis = 0, join = 'inner')
new_df1 = pd.concat([df_len[1], summary_df[1]], axis = 0, join = 'inner')
data = pd.concat([new_df0, new_df1], axis = 1)
print(data.shape)
X = data.values[0:2,:]
Y = data.values[2,:]
Y = Y.reshape(1,88)
X = X.T
Y = Y.T
X = X.astype(float)
print(X.shape)
print(Y.shape)
model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
print(model.summary())
看起来当我只有两个功能时它可以工作。但是当添加不同的 6 个功能时,它会给出错误。我主要关心的是理解错误。因为我已经阅读了与 python 中的绘图相关的类似问题。但这是在内置函数中触发的,而不是在我的代码中。非常感谢任何调试建议。
【问题讨论】:
-
一个想法...
data.dtypes显示了什么?看起来像对象不是数组的东西正在传递给np.isinstance和/或np.isnan函数。 -
当我让我的一个朋友查看我的代码时,我找到了一个解决方案。我只考虑 X 作为输入,完全忘记了 Y。 Y 只是 1/0。然后他建议将 Y 也设置为
astype(float)并且它的模型再次工作。
标签: python python-3.x statsmodels sklearn-pandas