为了改进支持向量机的结果,我必须使用网格搜索来搜索更好的参数和交叉验证.我不确定如何在scikit-learn中将它们结合起来.网格搜索搜索最佳参数(http://scikit-learn.org/stable/modules/grid_search.html)和交叉验证避免过度拟合(http://scikit-learn.org/dev/modules/cross_validation.html)
#GRID SEARCH
from sklearn import grid_search
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svr = svm.SVC()
clf = grid_search.GridSearchCV(svr, parameters)
#print(clf.fit(X, Y))
#CROSS VALIDATION
from sklearn import cross_validation
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, Y, test_size=0.4, random_state=0)
clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)
print("crossvalidation")
print(clf.score(X_test, y_test))
clf = svm.SVC(kernel='linear', C=1)
scores = cross_validation.cross_val_score(clf, X, Y, cv=3)
print(scores )
Run Code Online (Sandbox Code Playgroud)
结果:
GridSearchCV(cv=None,
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,
kernel=rbf, probability=False, shrinking=True, tol=0.001, verbose=False),
estimator__C=1.0, estimator__cache_size=200,
estimator__class_weight=None, estimator__coef0=0.0,
estimator__degree=3, estimator__gamma=0.0, …Run Code Online (Sandbox Code Playgroud) 我对cross_val_score评分指标'roc_auc'和我可以直接导入和调用的roc_auc_score之间的区别感到困惑.
文档(http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter)表明指定scoring ='roc_auc'将使用sklearn.metrics.roc_auc_score.但是,当我使用scoring ='roc_auc'实现GridSearchCV或cross_val_score时,我会收到非常不同的数字,当我直接调用roc_auc_score时.
这是我的代码,以帮助演示我所看到的:
# score the model using cross_val_score
rf = RandomForestClassifier(n_estimators=150,
min_samples_leaf=4,
min_samples_split=3,
n_jobs=-1)
scores = cross_val_score(rf, X, y, cv=3, scoring='roc_auc')
print scores
array([ 0.9649023 , 0.96242235, 0.9503313 ])
# do a train_test_split, fit the model, and score with roc_auc_score
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
rf.fit(X_train, y_train)
print roc_auc_score(y_test, rf.predict(X_test))
0.84634039111363313 # quite a bit different than the scores above!
Run Code Online (Sandbox Code Playgroud)
我觉得我在这里错过了一些非常简单的事情 - 很可能是我如何实施/解释其中一个评分指标的错误.
任何人都可以解释两个得分指标之间差异的原因吗?
python machine-learning random-forest scikit-learn cross-validation
我在理解Spark的交叉验证方面遇到了一些麻烦.我见过的任何一个例子都用它来进行参数调整,但我认为它只会进行常规的K折交叉验证吗?
我想要做的是执行k折交叉验证,其中k = 5.我想获得每个结果的准确性,然后获得平均准确度.在scikit中学习这是怎么做的,分数会给你每个折叠的结果,然后你可以使用scores.mean()
scores = cross_val_score(classifier, y, x, cv=5, scoring='accuracy')
Run Code Online (Sandbox Code Playgroud)
这就是我在Spark中的做法,paramGridBuilder是空的,因为我不想输入任何参数.
val paramGrid = new ParamGridBuilder().build()
val evaluator = new MulticlassClassificationEvaluator()
evaluator.setLabelCol("label")
evaluator.setPredictionCol("prediction")
evaluator.setMetricName("precision")
val crossval = new CrossValidator()
crossval.setEstimator(classifier)
crossval.setEvaluator(evaluator)
crossval.setEstimatorParamMaps(paramGrid)
crossval.setNumFolds(5)
val modelCV = crossval.fit(df4)
val chk = modelCV.avgMetrics
Run Code Online (Sandbox Code Playgroud)
这和scikit学习实现的做法是一样的吗?为什么这些示例在进行交叉验证时会使用培训/测试数据?
classification machine-learning cross-validation apache-spark-mllib
我想使用来自插入符号模型的折叠预测来训练包含一些原始预测变量的第二阶段模型.我可以收集如下的折叠预测:
#Load Data
set.seed(1)
library(caret)
library(mlbench)
data(BostonHousing)
#Build Model (see ?train)
rpartFit <- train(medv ~ . + rm:lstat, data = BostonHousing, method="rpart",
trControl=trainControl(method='cv', number=folds,
savePredictions=TRUE))
#Collect out-of-fold predictions
out_of_fold <- rpartFit$pred
bestCP <- rpartFit$bestTune[,'.cp']
out_of_fold <- out_of_fold[out_of_fold$.cp==bestCP,]
Run Code Online (Sandbox Code Playgroud)
这很好,但它们的顺序错误:
> all.equal(out_of_fold$obs, BostonHousing$medv)
[1] "Mean relative difference: 0.4521906"
Run Code Online (Sandbox Code Playgroud)
我知道该train对象返回一个列表,其中列出了用于训练每个折叠的索引:
> str(rpartFit$control$index)
List of 10
$ Fold01: int [1:457] 1 2 3 4 5 6 7 8 9 10 ...
$ Fold02: int [1:454] 2 3 4 8 10 11 12 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用可用的数据为几种分类方法/ hiper参数制作k倍CV
该集由208行组成,每行有60个属性.我正在使用read.table函数将其读入data.frame.
下一步是将我的数据分成k个折叠,假设k = 5.我的第一次尝试是使用
test < - createFolds(t,k = 5)
我有两个问题.第一个是折叠的长度彼此不相邻:
Run Code Online (Sandbox Code Playgroud)Length Class ModeFold1 29 -none-数字
折叠2 14-无 - 数字
折叠3 7-无 - 数字
折叠4 5 - 无 - 数字
折叠5 5 - 无 - 数字
另一个是,这显然是根据属性索引分割我的数据,但我想分割数据本身.我认为通过转置我的data.frame,使用:
test < - t(myDataNumericValues)
但是当我调用createFolds函数时,它给了我这样的东西:
Run Code Online (Sandbox Code Playgroud)Length Class ModeFold1 2496 -none-数字
折叠2 2496 -none-数字
折叠3 2495
-none- 数字折叠4 2496
-none- 数字折叠5 2497 -none-数字
长度问题已经解决,但它仍然没有相应地分割我的208数据.
关于我能做什么的任何想法?你认为插入包不是最合适的吗?
提前致谢
类似于自定义交叉验证split sklearn我想为GridSearchCV定义自己的拆分,我需要自定义内置的交叉验证迭代器.
我想将自己的一组列车测试索引传递给GridSearch,而不是允许迭代器为我确定它们.我浏览了sklearn文档页面上的可用cv迭代器但找不到它.
例如,我想实现类似这样的数据有9个样本2折cv我创建了自己的一套训练测试索引
>>> train_indices = [[1,3,5,7,9],[2,4,6,8]]
>>> test_indices = [[2,4,6,8],[1,3,5,7,9]]
1st fold^ 2nd fold^
>>> custom_cv = sklearn.cross_validation.customcv(train_indices,test_indices)
>>> clf = GridSearchCV(X,y,params,cv=custom_cv)
Run Code Online (Sandbox Code Playgroud)
什么可以像customcv一样工作?
我已经训练了一个模型scikit-learn使用Cross-Validation和Naive Bayes分类器中.如何坚持使用此模型以便以后针对新实例运行?
这就是我所拥有的,我能得到的 CV分数,但我不知道如何访问训练有素的模型
gnb = GaussianNB()
scores = cross_validation.cross_val_score(gnb, data_numpy[0],data_numpy[1], cv=10)
Run Code Online (Sandbox Code Playgroud) 我正在看这个教程:https://www.dataquest.io/mission/74/getting-started-with-kaggle
我得到第9部分,做出预测.在那里,在一个名为titanic的数据框中有一些数据,然后使用以下方式将其分成折叠:
# Generate cross validation folds for the titanic dataset. It return the row indices corresponding to train and test.
# We set random_state to ensure we get the same splits every time we run this.
kf = KFold(titanic.shape[0], n_folds=3, random_state=1)
Run Code Online (Sandbox Code Playgroud)
我不确定它究竟在做什么以及kf是什么样的对象.我试过阅读文档,但没有多大帮助.此外,有三个折叠(n_folds = 3),为什么以后只能访问火车和测试(我怎么知道它们被称为火车和测试)?
for train, test in kf:
Run Code Online (Sandbox Code Playgroud) 有什么区别:StratifiedKFold,StratifiedShuffleSplit,StratifiedKFold + Shuffle?我什么时候应该使用每一个?当我获得更好的准确度分数?为什么我没有得到类似的结果?我已经把我的代码和结果.我正在使用朴素贝叶斯和10x10交叉验证.
#######SKF FOR LOOP########
from sklearn.cross_validation import StratifiedKFold
for i in range(10):
skf = StratifiedKFold(y, n_folds=10, shuffle=True)
scoresSKF2 = cross_validation.cross_val_score(clf, x, y , cv=skf)
print(scoresSKF2)
print("Accuracy SKF_NB: %0.2f (*/- %0.2f)" % (scoresSKF2.mean(), scoresSKF2.std()* 2))
print("")
[ 0.1750503 0.16834532 0.16417051 0.18205424 0.1625758 0.1750939
0.15495808 0.1712963 0.17096494 0.16918166]
Accuracy SKF_NB: 0.17 (*/- 0.01)
[ 0.16297787 0.17956835 0.17309908 0.17686093 0.17239388 0.16093615
0.16970223 0.16956019 0.15473776 0.17208358]
Accuracy SKF_NB: 0.17 (*/- 0.01)
[ 0.17102616 0.16719424 0.1733871 0.16560877 0.166041 0.16122508
0.16767852 0.17042824 0.18719212 0.1677307 …Run Code Online (Sandbox Code Playgroud) 我正在Keras中实现一个多层感知器并使用scikit-learn来执行交叉验证.为此,我受到了Keras交叉验证问题中的代码的启发
from sklearn.cross_validation import StratifiedKFold
def load_data():
# load your data using this function
def create model():
# create your model using this function
def train_and_evaluate__model(model, data[train], labels[train], data[test], labels[test)):
# fit and evaluate here.
if __name__ == "__main__":
X, Y = load_model()
kFold = StratifiedKFold(n_splits=10)
for train, test in kFold.split(X, Y):
model = None
model = create_model()
train_evaluate(model, X[train], Y[train], X[test], Y[test])
Run Code Online (Sandbox Code Playgroud)
在我对神经网络的研究中,我了解到神经网络的知识表示是在突触权重和网络跟踪过程中,更新的权重,从而降低网络错误率并改善其性能.(就我而言,我正在使用监督学习)
为了更好地训练和评估神经网络性能,一种常用的方法是交叉验证,它返回数据集的分区,用于训练和评估模型.
我怀疑是......
在此代码段中:
for train, test in kFold.split(X, Y):
model = None
model = …Run Code Online (Sandbox Code Playgroud) machine-learning neural-network scikit-learn cross-validation keras
cross-validation ×10
scikit-learn ×6
python ×5
r ×2
r-caret ×2
kaggle ×1
keras ×1
pickle ×1
python-3.x ×1
svm ×1
validation ×1