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



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

我已经使用幕府将军图书馆找到了解决方案。您必须从提交 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

最近,字符串子序列内核(SSK)[Lodhi.等人,2002]已被添加到Shogun机器学习工具箱中,并可用于包括Python在内的所有模块化接口。你可以在这里找到一个使用 LibSVM 将此内核用于 DNA 分类问题的工作示例。

这是对gcedo的答案的更新,适用于当前版本的幕府将军(幕府将军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)

为了将来参考,当前版本的幕府将军 (3.2.0) 中的内核名称是 StringSubsequenceKernel

来源: https://code.google.com/p/shogun-toolbox/source/browse/src/shogun/kernel/string/StringSubsequenceKernel.h

最新更新