给我一个train_test_split函数随机分割的例子
时间: 2023-10-16 18:30:40 浏览: 39
好的,以下是一个使用sklearn中的train_test_split函数随机分割数据的例子:
```python
from sklearn.model_selection import train_test_split
import numpy as np
# 生成样本数据
X = np.arange(20).reshape(10, 2)
y = np.arange(10)
# 使用train_test_split函数将样本数据随机划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 参数test_size指定了测试集的比例,在本例中是20%
# 参数random_state用于设置随机数生成器的种子,以确保每次运行代码得到的结果一致
print("原始数据:\n", X, y)
print("训练集:\n", X_train, y_train)
print("测试集:\n", X_test, y_test)
```
输出结果:
```
原始数据:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]
[18 19]] [0 1 2 3 4 5 6 7 8 9]
训练集:
[[ 0 1]
[ 6 7]
[16 17]
[ 8 9]
[10 11]
[ 4 5]
[18 19]
[14 15]] [0 3 8 4 5 2 9 7]
测试集:
[[12 13]
[ 2 3]] [6 1]
```
在以上代码中,np.arange(20).reshape(10, 2)生成了一个包含10个样本,每个样本有2个特征的数据集。使用train_test_split函数将这个数据集随机划分为训练集(8个样本)和测试集(2个样本),并分别保存在X_train、y_train和X_test、y_test中。最后打印出了划分后的训练集和测试集。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)