计算SSE得到错误时:' numpy.float64'对象不可迭代

时间:2017-12-18 13:57:21

标签: python numpy jupyter

我正在尝试计算平方误差和(SSE),下面提到的代码

def SSEadver(tv_train,radio_train,newsppr_train,y_train):
 y_train_predct = []
 sse_train = 0
 y_train_predct_srs = 0

# Calculating the predicted sales values on training data
 for i in range(0,len(tv_train)):
    y_train_predct.append(2.8769666223179353 + (0.04656457* tv_train.iloc[i])+ (0.17915812*(radio_train.iloc[i])) + (0.00345046*(newsppr_train.iloc[i])))

# ** Here I Convert  y_train_predct's type List to Series, but still it is showing type as list**
 y_train_predct_srs = pd.Series(y_train_predct)

# *** Due above converting not working here y_train_predct_srs.iloc[j]) is not working***   
# Now calculate SSE (sum of Squared Errors)
 for j in range (len(y_train)):
    sse_train +=  sum((y_train.iloc[j] - y_train_predct_srs.iloc[j])**2) 

return y_train_predct, y_train_predct_srs

sse_train = SSEadver(tv_train,radio_train,newsppr_train, y_train)

我运行此代码时遇到错误:

   TypeError                                 Traceback (most recent call last)
 <ipython-input-446-576e1af02461> in <module>()
 20     return y_train_predct, y_train_predct_srs
 21 
  ---> 22 sse_train = SSEadver(tv_train,radio_train,newsppr_train, y_train)
   23 

  <ipython-input-446-576e1af02461> in SSEadver(tv_train, radio_train, newsppr_train, y_train)
 14     # Now calculate SSE (sum of Squared Errors)
 15     for j in range (len(y_train)):
---> 16 sse_train +=  sum((y_train.iloc[j] -         y_train_predct_srs.iloc[j])**2)
 17 
 18 

TypeError: 'numpy.float64' object is not iterable

为什么我收到此错误?我使用的是Python 3.X.X

1 个答案:

答案 0 :(得分:0)

我看不到你的所有代码,但它看起来像是

y_train.ilocy_train_predct_srs.iloc

不是列表,但实际上是numpy.float64。您应该检查它们是肯定是列表,然后重试。