簡體   English   中英

在Python中使用LIBSVM支持向量和系數計算超平面方程

[英]Calculate equation of hyperplane using LIBSVM support vectors and coefficients in Python

我在python中使用LIBSVM庫,並嘗試從計算的支持向量重構超平面的方程(w'x + b)。

該模型似乎可以正確訓練,但是我無法手動計算與測試數據svm_predict的輸出匹配的預測結果。

我已使用FAQ中的以下鏈接嘗試進行故障排除,但仍然無法計算出正確的結果。 https://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#f804

我的代碼如下:

from svmutil import *
import numpy as np

ytrain, xtrain = svm_read_problem('small_train.libsvm')
# Change labels from 0 to -1    
for index in range(len(ytrain)):
    if ytrain[index] == 0:
        ytrain[index] = -1.0
print ("Training set loaded...")

m = svm_train(ytrain, xtrain, '-q')
print ("Model trained...")

sv = np.asarray(m.get_SV())
sv_coef = np.asarray(m.get_sv_coef())
sv_indices = np.asarray(m.get_sv_indices())
rho = m.rho[0]

w = np.zeros(len(xtrain[0]))
b = -rho
# weight vector w = sum over i ( coefsi * xi )
for index, coef in zip(sv_indices, sv_coef):
    ai = coef[0]
    for key in xtrain[index-1]:
        w[key] = w[key] + (ai * xtrain[index-1][key])

# From LIBSVM FAQ - Doesn't seem to impact results
# if m.label[1] == -1:
#     w = np.negative(w)
#     b = -b

print(np.round(w,2))

ytest, xtest = svm_read_problem('small_test.libsvm')
# Change labels from 0 to -1  
for index in range(len(ytest)):
    if ytest[index] == 0:
        ytest[index] = -1.0

print ("Test set loaded...")
print ("Predict test set...")
p_label, p_acc, p_val = svm_predict(ytest, xtest, m)

print("p_label: ", p_label)
print("p_val: ", np.round(p_val,3))

for i in range(len(ytest)):
    wx = 0
    for key in xtest[i]:
        wx = wx + (xtest[i][key] * w[key])
    print("Manual calc: ", np.round(wx + b,3))

我的理解是,使用wx + b進行人工計算的結果應該與p_val中包含的結果相匹配。 我試過否定w和b,但仍然無法獲得與p_val中相同的結果。

我正在使用的數據集(LIBSVM格式)是:

small_train.libsvm

0 0:-0.36 1:-0.91 2:-0.99 3:-0.57 4:-1.38 5:-1.54
1 0:-1.4 1:-1.9 2:0.09 3:0.29 4:-0.3 5:-1.3
1 0:-0.43 1:1.45 2:-0.68 3:-1.58 4:0.32 5:-0.14
1 0:-0.76 1:0.3 2:-0.57 3:-0.33 4:-1.5 5:1.84

small_test.libsvm

1 0:-0.97 1:-0.69 2:-0.96 3:1.05 4:0.02 5:0.64
0 0:-0.82 1:-0.17 2:-0.36 3:-1.99 4:-1.54 5:-0.31

w的值是否計算正確? 並且p_val結果是否是要與之進行比較的正確值?

一如既往的任何幫助,我們將不勝感激。

我設法通過更改獲取值以匹配:

m = svm_train(ytrain, xtrain, '-q')

m = svm_train(ytrain, xtrain, '-q -t 0')

通過查看文檔,默認內核類型為非線性(徑向基函數)。 設置線性內核后,結果現在看起來對齊了。

以下是可用的內核類型:

-t kernel_type : set type of kernel function (default 2)
    0 -- linear: u'*v
    1 -- polynomial: (gamma*u'*v + coef0)^degree
    2 -- radial basis function: exp(-gamma*|u-v|^2)
    3 -- sigmoid: tanh(gamma*u'*v + coef0)
    4 -- precomputed kernel (kernel values in training_set_file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM