python中train_test_split函数怎么使用

1916
2024/2/7 15:25:25
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

train_test_split函数是用来将数据集划分为训练集和测试集的。在Python中,train_test_split函数可以通过sklearn库中的model_selection模块来使用。下面是一个简单的示例:

from sklearn.model_selection import train_test_split
import numpy as np

# 生成一些示例数据
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 1, 0, 1])

# 将数据集划分为训练集和测试集,test_size指定测试集比例,random_state设置随机种子
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 打印划分后的训练集和测试集
print("训练集X:", X_train)
print("测试集X:", X_test)
print("训练集y:", y_train)
print("测试集y:", y_test)

在这个示例中,我们生成了一个包含4个样本的数据集X和对应的标签y。然后使用train_test_split函数将数据集划分为训练集和测试集,其中test_size参数指定了测试集的比例(这里是0.2,即20%),random_state参数设置了随机种子以确保划分结果的一致性。最后打印出划分后的训练集和测试集。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么求列表的平均值