写一个代码按照小类别将数据集划分为训练集和测试集的方法,以确保训练集和测试集中每个小类别的比例相同
时间: 2024-02-03 19:03:31 浏览: 55
假设我们有一个数据集,每个样本都有一个类别标签。我们可以按照以下步骤划分训练集和测试集,并确保每个小类别的比例相同:
1. 对于每个小类别,计算样本数目,然后将其分为训练集和测试集。例如,我们可以将每个小类别的样本数的80%用于训练集,20%用于测试集。
2. 确保每个小类别的训练集和测试集的比例相同。如果某个小类别的样本数很少,可能需要将其与其他小类别合并。
下面是一个Python代码示例,它按照上述步骤将数据集划分为训练集和测试集:
```python
import numpy as np
def split_dataset(X, y, test_ratio=0.2):
"""
Split dataset into training and testing sets, ensuring that
each small category has the same ratio in both sets.
"""
# Determine the unique small categories
small_categories = np.unique(y)
# Split each small category into training and testing sets
X_train, y_train, X_test, y_test = [], [], [], []
for cat in small_categories:
# Find samples belonging to this small category
idx = np.where(y == cat)[0]
n_samples = len(idx)
# Split into training and testing sets
n_test = int(n_samples * test_ratio)
n_train = n_samples - n_test
np.random.shuffle(idx)
idx_train = idx[:n_train]
idx_test = idx[n_train:n_samples]
# Add to training and testing sets
X_train.append(X[idx_train])
y_train.append(y[idx_train])
X_test.append(X[idx_test])
y_test.append(y[idx_test])
# Concatenate training and testing sets
X_train = np.concatenate(X_train, axis=0)
y_train = np.concatenate(y_train, axis=0)
X_test = np.concatenate(X_test, axis=0)
y_test = np.concatenate(y_test, axis=0)
# Shuffle the training set
idx = np.arange(len(y_train))
np.random.shuffle(idx)
X_train = X_train[idx]
y_train = y_train[idx]
return X_train, y_train, X_test, y_test
```
该函数接受输入数据集X和标签y,以及可选的测试集比例。它首先确定数据集中的小类别,然后将每个小类别分成训练集和测试集。最后,它将训练集和测试集串联起来,并对训练集进行随机排序。
使用示例:
```python
X_train, y_train, X_test, y_test = split_dataset(X, y, test_ratio=0.2)
```
阅读全文