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

gce*_*edo 4 python machine-learning svm supervised-learning

如何使用Subsequence String Kernel(SSK)[Lodhi 2002]在Python中训练SVM(支持向量机)?

gce*_*edo 5

我使用幕府图书馆找到了解决方案.您必须从提交0891f5a38bcb安装它,因为以后的修订会错误地删除所需的类.

这是一个有效的例子:

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
Run Code Online (Sandbox Code Playgroud)


小智 2

这是对gcedo 答案的更新,以便与当前版本的 shogun (Shogun 6.1.3) 一起使用。

工作示例:

import numpy as np
from shogun import StringCharFeatures, RAWBYTE
from shogun import BinaryLabels
from shogun import SubsequenceStringKernel
from shogun import LibSVM

strings = ['cat', 'doom', 'car', 'boom','caboom','cartoon','cart']
test = ['bat', 'soon', 'it is your doom', 'i love your cat cart','i love loonytoons']

train_labels  = np.array([1, -1, 1, -1,-1,-1,1])
test_labels = np.array([1, -1, -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 = SubsequenceStringKernel(features, features, 3, 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)
Run Code Online (Sandbox Code Playgroud)