我正在尝试使用SVC分类器绘制学习曲线。数据集有点偏斜,大小约为150,1000,1000,1000和150。我在拟合估算器方面遇到了问题:
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/learning_curve.py", line 135, in learning_curve
for train, test in cv for n_train_samples in train_sizes_abs)
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 644, in __call__
self.dispatch(function, args, kwargs)
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 391, in dispatch
job = ImmediateApply(func, args, kwargs)
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 129, in __init__
self.results = func(*args, **kwargs)
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/cross_validation.py", line 1233, in _fit_and_score
estimator.fit(X_train, y_train, **fit_params)
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/svm/base.py", line 140, in fit
X = atleast2d_or_csr(X, dtype=np.float64, order='C')
File "/Users/carrier24sg/.virtualenvs/ml/lib/python2.7/site-packages/sklearn/svm/base.py", line 450, in _validate_targets
% len(cls))
ValueError: The number of classes has to be greater than one; got 1
我的代码
df = pd.read_csv('../resources/problem2_processed_validate.csv')
data, label = preprocess_text(df)
cv = StratifiedKFold(label, 10)
plt = plot_learning_curve(estimator=SVC(), title="Learning curve", X=data, y=label.values, cv
train_sizes, train_scores, test_scores = learning_curve(
estimator, data, y=label, cv=cv, train_sizes=np.linspace(.1, 1.0, 5))
即使我使用分层抽样,我仍然遇到这个错误。我相信它是因为学习曲线代码在递增数据集大小时不执行分层,并且我在一步中获得了所有类似的类标签。
我该如何解决这个问题?
答案 0 :(得分:3)
您可以使用StratifiedShuffleSplit
代替StratifiedKFold
,然后自己编写学习曲线循环,在每次迭代时创建一个新的CV对象。 StratifiedShuffleSplit
允许您指定train_size
和test_size
,您可以在创建学习曲线时增加train_size
和{{1}}。只要你让{{1}}大于类的数量,它就能够分层。
答案 1 :(得分:0)
你是对的。 learning_curve
在创建较小的数据集时不执行分层,它只占用数据的第一位。 learning_curve.py
中的第134-136行说
train[:n_train_samples] for n_train_samples in train_sizes_abs
您可以提前对数据进行随机播放,以便切片train[:n_train_samples]
可以(但不保证)包含来自所有类的数据点。如果你愿意做更多的工作,@ eickenberg提出的建议将会奏效。
PS这听起来应该包含在sklearn
中。如果您最终编写该代码,请在github上发送拉取请求