ValueError:不能有拆分数 n_splits=3 大于样本数:1
Posted
技术标签:
【中文标题】ValueError:不能有拆分数 n_splits=3 大于样本数:1【英文标题】:ValueError: Cannot have number of splits n_splits=3 greater than the number of samples: 1 【发布时间】:2017-02-10 23:37:48 【问题描述】:我正在尝试使用 train_test_split 和决策树回归器进行这种训练建模:
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import cross_val_score
# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature
new_data = samples.drop('Fresh', 1)
# TODO: Split the data into training and testing sets using the given feature as the target
X_train, X_test, y_train, y_test = train_test_split(new_data, samples['Fresh'], test_size=0.25, random_state=0)
# TODO: Create a decision tree regressor and fit it to the training set
regressor = DecisionTreeRegressor(random_state=0)
regressor = regressor.fit(X_train, y_train)
# TODO: Report the score of the prediction using the testing set
score = cross_val_score(regressor, X_test, y_test, cv=3)
print score
运行时出现错误:
ValueError: Cannot have number of splits n_splits=3 greater than the number of samples: 1.
如果我将 cv 的值更改为 1,我会得到:
ValueError: k-fold cross-validation requires at least one train/test split by setting n_splits=2 or more, got n_splits=1.
数据的一些示例行如下所示:
Fresh Milk Grocery Frozen Detergents_Paper Delicatessen
0 14755 899 1382 1765 56 749
1 1838 6380 2824 1218 1216 295
2 22096 3575 7041 11422 343 2564
【问题讨论】:
new_data
中有多少行?你能输出它并检查一次吗?
【参考方案1】:
如果分割数大于样本数,您将得到第一个错误。检查下面给出的source code 的 sn-p:
if self.n_splits > n_samples:
raise ValueError(
("Cannot have number of splits n_splits=0 greater"
" than the number of samples: 1.").format(self.n_splits,
n_samples))
如果折叠数小于或等于1
,则会出现第二个错误。在您的情况下,cv = 1
。检查source code:
if n_folds <= 1:
raise ValueError(
"k-fold cross validation requires at least one"
" train / test split by setting n_folds=2 or more,"
" got n_folds=0.".format(n_folds))
有根据的猜测,X_test
中的样本数少于3
。仔细检查。
【讨论】:
以上是关于ValueError:不能有拆分数 n_splits=3 大于样本数:1的主要内容,如果未能解决你的问题,请参考以下文章
拆分文本时出现“ValueError:int() 的无效文字,基数为 10:''”
使用 for 循环拆分 CSV 数据并打印一个变量。 ValueError:需要多于 1 个值才能解压?
错误:__init__() 有一个意外的关键字参数“n_splits”