如何使用交叉验证模型获取系数

3

如何在交叉验证模型中得到系数?进行交叉验证时,我可以获得CV模型的分数,但我该如何获得系数呢?

#Split into training and testing
x_train, x_test, y_train, y_test = train_test_split(samples, scores, test_size = 0.30, train_size = 0.70)

clf = svm.SVC(kernel='linear', C=1)
scores = cross_val_score(clf, x_train, y_train, cv=5)
scores

我想打印与每个特征相关的系数。

   #Print co-efficients of features
    for i in range(0, nFeatures):
    print samples.columns[i],":", coef[0][i]

这个版本没有交叉验证,其中提供了系数。

#Create SVM model using a linear kernel
model = svm.SVC(kernel='linear', C=C).fit(x_train, y_train)
coef = model.coef_
1个回答

5
你可能想使用 model_selection.cross_validate(使用return_estimator=True)而不是cross_val_score。它更加灵活,因此您可以访问每个折叠所使用的估计器:
from sklearn.svm import SVC
from sklearn.model_selection import cross_validate

clf = SVC(kernel='linear', C=1)
cv_results = cross_validate(clf, x_train, y_train, cv=5, return_estimator=True)

for model in cv_results['estimator']:
    print(model.coef_)

希望这能满足您的需求!(您可以通过cv_results['train_score']cv_results['test_score']访问指标)


那么,如果我打印(samples.columns[i],":", coef[0][i]),我会得到交叉验证模型中每列的平均系数吗?@fordy - sp2
1
当然可以,如果您想要这样做,只需要将每个model.coef_结果加载到ndarray或类似的数据结构中,然后在交叉验证的每一折中计算每个系数的平均值即可。 - fordy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接