将sklearn.svm SVC分类器转换为Keras实现 [英] Convert sklearn.svm SVC classifier to Keras implementation
问题描述
我正在尝试将一些旧代码从使用sklearn转换为Keras实现.由于维持相同的操作方式至关重要,因此我想了解自己是否正确执行操作.
I'm trying to convert some old code from using sklearn to Keras implementation. Since it is crucial to maintain the same way of operation, I want to understand if I'm doing it correctly.
我已经转换了大多数代码,但是sklearn.svm SVC分类器转换遇到了麻烦.这是现在的样子:
I've converted most of the code already, however I'm having trouble with sklearn.svm SVC classifier conversion. Here is how it looks right now:
from sklearn.svm import SVC
model = SVC(kernel='linear', probability=True)
model.fit(X, Y_labels)
超级简单,对.但是,我在Keras中找不到SVC分类器的类似物.所以,我尝试过的是这样:
Super easy, right. However, I couldn't find the analog of SVC classifier in Keras. So, what I've tried is this:
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分类器的替代方法吗?
But, I think that it is not correct by any means. Could you, please, help me find an alternative of the SVC classifier from sklearn in Keras?
谢谢.
推荐答案
如果要进行分类,则需要squared_hinge
和regularizer
,以获得完整的SVM丢失功能,如
If you are making a classifier, you need squared_hinge
and regularizer
, to get the complete SVM loss function as can be seen here. So you will also need to break your last layer to add regularization parameter before performing activation, I have added the code here.
这些更改应该为您提供输出
These changes should give you the output
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), W_regularizer=l2(0.01))
model.add(activation('softmax'))
model.compile(loss='squared_hinge',
optimizer='adadelta',
metrics=['accuracy'])
model.fit(X, Y_labels)
hinge
也是在keras中实现的,用于二进制分类,因此,如果您正在使用二进制分类模型,请使用下面的代码.
Also hinge
is implemented in keras for binary classification, so if you are working on a binary classification model, use the code below.
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), W_regularizer=l2(0.01))
model.add(activation('linear'))
model.compile(loss='hinge',
optimizer='adadelta',
metrics=['accuracy'])
model.fit(X, Y_labels)
如果您无法理解本文或对代码有疑问,请随时发表评论. 我前一段时间也遇到过同样的问题,这个GitHub线程帮助我理解了,也许也经历了,这里的一些想法直接来自这里
If you cannot understand the article or have issues with the code, feel free to comment. I had this same issue a while back, and this GitHub thread helped me understand, maybe go through it too, some of the ideas here are directly from here https://github.com/keras-team/keras/issues/2588
这篇关于将sklearn.svm SVC分类器转换为Keras实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!