train_test_split怎么使用,你能给我个例子吗
时间: 2023-10-19 18:19:38 浏览: 26
train_test_split是sklearn库中的函数,用于将数据集划分为训练集和测试集。
以下是一个使用train_test_split函数的例子:
```python
from sklearn.model_selection import train_test_split
import numpy as np
# 生成一个包含100个样本的数据集,每个样本有3个特征
X = np.random.rand(100, 3)
# 生成一个包含100个样本的标签,0或1
y = np.random.randint(2, size=100)
# 将数据集划分为训练集和测试集,比例为7:3
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
print("训练集样本数:", len(X_train))
print("测试集样本数:", len(X_test))
```
在上面的例子中,首先我们生成了一个包含100个样本和3个特征的数据集X,以及一个包含100个样本的标签y。然后我们使用train_test_split函数将数据集划分为训练集和测试集,其中test_size参数表示测试集所占的比例。最后,我们打印出训练集和测试集的样本数。
需要注意的是,train_test_split函数的使用需要导入sklearn的model_selection模块。
相关问题
给我一个train_test_split函数随机分割的例子
好的,以下是一个使用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中。最后打印出了划分后的训练集和测试集。
sklearn的 train_test_split 如何使用
train_test_split 是 sklearn 中用于将数据集划分为训练集和测试集的方法。它可以从给定的数据集中随机选择一部分数据作为训练集,另一部分数据作为测试集。
使用方法:
1. 导入 train_test_split 方法:from sklearn.model_selection import train_test_split
2. 将数据集划分为特征与标签两部分,如:X, y
3. 调用 train_test_split 方法,传入参数:X, y, test_size, random_state等。
例子:
```
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# load iris dataset
iris = load_iris()
# split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=0)
# print the shape of the datasets
print("X_train shape:", X_train.shape)
print("y_train shape:", y_train.shape)
print("X_test shape:", X_test.shape)
print("y_test shape:", y_test.shape)
```
在这个例子中,我们使用 iris 数据集,将数据集划分为训练集(70%)和测试集(30%)。