use*_*ser 7 python scikit-learn joblib
我在python中创建了以下函数:
def cross_validate(algorithms, data, labels, cv=4, n_jobs=-1):
print "Cross validation using: "
for alg, predictors in algorithms:
print alg
print
# Compute the accuracy score for all the cross validation folds.
scores = cross_val_score(alg, data, labels, cv=cv, n_jobs=n_jobs)
# Take the mean of the scores (because we have one for each fold)
print scores
print("Cross validation mean score = " + str(scores.mean()))
name = re.split('\(', str(alg))
filename = str('%0.5f' %scores.mean()) + "_" + name[0] + ".pkl"
# We might use this another time
joblib.dump(alg, filename, compress=1, cache_size=1e9)
filenameL.append(filename)
try:
move(filename, "pkl")
except:
os.remove(filename)
print
return
Run Code Online (Sandbox Code Playgroud)
我认为,为了进行交叉验证,sklearn必须适合您的功能.
但是,当我稍后尝试使用它时(f是我在上面保存的pkl文件joblib.dump(alg, filename, compress=1, cache_size=1e9)):
alg = joblib.load(f)
predictions = alg.predict_proba(train_data[predictors]).astype(float)
Run Code Online (Sandbox Code Playgroud)
我在第一行没有错误(因此它看起来像负载工作),但它告诉我NotFittedError: Estimator not fitted, call适合before exploiting the model.在下面的行.
我究竟做错了什么?我不能重复使用适合的模型来计算交叉验证吗?我在scikits中使用cross_val_score时查看了保持拟合参数但是我不理解答案,或者它不是我想要的.我想要的是用joblib保存整个模型,以便我以后可以使用它而无需重新拟合.
交叉验证必须适合您的模型,这是不正确的; 相反,k折交叉验证可以在部分数据集上适合您的模型k次.如果您想要模型本身,您实际上需要在整个数据集上再次拟合模型; 这实际上不是交叉验证过程的一部分.所以实际上呼叫并不是多余的
alg.fit(data, labels)
Run Code Online (Sandbox Code Playgroud)
在交叉验证后适合您的模型.
另一个方法是使用专用函数cross_val_score,而不是使用专用函数,您可以将其视为交叉验证网格搜索的特殊情况(在参数空间中有一个点).在这种情况下GridSearchCV,默认情况下会在整个数据集上重新设置模型(它有一个参数refit=True),并且在其API中也有方法predict和predict_proba方法.
| 归档时间: |
|
| 查看次数: |
6789 次 |
| 最近记录: |