0

以下是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''
4

1 回答 1

0

- 只需添加这一行,因为 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()
于 2020-11-11T16:59:17.853 回答