gpt4 book ai didi

python - 为什么具有铰链损失的 SGDClassifier 比 scikit-learn 中的 SVC 实现更快

转载 作者:行者123 更新时间:2023-11-30 09:02:34 24 4
gpt4 key购买 nike

正如我们所知,对于支持向量机,我们可以使用 SVC 以及带有铰链损失实现的 SGDClassifier。具有铰链损失的 SGDClassifier 实现比 SVC 更快吗?为什么?

scikit-learn 中 SVC 的两种实现的链接:
SVC
SGDClassifier

我在sci-kit的文档页面上读到SVC使用libsvm库的一些算法进行优化。而 SGDClassifier 使用 SGD(显然)。

最佳答案

也许最好开始尝试一些实际案例并阅读代码。让我们开始吧...

首先,如果我们阅读SGDC的文档,它说仅使用线性SVM:

Linear classifiers (SVM, logistic regression, a.o.) with SGD training

如果我们不使用通常的 SVC,而是使用 LinearSVC 会怎么样? ?

Similar to SVC with parameter kernel=’linear’, but implemented in terms of liblinear rather than libsvm, so it has more flexibility in the choice of penalties and loss functions and should scale better to large numbers of samples.

让我们为这三种算法添加一个示例:

from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
from sklearn.svm import LinearSVC
from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
X = np.random.rand(20000,2)

Y = np.random.choice(a=[False, True], size=(20000, 1))

# hinge is used as the default
svc = SVC(kernel='linear')

sgd = SGDClassifier(loss='hinge')

svcl = LinearSVC(loss='hinge')

使用 jupyter 和命令 %%time 我们得到执行时间(你可以在普通 python 中使用类似的方法,但这就是我的做法):

%%time
svc.fit(X, Y)

挂壁时间:5.61 秒

%%time
sgd.fit(X, Y)

挂墙时间:24ms

%%time
svcl.fit(X, Y)

挂墙时间:26.5ms

正如我们所见,它们之间存在巨大差异,但线性和 SGDC 的时间或多或少相同。时间总是有点不同,但这种情况总会发生,因为每个算法的执行并非来自相同的代码。

如果你对每个实现感兴趣,我建议你使用新的github阅读工具阅读github代码,这真的很好!

代码linearSVC

代码SGDC

关于python - 为什么具有铰链损失的 SGDClassifier 比 scikit-learn 中的 SVC 实现更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com