如何使用子序列字符串内核(ssk)[lodhi 2002]在python中训练支持向量机(support vector machine)?

最佳答案

这是对gcedo's answer的更新,以使用当前版本的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)

07-26 00:45