加速预测

Accelerating the prediction

使用默认参数使用 5 个特征和 3000 个样本创建的 SVM 模型的预测花费了 5 个特征和 100000 个样本的意外更长的时间(超过一小时)。有没有办法加速预测?

因为特征数量比较少,我会先从降低惩罚参数开始。它控制训练数据中错误标记样本的惩罚,并且由于您的数据包含 5 个特征,我猜它不是完全线性可分的。

一般来说,此参数 (C) 允许分类器在更高准确度的情况下具有更大的余量(有关详细信息,请参阅 this

默认情况下,C=1.0。从 svm = SVC(C=0.1) 开始,看看进展如何。

这里需要考虑的几个问题:

  1. 你标准化你的输入矩阵X了吗? SVM 不是尺度不变的,因此如果算法在没有适当缩放的情况下采用大量原始输入,则算法可能很难进行分类。

  2. 参数的选择C: Higher C 允许更复杂的非平滑决策边界,并且在这种复杂性下需要更多的时间来适应。因此,将值 C 从默认值 1 降低到较低的值可以加速该过程。

  3. 也建议选择合适的值gamma。这可以通过网格搜索交叉验证来完成。

这是进行网格搜索交叉验证的代码。为了简单起见,我在这里忽略了测试集。

import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import accuracy_score, recall_score, f1_score, roc_auc_score, make_scorer

# generate some artificial data
X, y = make_classification(n_samples=3000, n_features=5, weights=[0.1, 0.9])

# make a pipeline for convenience
pipe = make_pipeline(StandardScaler(), SVC(kernel='rbf', class_weight='auto'))

# set up parameter space, we want to tune SVC params C and gamma
# the range below is 10^(-5) to 1 for C and 0.01 to 100 for gamma
param_space = dict(svc__C=np.logspace(-5,0,5), svc__gamma=np.logspace(-2, 2, 10))

# choose your customized scoring function, popular choices are f1_score, accuracy_score, recall_score, roc_auc_score
my_scorer = make_scorer(roc_auc_score, greater_is_better=True)
# construct grid search
gscv = GridSearchCV(pipe, param_space, scoring=my_scorer)
gscv.fit(X, y)
# what's the best estimator
gscv.best_params_

Out[20]: {'svc__C': 1.0, 'svc__gamma': 0.21544346900318834}

# what's the best score, in our case, roc_auc_score
gscv.best_score_

Out[22]: 0.86819366014152421

注意:SVC 仍然不是 运行 很快。计算 50 种可能的参数组合需要 40 多秒。

%time gscv.fit(X, y)
CPU times: user 42.6 s, sys: 959 ms, total: 43.6 s
Wall time: 43.6 s

一个原因可能是参数 gamma 不一样。

默认情况下sklearn.svm.SVC使用RBF内核,gamma为0.0,在这种情况下将使用1/n_features。所以 gamma 是不同的,因为特征数量不同。

在建议方面,我同意