使用 for 循环交叉验证模型时查看每个折叠的分数
See the score of each fold when cross validating a model using a for loop
我想查看每个拟合模型的单独得分,以可视化交叉验证的强度(我这样做是为了向我的同事展示为什么交叉验证很重要)。
我有一个包含 500 行、200 个自变量和 1 个二进制目标的 .csv 文件。我定义 skf
使用 StratifiedKFold
.
折叠数据 5 次
我的代码如下所示:
X = data.iloc[0:500, 2:202]
y = data["target"]
skf = StratifiedKFold(n_splits = 5, random_state = 0)
clf = svm.SVC(kernel = "linear")
Scores = [0] * 5
for i, j in skf.split(X, y):
X_train, y_train = X.iloc[i], y.iloc[i]
X_test, y_test = X.iloc[j], y.iloc[j]
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
如您所见,我将 5 个零的列表分配给 Scores
。我想将 5 个预测中的每一个的 clf.score(X_test, y_test)
分配给列表。但是,索引 i
和 j
不是 {1, 2, 3, 4, 5}。相反,它们是用于折叠 X
和 y
数据框的行号。
如何在此循环中将每个 k
拟合模型的测试分数分配给 Scores
?我需要一个单独的索引吗?
我知道使用 cross_val_score
确实可以完成所有这些,并为您提供 k
分数的几何平均值。但是,我想向我的同事展示 sklearn
库中的交叉验证函数背后发生了什么。
提前致谢!
如果我理解了问题,并且您不需要任何特定的分数索引:
from sklearn.model_selection import StratifiedKFold
from sklearn.svm import SVC
X = np.random.normal(size = (500, 200))
y = np.random.randint(low = 0, high=2, size=500)
skf = StratifiedKFold(n_splits = 5, random_state = 0)
clf = SVC(kernel = "linear")
Scores = []
for i, j in skf.split(X, y):
X_train, y_train = X[i], y[i]
X_test, y_test = X[j], y[j]
clf.fit(X_train, y_train)
Scores.append(clf.score(X_test, y_test))
结果是:
>>>Scores
[0.5247524752475248, 0.53, 0.5, 0.51, 0.4444444444444444]
我想查看每个拟合模型的单独得分,以可视化交叉验证的强度(我这样做是为了向我的同事展示为什么交叉验证很重要)。
我有一个包含 500 行、200 个自变量和 1 个二进制目标的 .csv 文件。我定义 skf
使用 StratifiedKFold
.
我的代码如下所示:
X = data.iloc[0:500, 2:202]
y = data["target"]
skf = StratifiedKFold(n_splits = 5, random_state = 0)
clf = svm.SVC(kernel = "linear")
Scores = [0] * 5
for i, j in skf.split(X, y):
X_train, y_train = X.iloc[i], y.iloc[i]
X_test, y_test = X.iloc[j], y.iloc[j]
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
如您所见,我将 5 个零的列表分配给 Scores
。我想将 5 个预测中的每一个的 clf.score(X_test, y_test)
分配给列表。但是,索引 i
和 j
不是 {1, 2, 3, 4, 5}。相反,它们是用于折叠 X
和 y
数据框的行号。
如何在此循环中将每个 k
拟合模型的测试分数分配给 Scores
?我需要一个单独的索引吗?
我知道使用 cross_val_score
确实可以完成所有这些,并为您提供 k
分数的几何平均值。但是,我想向我的同事展示 sklearn
库中的交叉验证函数背后发生了什么。
提前致谢!
如果我理解了问题,并且您不需要任何特定的分数索引:
from sklearn.model_selection import StratifiedKFold
from sklearn.svm import SVC
X = np.random.normal(size = (500, 200))
y = np.random.randint(low = 0, high=2, size=500)
skf = StratifiedKFold(n_splits = 5, random_state = 0)
clf = SVC(kernel = "linear")
Scores = []
for i, j in skf.split(X, y):
X_train, y_train = X[i], y[i]
X_test, y_test = X[j], y[j]
clf.fit(X_train, y_train)
Scores.append(clf.score(X_test, y_test))
结果是:
>>>Scores
[0.5247524752475248, 0.53, 0.5, 0.51, 0.4444444444444444]