本文介绍了如何在Python中有效地将数据集划分为训练集和测试集,涵盖了几种常见的方法和技巧。通过使用scikit-learn库等工具,可以帮助机器学习初学者更好地理解和实践这一重要步骤。
在sklearn的cross_validation包中有一个函数train_test_split可以将数据集按照一定比例随机划分为训练集和测试集。使用方法如下:
```python
from sklearn.cross_validation import train_test_split
# x为数据集中的特征,y为标签。
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
```
执行上述代码后得到的`x_train`, `y_train`(以及`x_test`, `y_test`)对应的索引是原始数据集中的序号。