-
Notifications
You must be signed in to change notification settings - Fork 1
/
classificationDefs.py
68 lines (61 loc) · 2.18 KB
/
classificationDefs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#*****************************************************************************
# Copyright (C) 2010 Dario Malchiodi <[email protected]>
#
# This file is part of svMathematica.
# svMathematica is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
# svMathematica is distributed in the hope that it will be useful, but without any
# warranty; without even the implied warranty of merchantability or fitness
# for a particular purpose. See the GNU Lesser General Public License for
# more details.
# You should have received a copy of the GNU Lesser General Public License
# along with svMathematica; if not, see <http://www.gnu.org/licenses/>.
#
#*****************************************************************************
from cvxopt import matrix,solvers
from numpy import dot,array
def kronecker_delta(i,j):
if i==j:
return 1.0;
else:
return 0.0
def chop(data):
tolerance=10**-4
if data<tolerance:
return 0.0
else:
return data
def chop_c(data,c):
tolerance=10**-4
if data<tolerance:
return 0.0
elif c-data<tolerance:
return c
else:
return data
def svm_classification(patterns,labels,kernel):
m=len(patterns)
Q=matrix([[labels[i]*labels[j]*(kernel(patterns[i],patterns[j])) for i in range(m)] for j in range(m)])
p=matrix([-1.0 for i in range(m)])
g=[[-1.0*kronecker_delta(i,j) for i in range(m)] for j in range(m)]
G=matrix(g)
hl=[0.0 for i in range(m)]
h=matrix(hl)
A=matrix(labels,(1,m))
b=matrix(0.0)
sol=solvers.qp(Q,p,G,h,A,b)
return map(lambda x:chop(x),list(sol['x']))
def svm_classification_c(patterns,labels,c,kernel):
m=len(patterns)
Q=matrix([[labels[i]*labels[j]*(kernel(patterns[i],patterns[j])) for i in range(m)] for j in range(m)])
p=matrix([-1.0 for i in range(m)])
g=[[-1.0*kronecker_delta(i,j) for i in range(m)]+[kronecker_delta(i,j) for i in range(m)] for j in range(m)]
G=matrix(g)
hl=[0.0 for i in range(m)]+[c for i in range(m)]
h=matrix(hl)
A=matrix(labels,(1,m))
b=matrix(0.0)
sol=solvers.qp(Q,p,G,h,A,b)
return map(lambda x:chop_c(x,c),list(sol['x']))