我正在跟随 Kaggle 上的一个内核,主要是跟随 信用卡欺诈检测内核。
我已经到了需要执行 KFold 以找到逻辑回归的最佳参数这一步。
内核中展示了以下代码,但由于某些原因(可能是较旧版本的 scikit-learn),我遇到了一些错误。
def printing_Kfold_scores(x_train_data,y_train_data):
fold = KFold(len(y_train_data),5,shuffle=False)
# 不同的 C 参数
c_param_range = [0.01,0.1,1,10,100]
results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])
results_table['C_parameter'] = c_param_range
# k-fold 将提供两个列表:train_indices = indices[0], test_indices = indices[1]
j = 0
for c_param in c_param_range:
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in enumerate(fold,start=1):
# 调用带有特定 C 参数的逻辑回归模型
lr = LogisticRegression(C = c_param, penalty = 'l1')
# 使用训练数据来拟合模型。在这种情况下,我们使用 fold 的一部分来训练模型
# 使用 indices[0]。然后我们用 indices[1] 指定为“测试交叉验证”的部分进行预测
lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())
# 使用训练数据中的测试索引预测值
y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)
# 计算召回率分数并将其添加到代表当前 c_parameter 的召回率分数列表中
recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample)
recall_accs.append(recall_acc)
print('Iteration ', iteration,': recall score = ', recall_acc)
# 我们想要保存和获取的指标是这些召回率分数的平均值。
results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score ', np.mean(recall_accs))
print('')
best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
# 最后,我们可以检查在所选择的 C 参数中哪个是最佳的。
print('*********************************************************************************')
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*********************************************************************************')
return best_c
我遇到的错误如下:对于这一行:fold = KFold(len(y_train_data),5,shuffle=False)
错误:
TypeError: __init__() 收到了参数 ‘shuffle’ 的多个值
如果我从这一行中移除 shuffle=False
,我会得到以下错误:
TypeError: shuffle 必须是 True 或 False;得到 5
如果我移除 5
并保留 shuffle=False
,我会得到以下错误:
TypeError: ‘KFold’ 对象不可迭代,这来自于这一行:
for iteration, indices in enumerate(fold,start=1):
如果有人能帮助我解决这个问题,并建议如何在最新版本的 scikit-learn 中完成这项工作,将非常感激。
谢谢。
回答:
KFold 是一个分隔器,所以你必须提供一些东西来分隔。
示例代码:
X = np.array([[1,1,1,1], [2,2,2,2], [3,3,3,3], [4,4,4,4]])
y = np.array([1, 2, 3, 4])
# 现在你通过传递分割数和是否需要洗牌来创建你的 Kfolds。
fold = KFold(2,shuffle=False)
# 要遍历折叠,只需使用 split
for train_index, test_index in fold.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# 继续拟合分类器
如果你想在训练/测试循环中获取索引,只需添加 enumerate
for i, (train_index, test_index) in enumerate(fold.split(X)):
print('Iteration:', i)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
希望这能起作用