使用 Python 的字符串子序列内核和 SVM

2023-12-27

如何使用子序列内核 (SSK) [Lodhi 2002] 在 Python 中训练 SVM(支持向量机)?


我找到了使用幕府将军库的解决方案。您必须从提交安装它0891f5a38bcb https://code.google.com/p/shogun-toolbox/source/detail?r=0891f5a38bcb927d3c2349f1d3a006b975893d11因为后来的修订会错误地删除所需的类。

这是一个工作示例:

from shogun.Features import *
from shogun.Kernel import *
from shogun.Classifier import *
from shogun.Evaluation import *
from modshogun import StringCharFeatures, RAWBYTE
from shogun.Kernel import SSKStringKernel


strings = ['cat', 'doom', 'car', 'boom']
test = ['bat', 'soon']

train_labels  = numpy.array([1, -1, 1, -1])
test_labels = numpy.array([1, -1])

features = StringCharFeatures(strings, RAWBYTE)
test_features = StringCharFeatures(test, RAWBYTE)

# 1 is n and 0.5 is lambda as described in Lodhi 2002
sk = SSKStringKernel(features, features, 1, 0.5)

# Train the Support Vector Machine
labels = BinaryLabels(train_labels)
C = 1.0
svm = LibSVM(C, sk, labels)
svm.train()

# Prediction
predicted_labels = svm.apply(test_features).get_labels()
print predicted_labels
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 的字符串子序列内核和 SVM 的相关文章

随机推荐