python将样本集训练集和测试集
时间: 2024-02-03 09:04:35 浏览: 34
在Python中,我们可以使用sklearn库中的train_test_split()函数将样本集划分为训练集和测试集。train_test_split()函数接受多个参数,包括特征数据和目标数据。例如,如果我们有一个名为X的特征矩阵和一个名为y的目标向量,我们可以使用以下代码将其划分为训练集和测试集:
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
在这个例子中,我们将样本集(X)和目标向量(y)作为输入,test_size参数指定了测试集的大小(例如0.2表示将20%的数据用于测试),random_state参数用于设置随机种子,以确保每次划分的结果一致。
相关问题
python划分测试集和训练集的代码
以下是一个简单的 Python 代码示例,用于将数据集随机拆分为训练集和测试集:
```python
import random
def split_dataset(dataset, split_ratio):
train_size = int(len(dataset) * split_ratio)
train_set = []
test_set = list(dataset)
while len(train_set) < train_size:
index = random.randrange(len(test_set))
train_set.append(test_set.pop(index))
return [train_set, test_set]
```
其中,`dataset` 是一个列表,包含了所有的数据样本,`split_ratio` 表示训练集占整个数据集的比例。函数会将数据集随机拆分为训练集和测试集,并返回一个列表,其中第一个元素是训练集,第二个元素是测试集。可以使用以下代码将数据集拆分为训练集和测试集:
```python
dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
split_ratio = 0.7
train_set, test_set = split_dataset(dataset, split_ratio)
print(train_set)
print(test_set)
```
输出结果类似于:
```
[2, 8, 6, 10, 5, 3, 1]
[4, 7, 9]
```
这表示训练集包含了 70% 的数据样本,测试集包含了 30% 的数据样本。
python 分层测试集训练集
可以使用sklearn库中的train_test_split方法来将数据集分割成训练集和测试集。
```python
from sklearn.model_selection import train_test_split
# X是样本特征矩阵,y是样本标签向量
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
其中,test_size表示测试集所占比例,random_state表示随机种子,保证每次运行结果一致。
如果数据集有多层结构,可以按照需要进行分层抽样,例如按照标签分层、按照数据集来源分层等。可以使用StratifiedShuffleSplit方法来实现分层抽样,并指定每层所占比例。
```python
from sklearn.model_selection import StratifiedShuffleSplit
# X是样本特征矩阵,y是样本标签向量
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(X, y):
X_train = X[train_index]
y_train = y[train_index]
X_test = X[test_index]
y_test = y[test_index]
```
以上代码实现了按照样本标签进行分层抽样,保证训练集和测试集中各类样本的比例相同。