python - 应该对原始数据还是拆分数据执行交叉验证分数?
问题描述
当我想通过交叉验证评估我的模型时,我应该对原始数据(在训练和测试中未拆分的数据)还是在训练/测试数据上执行交叉验证?
我知道训练数据用于拟合模型,测试用于评估。如果我使用交叉验证,我是否仍应将数据拆分为训练和测试?
features = df.iloc[:,4:-1]
results = df.iloc[:,-1]
x_train, x_test, y_train, y_test = train_test_split(features, results, test_size=0.3, random_state=0)
clf = LogisticRegression()
model = clf.fit(x_train, y_train)
accuracy_test = cross_val_score(clf, x_test, y_test, cv = 5)
或者我应该这样做:
features = df.iloc[:,4:-1]
results = df.iloc[:,-1]
clf = LogisticRegression()
model = clf.fit(features, results)
accuracy_test = cross_val_score(clf, features, results, cv = 5)), 2)
或者也许是不同的东西?
解决方案
你的两种方法都是错误的。
在第一个中,您将交叉验证应用于测试集,这是没有意义的
在第二个中,您首先使用整个数据拟合模型,然后执行交叉验证,这再次毫无意义。此外,该方法是多余的(该方法
clf
不使用您的拟合,该cross_val_score
方法自己进行拟合)
由于您没有进行任何超参数调整(即您似乎只对性能评估感兴趣),因此有两种方法:
- 使用单独的测试集
- 或使用交叉验证
第一种方式(测试集):
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
x_train, x_test, y_train, y_test = train_test_split(features, results, test_size=0.3, random_state=0)
clf = LogisticRegression()
model = clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
accuracy_test = accuracy_score(y_test, y_pred)
第二种方式(交叉验证):
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
from sklearn.utils import shuffle
clf = LogisticRegression()
# shuffle data first:
features_s, results_s = shuffle(features, results)
accuracy_cv = cross_val_score(clf, features_s, results_s, cv = 5, scoring='accuracy')
# fit the model afterwards with the whole data, if satisfied with the performance:
model = clf.fit(features, results)
推荐阅读
- visual-studio-code - 当我在 JSX 代码中输入 {} 时向左移动 - VSCode
- c++ - [VsCode]:有什么方法可以显示微软 VsCode 中 C/C++ 函数的调用层次结构/调用树?
- r - 如果任何列包含 NA,则删除行
- python - 如何使用 Beautiful Soup 检索标签之后的文本?
- node.js - 检查环回 v3 中是否存在 MongoDB 集合。如果不使用自定义属性创建
- javascript - React Native 找不到已声明的变量函数
- javascript - 从循环渲染本机反应
- c# - Newtonsoft.Json:当有附加属性时如何将 json 转换为 xml?
- java - java中可以为null的返回值是否可以放入kotlin中声明为非null的变量中
- python - Python 错误,与未散列的可变 Series 对象有关