10倍交叉验证并获得RMSE

时间:2019-10-16 17:23:58

标签: python scikit-learn linear-regression mse k-fold

我正在尝试使用scikit learning中的KFold模块将对整个数据集执行多元线性回归与进行10倍交叉验证的RMSE进行比较。我找到了一些我试图改编的代码,但我无法使其正常工作(我怀疑它一开始就没有效果。

TIA寻求帮助!

这是我的线性回归函数

  def standRegres(xArr,yArr):
      xMat = np.mat(xArr); yMat = np.mat(yArr).T
      xTx = xMat.T*xMat
      if np.linalg.det(xTx) == 0.0:
          print("This matrix is singular, cannot do inverse")
          return
      ws = xTx.I * (xMat.T*yMat)
      return ws

  ##  I run it on my matrix ("comm_df") and my dependent var (comm_target)

  ##  Calculate RMSE (omitted some code)

  initial_regress_RMSE = np.sqrt(np.mean((yHat_array - comm_target_array)**2)

  ##  Now trying to get RMSE after training model through 10-fold cross validation

  from sklearn.model_selection import KFold
  from sklearn.linear_model import LinearRegression

  kf = KFold(n_splits=10)
  xval_err = 0
  for train, test in kf:
      linreg.fit(comm_df,comm_target)
      p = linreg.predict(comm_df)
      e = p-comm_target
      xval_err += np.sqrt(np.dot(e,e)/len(comm_df))

  rmse_10cv = xval_err/10

我收到关于kfold对象如何不可迭代的错误

2 个答案:

答案 0 :(得分:0)

此代码中需要纠正几件事。

  • 您无法迭代kf。您只能在kf.split(comm_df)

  • 上进行迭代
  • 您需要以某种方式使用KFold提供的火车测试拆分。您没有在代码中使用它们! KFold的目标是使您的回归适合火车的观测值,并根据测试观测值评估回归(即计算您案例中的RMSE)。

牢记这一点,这就是我将如何纠正您的代码(这里假设您的数据位于numpy数组中,但是您可以轻松切换到熊猫)

kf = KFold(n_splits=10)
xval_err = 0
for train, test in kf.split(comm_df):
    linreg.fit(comm_df[train],comm_target[train])
    p = linreg.predict(comm_df[test])
    e = p-comm_label[test]
    xval_err += np.sqrt(np.dot(e,e)/len(comm_target[test]))

rmse_10cv = xval_err/10

答案 1 :(得分:0)

因此,您提供的代码仍然引发错误。我放弃了上面的内容,转而采用了下面的方法:

## KFold cross-validation

from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression

## Define variables for the for loop

kf = KFold(n_splits=10)
RMSE_sum=0
RMSE_length=10
X = np.array(comm_df)
y = np.array(comm_target)

for loop_number, (train, test) in enumerate(kf.split(X)):

    ## Get Training Matrix and Vector

    training_X_array = X[train]
    training_y_array = y[train].reshape(-1, 1)

    ## Get Testing Matrix Values

    X_test_array = X[test]
    y_actual_values = y[test]

    ## Fit the Linear Regression Model

    lr_model = LinearRegression().fit(training_X_array, training_y_array)

    ## Compute the predictions for the test data

    prediction = lr_model.predict(X_test_array)      
    crime_probabilites = np.array(prediction)   

    ## Calculate the RMSE

    RMSE_cross_fold = RMSEcalc(crime_probabilites, y_actual_values)

    ## Add each RMSE_cross_fold value to the sum

    RMSE_sum=RMSE_cross_fold+RMSE_sum

## Calculate the average and print    

RMSE_cross_fold_avg=RMSE_sum/RMSE_length

print('The Mean RMSE across all folds is',RMSE_cross_fold_avg)