将 sklearn.svm 个 SVC 分类器转换为 Keras 实现

Convert sklearn.svm SVC classifier to Keras implementation

我正在尝试将一些旧代码从使用 sklearn 转换为 Keras 实现。由于保持相同的操作方式至关重要,因此我想了解我是否正确操作。

我已经转换了大部分代码,但是我在 sklearn.svm SVC 分类器转换方面遇到了问题。这是现在的样子:

from sklearn.svm import SVC
model = SVC(kernel='linear', probability=True)
model.fit(X, Y_labels)

超级简单,对吧。但是,我在 Keras 中找不到 SVC 分类器的类比。所以,我试过的是:

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='softmax'))
model.compile(loss='squared_hinge',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(X, Y_labels)

但是,我认为无论如何都不正确。你能帮我从 Keras 的 sklearn 中找到 SVC 分类器的替代品吗?

谢谢。

如果你正在做一个分类器,你需要 squared_hingeregularizer,才能得到完整的 SVM 损失函数,如图所示 here. 所以你还需要打破你的最后一层在执行激活之前添加正则化参数,我在这里添加了代码。

这些更改应该会给你输出

from keras.regularizers import l2
from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(64, activation='relu'))
model.add(Dense(1), kernel_regularizer=l2(0.01))
model.add(activation('softmax'))
model.compile(loss='squared_hinge',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(X, Y_labels)

此外 hinge 在 keras 中实现了二进制分类,因此如果您正在处理二进制分类模型,请使用下面的代码。

from keras.regularizers import l2
from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(64, activation='relu'))
model.add(Dense(1), kernel_regularizer=l2(0.01))
model.add(activation('linear'))
model.compile(loss='hinge',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(X, Y_labels)

如果您无法理解本文或对代码有疑问,请随时发表评论。 前段时间我遇到了同样的问题,这个 GitHub 线程帮助我理解,也许也经历过它,这里的一些想法直接来自这里 https://github.com/keras-team/keras/issues/2588

如果您使用的是 Keras 2.0,那么您需要更改 anand v sing 的回答的以下几行。

W_regularizer -> kernel_regularizer

Github link

model.add(Dense(nb_classes, kernel_regularizer=regularizers.l2(0.0001)))
model.add(Activation('linear'))
model.compile(loss='squared_hinge',
                      optimizer='adadelta', metrics=['accuracy'])

或者您可以使用关注

top_model = bottom_model.output
  top_model = Flatten()(top_model)
  top_model = Dropout(0.5)(top_model)
  top_model = Dense(64, activation='relu')(top_model)
  top_model = Dense(2, kernel_regularizer=l2(0.0001))(top_model)
  top_model = Activation('linear')(top_model)
  
  model = Model(bottom_model.input, top_model)
  model.compile(loss='squared_hinge',
                      optimizer='adadelta', metrics=['accuracy'])