-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.py
71 lines (57 loc) · 1.71 KB
/
kernel.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
69
70
71
from ctypes import *
from ctypes.util import find_library
from os import path
import numpy as np
from scipy.sparse import csr_matrix
import sys
# load library first
try:
dirname = path.dirname(path.abspath(__file__))
if sys.platform == 'win32':
print 'not applicable'
else:
libknn = CDLL(path.join(dirname, 'libpsdkernel.so'))
except:
if find_library('psdkernel'):
libknn = CDLL(find_library('psdkernel'))
else:
raise Exception('LIBpsdkernel not found!')
def genFields(names, types):
return list(zip(names, types))
def fillprototype(f, restype, argtypes):
f.restype = restype
f.argtypes = argtypes
class data(Structure):
_names = ['m', 'd', 'nnz', 'val', 'rowptr', 'colind']
_types = [c_ulong, c_int, c_ulong, POINTER(c_double), POINTER(c_ulong), POINTER(c_int)]
_fields_ = genFields(_names, _types)
def clone_data(self, X):
self.m = X.shape[0]
self.d = X.shape[1]
self.nnz = X.nnz
self.val = (c_double * self.nnz)()
for i, v in enumerate(X.data):
self.val[i] = v
self.colind = (c_int * self.nnz)()
for i, v in enumerate(X.indices):
self.colind[i] = v
self.rowptr = (c_ulong * (self.m+1))()
for i, v in enumerate(X.indptr):
self.rowptr[i] = v
def compute_PSDkernel(X, Z, kern='rbf', sigma=1.0, verbose=False):
if not isinstance(X, csr_matrix):
X = csr_matrix(X)
if not isinstance(Z, csr_matrix):
Z = csr_matrix(Z)
x = data()
x.clone_data(X)
z = data()
z.clone_data(Z)
if kern == 'rbf':
libknn.classify_knn_cosine(mydata, mytest, prediction, knn, verbose)
elif kern == 'lin':
libknn.classify_knn_l2(mydata, mytest, prediction, knn, verbose)
else:
raise Error('unknown kernel type')
K = np.array(np.fromiter(k, dtype=float, count=Z.shape[0]))
return prediction