from svmutil import *
from sys import argv, platform
from os import path, popen
from random import randrange , seed
from operator import itemgetter
from time import sleep
gnuplot_exe_list = [r'"C:\Program Files\gnuplot\pgnuplot.exe"', "/usr/bin/gnuplot","/usr/local/bin/gnuplot"]
def get_pos_deci(train_y, train_x, test_y, test_x, param):
model = svm_train(train_y, train_x, param)
labels = model.get_labels()
py, evals, deci = svm_predict(test_y, test_x, model)
deci = [labels[0]*val[0] for val in deci]
return deci,model
def get_cv_deci(prob_y, prob_x, param, nr_fold):
if nr_fold == 1 or nr_fold==0:
deci,model = get_pos_deci(prob_y, prob_x, prob_y, prob_x, param)
return deci
deci, model = [], []
prob_l = len(prob_y)
for i in range(prob_l):
j = randrange(i,prob_l)
prob_x[i], prob_x[j] = prob_x[j], prob_x[i]
prob_y[i], prob_y[j] = prob_y[j], prob_y[i]
for i in range(nr_fold):
begin = i * prob_l // nr_fold
end = (i + 1) * prob_l // nr_fold
train_x = prob_x[:begin] + prob_x[end:]
train_y = prob_y[:begin] + prob_y[end:]
test_x = prob_x[begin:end]
test_y = prob_y[begin:end]
subdeci, submdel = get_pos_deci(train_y, train_x, test_y, test_x, param)
deci += subdeci
return deci
class gnuplot:
def __init__(self, term='onscreen'):
if platform == 'win32':
cmdline = gnuplot_exe
self.__dict__['screen_term'] = 'windows'
else:
cmdline = gnuplot_exe + ' -persist'
self.__dict__['screen_term'] = 'x11'
self.__dict__['iface'] = popen(cmdline,'w')
self.set_term(term)
def set_term(self, term):
if term=='onscreen':
self.writeln("set term %s" % self.screen_term)
else:
if term.find('.ps')>0:
self.writeln("set term postscript eps color 22")
elif term.find('.png')>0:
self.writeln("set term png")
else:
print("You must set term to either *.ps or *.png")
raise SystemExit
self.output = term
def writeln(self,cmdline):
self.iface.write(cmdline + '\n')
def __setattr__(self, attr, val):
if type(val) == str:
self.writeln('set %s \"%s\"' % (attr, val))
else:
print("Unsupport format:", attr, val)
raise SystemExit
def __del__(self):