我需要(根据提示)"计算3个算法中每个算法的n倍交叉验证以及n倍性能测量的平均值和标准差"。
我的原始数据框是这样的结构,其中有16种类型的重复。
target type post
1 intj "hello world shdjd"
2 entp "hello world fddf"
16 estj "hello world dsd"
4 esfp "hello world sfs"
1 intj "hello world ddfd"
我训练并计算了奈夫贝叶斯,SVM和逻辑回归的准确率,是这样的。
text_clf3 = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', LogisticRegression(multi_class = 'multinomial', solver = 'newton-cg')),
])
text_clf3.fit(result.post, result.target)
predicted3 = text_clf3.predict(docs_test)
print("Logistics Regression: ")
print(np.mean(predicted3 == result.target))
其中clf是
LogisticRegression(multi_class = 'multinomial', solver = 'newton-cg')
SGDClassifier(loss='hinge', penalty='l2',
alpha=1e-3, random_state=42,
max_iter=5, tol=None)
和
MultinomialNB(alpha = 0.0001)
我可以得到 (metrics.classification_report(result.target, predicted3)
但不知道如何实现交叉验证。
我怎么才能做到这一点?
因为我没有数据集,所以无法测试,但下面的代码希望能让大家明白主要思路。在下面的代码中。all_post
表示所有样本的组合,既 result.post
和 docs_test
照你的例子,而且 n
假设为10。
from sklearn.model_selection import cross_val_score
models = {'lr':LogisticRegression(multi_class = 'multinomial', solver = 'newton-cg'),
'nb':MultinomialNB(alpha = 0.0001),
'sgd':SGDClassifier(loss='hinge', penalty='l2',alpha=1e-3, random_state=42,
max_iter=5, tol=None)}
for name,clf in models.items():
pipe = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', clf)])
res = cross_val_score(pipe,all_post,all_target,cv=10) #res is an array of size 10
print(name,res.mean(),res.std())