使用train_test_split时出现n_samples=0错误,训练集为空
问题排查:train_test_split触发n_samples=0错误
代码片段
print("shape of waves array",np.array(all_wave).shape) print("shape of labels array",np.array(all_label).shape) # 检查随机样本 time = np.linspace(0, len(samples - 1) / fs, len(samples - 1)) # 假设time的长度应与all_wave的第一维度一致 time = np.arange(np.array(all_wave).shape[0]) plt.plot(time,np.array(all_wave)[311:,]) plt.show() from sklearn.preprocessing import LabelEncoder le = LabelEncoder() y=le.fit_transform(all_label) classes= list(le.classes_) !pip install scikit-learn from keras.utils import to_categorical import tensorflow as tf from keras.src.utils.np_utils import to_categorical from tensorflow.python.keras.utils import np_utils from tensorflow.keras.utils import to_categorical y = tf.keras.utils.to_categorical(y, num_classes=len(labels)) all_wave = np.array(all_wave).reshape(-1,22050,1) from sklearn.model_selection import train_test_split x_train, x_valid, y_train, y_valid = train_test_split(np.array(all_wave),np.array(y), stratify=y,test_size = 0.5,random_state=777,shuffle=True)
触发的错误
1 from sklearn.model_selection import train_test_split ----> 2 x_train, x_valid, y_train, y_valid = train_test_split(np.array(all_wave),np.array(y), stratify=y,test_size = 0.5,random_state=777,shuffle=True) 1 frames /usr/local/lib/python3.10/dist-packages/sklearn/model_selection/_split.py in _validate_shuffle_split(n_samples, test_size, train_size, default_test_size) 2234 2235 if n_train == 0: -> 2236 raise ValueError( 2237 "With n_samples={}, test_size={} and train_size={}, the " 2238 "resulting train set will be empty. Adjust any of the " ValueError: With n_samples=0, test_size=0.5 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters.
排查与解决步骤
1. 核心原因
错误提示n_samples=0说明传入train_test_split的特征数组all_wave是空的,样本数量为0,导致无法划分训练集和验证集。
2. 具体排查点
- 验证初始数据加载状态:执行代码开头的打印语句,确认
all_wave和all_label的形状:
若输出的shape第一个维度为0,说明数据未正确加载,需检查数据读取逻辑(比如文件路径、读取函数参数是否正确)。print("shape of waves array",np.array(all_wave).shape) print("shape of labels array",np.array(all_label).shape) - 检查数组操作是否导致数据丢失:代码中对
all_wave的切片仅用于绘图,未修改原数组;reshape操作若原数组为空,结果仍为空,不会触发额外报错,因此核心问题还是初始数据为空。 - 确认特征与标签样本数匹配:即使
all_label非空,若all_wave为空,仍会触发该错误,需确保两者样本数一致且均大于0。
3. 修复步骤
- 修复数据加载逻辑,确保
all_wave和all_label都加载到有效数据,样本数大于0。 - 添加断言验证样本数一致性:
assert len(all_wave) == len(all_label), "特征与标签样本数不匹配" - 重新执行
train_test_split操作,此时即可正常划分数据集。
额外优化建议
- 清理冗余的
to_categorical导入,仅保留一行:from tensorflow.keras.utils import to_categorical - 修复绘图代码中的语法错误:
len(samples - 1)改为len(samples)-1,避免数组广播错误。
内容的提问来源于stack exchange,提问作者Arif Hossain
相关产品推荐
相关产品推荐

