-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathvector.py
More file actions
2008 lines (1769 loc) · 82.8 KB
/
vector.py
File metadata and controls
2008 lines (1769 loc) · 82.8 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2006, National ICT Australia
# All rights reserved.
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the 'License'); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an 'AS IS' basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# Authors: Le Song (lesong@it.usyd.edu.au) and Alex Smola
# (alex.smola@nicta.com.au)
# Created: (20/10/2006)
# Last Updated: (dd/mm/yyyy)
#
##\package elefant.kernels.vector
# This module contains kernel classes for vectorial data.
#
# The CVectorKernel class provides common interface for all kernel classes
# for vectorial data. This kernel should never be instantiated as well.
# All other kernel classes are derived from the CVectorKernel class. The
# hierarchy for the the classes in this package is as follows:
# --CKernel (abstract)
# ------CVectorKernel (abstract)
# ----------CDeltaKernel
# ----------CLinearKernel
# ----------CDotProductKernel (abstract)
# --------------CPolynomialKernel
# --------------CTanhKernel
# --------------CExpKernel
# ----------CRBFKernel (abstract)
# --------------CGaussKernel
# --------------CLaplaceKernel
# --------------CInvDisKernel
# --------------CInvSqDisKernel
# --------------CBesselKernel
#
__version__ = '$Revision: $'
# $Source$
import numpy
import numpy.random as random
from generic import CKernel
from my_exceptions import CElefantConstraintException
## Generic kernel class for vectorial data
#
# This kernel provide common interface for all kernels operating on
# vectorial data. This interface includes the following key kernel
# manipulations (functions):
# --Dot(x1, x2): $K(x1, x2)$
# --Expand(x1, x2, alpha): $sum_r K(x1_i,x2_r) \times alpha2_r$
# --Tensor(x1, y1, x2, y2): $K(x1_i,x2_j) \times (y1_i \times y1_j)$
# --TensorExpand(x1, y1, x2, y2, alpha2):
# $sum_r K(x1_i,x2_r) \times (y1_i \times y1_r) \times alpha2_r$
# --Remember(x): Remember data x
# --Forget(x): Remove remembered data x
# To design a specific kernel, simply overload these methods. The generic
# kernel itself should never be instantiated, although methods
# Remember and Forget are implemented in this class. The Remember method
# stores the inner product of an input vector.
#
class CVectorKernel(CKernel):
def __init__( self, blocksize = 128 ):
CKernel.__init__( self, blocksize )
self._name = 'Vector kernel'
## @var _cacheKernel
# Cache that store the base part for the kernel matrix.
# This cache facilates the incremental and decremental
# computational of the kernel matrix.
#
self._cacheKernel = {}
## @var _typicalParam
# Typical parameter for the kernel. Many kernels do not
# have parameters, such linear kernel. In this case, set
# zero as the typical parameter. This variable will be
# usefull when optimizing the kernel matrix with respect
# to the kernel matrix.
#
self._typicalParam = numpy.array([0])
## Compute the kernel between two data points x1 and x2.
# It returns a scale value of dot product between x1 and x2.
# @param x1 [read] The first data point.
# @param x2 [read] The second data point.
#
def K(self, x1, x2):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Compute the kernel between the data points in x1 and those in x2.
# It returns a matrix with entry $(ij)$ equal to $K(x1_i, x1_j)$.
# If index1/index2 is
# specified, only those data points in x1/x2 with indices corresponding
# to index1/index2 are used to compute the kernel matrix. Furthermore,
# if output is specified, the provided buffer is used explicitly to
# store the kernel matrix.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Dot(self, x1, x2, index1=None, index2=None, output=None):
raise NotImplementedError, \
'CVectorKernel.Dot in abstract class is not implemented'
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix by alpha2.
# It returns a matrix with entry $(ij)$ equal to
# $sum_r K(x1_i,x2_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param alpha2 [read] The set of coefficients.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Expand(self, x1, x2, alpha2, index1=None, index2=None):
raise NotImplementedError, \
'CVectorKernel.Expand in abstract class is not implemented'
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2. It returns a matrix
# with entry $(ij)$ equal to $K(x1_i,x2_j) \times (y1_i \times y1_j)$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Tensor(self, x1, y1, x2, y2, index1=None, index2=None):
raise NotImplementedError, \
'CVectorKernel.Tensor in abstract class is not implemented'
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2, and final multiply
# the resulting matrix by alpha2. It returns a matrix with entry $(ij)$
# equal to $sum_r K(x1_i,x2_r) \times (y1_i \times y1_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def TensorExpand(self, x1, y1, x2, y2, alpha2, index1=None, index2=None, \
output=None):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Remember x by computing the inner product of the data points contained
# in x, storing them in the cache and indexing them by the id of
# x. If x have already been remembered,
# the old stored information is simply overwritten.
# @param x [read] The data to be remembered.
#
def Remember(self, x):
# default behavior
assert x is not None, 'x is None'
assert len(x.shape) == 2, 'x is not a matrix'
self._cacheData[id(x)] = (x**2).sum(axis=1)
## Remove the remembered data x. If x is not given, then all remembered
# data in the cache is removed. If x has never been remembered, then
# this function does nothing and return False instead.
# @param x [read] The data to be removed.
#
def Forget(self, x=None):
# default behavior
if x is not None:
assert len(x.shape) == 2, 'Argument 1 is has wrong shape'
if self._cacheData.has_key(id(x)) is False:
return False
else:
del self._cacheData[id(x)]
else:
self._cacheData.clear()
return True
## Method that operates on the base part x of a kernel.
# The derived classes overload this method to generate new
# kernels.
# @param x Base part of the kernel.
#
def Kappa(self, x):
# default behavior
return x
## Gradient of the kernel with respect to the kernel
# parameter evaluated in the base part x of a kernel.
# The derived classes overload this method to generate new
# gradients of the kernels.
# @param x Base part of the kernel.
#
def KappaGrad(self, x):
# default behavior
return numpy.zeros(x.shape)
## Function that set the parameter of the kernel.
# If the derived classes have parameters, overload this
# method to set the parameters.
# @param param Parameters to be set.
#
def SetParam(self, param):
# default behavior
pass
## Clear the base part of the kernel computed for data x.
# If x is not given, then all remembered data in the cache is removed.
# If x has never been remembered, then this function does nothing
# and return False instead.
# @param x [read] The data whose base part is to be removed from the cache.
#
def ClearCacheKernel(self, x=None):
# default behavior
if x is not None:
assert len(x.shape) == 2, "Argument 1 has wrong shape"
if self._cacheKernel.has_key(id(x)) is False:
return False
else:
del self._cacheKernel[id(x)]
else:
self._cacheKernel.clear()
return True
## Create the cache for the base part of the kernel computed for
# data x, and index them by the id of x. If x have already been
# remembered, the old stored information is simply overwritten.
# Overload this method to store different base part for different
# kernels.
# @param x [read] The data whose base part is to be cached.
#
def CreateCacheKernel(self, x):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Dot product of x with itself with the cached base part of the kernel.
# Overload this method to use the base part differently for different
# kernel. If param is given, the kernel matrix is computed using
# the given parameter and the current base part. Otherwise, the old
# parameters are used.
# @param x The data set.
# @param param The new parameters.
# @param output The output buffer.
#
def DotCacheKernel(self, x, param=None, output=None):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Decrement the base part of the kernel for x1 stored in the cache
# by x2. Overload this method to define the decrement of the base
# part differently for different kernels. Note that this method
# updates the cache for the kernel part.
# @param x1 The data set whose base part has been cached.
# @param x2 The data set who is to be decremented from x1.
#
def DecCacheKernel(self, x1, x2):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Decrement the base part of the kernel for x1 stored in the cache
# by x2, and return the resulting kernel matrix. If param is given,
# the kernel matrix is computed using the given parameter and the
# current base part. Otherwise, the old parameters are used. Overload
# this method to have different behavior for different kernel. Note
# that this method does NOT change the cache for the kernel part.
# @param x1 The data set whose base part has been cached.
# @param x2 The data set who is to be decremented from x1.
# @param param The new parameters.
#
def DecDotCacheKernel(self, x1, x2, param=None, output=None):
raise NotImplementedError, \
'CVectorKernel.K in abstract class is not implemented'
## Gradient of the kernel matrix with respect to the kernel parameter.
# If param is given, the kernel matrix is computed using the given
# parameter and the current base part. Otherwise, the old parameters
# are used. Overload this method to have different behavior.
# @param x The data set for the kernel matrix.
# @param param The kernel parameters.
#
def GradDotCacheKernel(self, x, param=None, output=None):
# default behavior
assert len(x.shape)==2, "Argument 1 has wrong shape"
assert self._cacheKernel.has_key(id(x)) == True, \
"Argument 1 has not been cached"
if param is not None:
self.SetParam(param)
n = x.shape[0]
output = numpy.zeros((n,n), numpy.float64)
return output
#------------------------------------------------------------------------------
## Linear kernel class
#
# The methods are implemente efficiently by computing the resulting
# matrices block by block.
#
class CLinearKernel(CVectorKernel):
def __init__(self, blocksize=128):
CVectorKernel.__init__(self, blocksize)
self._name = 'Linear kernel'
## Compute the kernel between two data points x1 and x2.
# It returns a scale value of dot product between x1 and x2.
# @param x1 [read] The first data point.
# @param x2 [read] The second data point.
#
def K(self, x1, x2):
assert len(x1.squeeze().shape) == 1, 'x1 is not a vector'
assert len(x2.squeeze().shape) == 1, 'x2 is not a vector'
return (x1.squeeze()*x2.squeeze()).sum()
## Compute the kernel between the data points in x1 and those in x2.
# It returns a matrix with entry $(ij)$ equal to $K(x1_i, x1_j)$.
# If index1/index2 is
# specified, only those data points in x1/x2 with indices corresponding
# to index1/index2 are used to compute the kernel matrix. Furthermore,
# if output is specified, the provided buffer is used explicitly to
# store the kernel matrix.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Dot(self, x1, x2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[1] == x2.shape[1], \
'Argument 1 and Argument 2 have different dimensions'
if index1 is not None:
x1 = x1[index1,]
if index2 is not None:
x2 = x2[index2,]
# number of data points in x1.
n1 = x1.shape[0]
# number of data points in x2.
n2 = x2.shape[0]
# number of blocks.
nb = n1 / self._blocksize
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.dot(x1, numpy.transpose(x2))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = numpy.transpose(numpy.dot(x2, numpy.transpose(x1[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = numpy.transpose(numpy.dot(x2, numpy.transpose(x1[lower_limit:n1,])))
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix by alpha2.
# It returns a matrix with entry $(ij)$ equal to
# $sum_r K(x1_i,x2_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param alpha2 [read] The set of coefficients.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Expand(self, x1, x2, alpha2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert len(alpha2.shape) == 2, 'Argument 3 has wrong shape'
assert x1.shape[1] == x2.shape[1], \
'Argument 1 and 2 has different dimesions'
assert x2.shape[0] == alpha2.shape[0], \
'Argument 2 and 3 has different number of data points'
if index1 is not None:
x1 = x1[index1,]
if index2 is not None:
x2 = x2[index2,]
alpha2 = alpha2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = alpha2.shape[1]
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.dot(numpy.dot(x1, numpy.transpose(x2)), alpha2)
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = numpy.dot(numpy.transpose(numpy.dot(x2,numpy.transpose(x1[lower_limit:upper_limit,]))), alpha2)
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = numpy.dot(numpy.transpose(numpy.dot(x2,numpy.transpose(x1[lower_limit:n1,]))), alpha2)
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2. It returns a matrix
# with entry $(ij)$ equal to $K(x1_i,x2_j) \times (y1_i \times y1_j)$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Tensor(self, x1, y1, x2, y2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(y1.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == y1.shape[0], \
'Argument 1 and 2 has different dimensions'
assert len(x2.shape) == 2, 'Argument 3 has wrong shape'
assert len(y2.shape) == 2, 'Argument 4 has wrong shape'
assert x2.shape[0] == y2.shape[0], \
'Argument 2 and 3 has different dimensions'
if index1 is not None:
x1 = x1[index1,]
y1 = y1[index1,]
if index2 is not None:
x2 = x2[index2,]
y2 = y2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = x2.shape[0]
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.transpose(y1[:,0]*numpy.transpose(y2[:,0]*numpy.dot(x1, numpy.transpose(x2))))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = y2[:,0]*numpy.transpose(y1[lower_limit:upper_limit,0]*numpy.dot(x2, numpy.transpose(x1[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = y2[:,0]*numpy.transpose(y1[lower_limit:n1,0]*numpy.dot(x2, numpy.transpose(x1[lower_limit:n1,])))
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2, and final multiply
# the resulting matrix by alpha2. It returns a matrix with entry $(ij)$
# equal to $sum_r K(x1_i,x2_r) \times (y1_i \times y1_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def TensorExpand(self, x1, y1, x2, y2, alpha2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(y1.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == y1.shape[0], \
'Argument 1 and 2 have different dimensions'
assert len(x2.shape) == 2, 'Argument 3 has wrong shape'
assert len(y2.shape) == 2, 'Argument 4 has wrong shape'
assert x2.shape[0] == y2.shape[0], \
'Argument 3 and 4 have different dimensions'
assert len(alpha2.shape) == 2, 'Argument 5 has wrong shape'
assert x2.shape[0] == alpha2.shape[0], \
'Argument 3 and 5 have different number of data points'
if index1 is not None:
x1 = x1[index1,]
y1 = y1[index1,]
if index2 is not None:
x2 = x2[index2,]
y2 = y2[index2,]
alpha2 = alpha2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = alpha2.shape[1]
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.transpose(y1[:,0] * numpy.transpose(numpy.dot(y2[:,0]*numpy.dot(x1,numpy.transpose(x2)), alpha2)))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = numpy.dot(y2[:,0]*numpy.transpose(y1[lower_limit:upper_limit,0] * numpy.dot(x2,numpy.transpose(x1[lower_limit:upper_limit,]))), alpha2)
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = numpy.dot(y2[:,0]*numpy.transpose(y1[lower_limit:n1,0] * numpy.dot(x2,numpy.transpose(x1[lower_limit:n1,]))), alpha2)
return output
## Create the cache for the base part of the kernel computed for
# data x, and index them by the id of x. If x have already been
# remembered, the old stored information is simply overwritten.
# @param x [read] The data whose base part is to be cached.
#
def CreateCacheKernel(self, x):
assert len(x.shape) == 2, 'Argument 1 has wrong shape'
n = x.shape[0]
nb = n / self._blocksize
# create the cache space
if self._cacheKernel.has_key(id(x)):
self.ClearCacheKernel(x)
tmpCacheKernel = numpy.zeros((n,n), numpy.float64)
self._cacheKernel[id(x)] = tmpCacheKernel
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
tmpCacheKernel[lower_limit:upper_limit,] = numpy.transpose(numpy.dot(x, numpy.transpose(x[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n:
tmpCacheKernel[lower_limit:n,] = numpy.transpose(numpy.dot(x, numpy.transpose(x[lower_limit:n,])))
return True
## Dot product of x with itself with the cached base part of the kernel.
# If param is given, the kernel matrix is computed using
# the given parameter and the current base part. Otherwise, the old
# parameters are used.
# @param x The data set.
# @param param The new parameters.
# @param output The output buffer.
#
def DotCacheKernel(self, x, param=None, output=None):
assert len(x.shape)==2, 'Argument 1 has wrong shape'
assert self._cacheKernel.has_key(id(x)) == True, \
'Argument 1 has not been cached'
n = x.shape[0]
nb = n / self._blocksize
tmpCacheKernel = self._cacheKernel[id(x)]
# set parameters.
if param is not None:
self.SetParam(param)
if output is None:
output = numpy.zeros((n,n), numpy.float64)
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = tmpCacheKernel[lower_limit:upper_limit,]
lower_limit = upper_limit
if lower_limit <= n:
output[lower_limit:n,] = tmpCacheKernel[lower_limit:n,]
return output
## Decrement the base part of the kernel for x1 stored in the cache
# by x2. Note that this method updates the cache for the kernel part.
# @param x1 The data set whose base part has been cached.
# @param x2 The data set who is to be decremented from x1.
#
def DecCacheKernel(self, x1, x2):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == x2.shape[0], \
'Argument 1 and 2 have different number of data points'
assert self._cacheKernel.has_key(id(x1)) == True, \
'Argument 1 has not been cached'
n = x1.shape[0]
nb = n / self._blocksize
tmpCacheKernel = self._cacheKernel[id(x1)]
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
tmpCacheKernel[lower_limit:upper_limit,] = tmpCacheKernel[lower_limit:upper_limit,] \
- numpy.transpose(numpy.dot(x2, numpy.transpose(x2[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n:
tmpCacheKernel[lower_limit:n,] = tmpCacheKernel[lower_limit:n,] \
- numpy.transpose(numpy.dot(x2, numpy.transpose(x2[lower_limit:n,])))
return True
## Decrement the base part of the kernel for x1 stored in the cache
# by x2, and return the resulting kernel matrix. If param is given,
# the kernel matrix is computed using the given parameter and the
# current base part. Otherwise, the old parameters are used. Note
# that this method does NOT change the cache for the kernel part.
# @param x1 The data set whose base part has been cached.
# @param x2 The data set who is to be decremented from x1.
# @param param The new parameters.
#
def DecDotCacheKernel(self, x1, x2, param=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == x2.shape[0], \
'Argument 1 and 2 have different number of data points'
assert self._cacheKernel.has_key(id(x1)) == True, \
'Argument 1 has not been cached'
n = x1.shape[0]
nb = n / self._blocksize
tmpCacheKernel = self._cacheKernel[id(x1)]
# set parameters.
if param is not None:
self.SetParam(param)
if output is None:
output = numpy.zeros((n,n), numpy.float64)
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = tmpCacheKernel[lower_limit:upper_limit,] \
- numpy.transpose(numpy.dot(x2, numpy.transpose(x2[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n:
output[lower_limit:n,] = tmpCacheKernel[lower_limit:n,] \
- numpy.transpose(numpy.dot(x2, numpy.transpose(x2[lower_limit:n,])))
return output
#------------------------------------------------------------------------------
## Dot Product kernel class
#
# All kernels that are function of the dot product between the two
# data points, ie. $K(x1,x2)=Kappa(x1^\top x2).
# The methods are implemente efficiently by computing the resulting
# matrices block by block. All kernel classes derived from CDotProductKernel
# differ only in their choice of Kappa function.
#
class CDotProductKernel(CVectorKernel):
def __init__(self, blocksize=128):
CVectorKernel.__init__(self, blocksize)
self._name = 'Dot Product kernel'
## Compute the kernel between two data points x1 and x2.
# It returns a scale value of dot product between x1 and x2.
# @param x1 [read] The first data point.
# @param x2 [read] The second data point.
#
def K(self, x1, x2):
assert len(x1.squeeze().shape) == 1, 'x1 is not a vector'
assert len(x2.squeeze().shape) == 1, 'x2 is not a vector'
return (x1.squeeze()*x2.squeeze()).sum()
## Compute the kernel between the data points in x1 and those in x2.
# It returns a matrix with entry $(ij)$ equal to $K(x1_i, x1_j)$.
# If index1/index2 is
# specified, only those data points in x1/x2 with indices corresponding
# to index1/index2 are used to compute the kernel matrix. Furthermore,
# if output is specified, the provided buffer is used explicitly to
# store the kernel matrix.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Dot(self, x1, x2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[1] == x2.shape[1], \
'Argument 1 and Argument 2 have different dimensions'
if index1 is not None:
x1 = x1[index1,]
if index2 is not None:
x2 = x2[index2,]
# number of data points in x1.
n1 = x1.shape[0]
# number of data points in x2.
n2 = x2.shape[0]
# number of blocks.
nb = n1 / self._blocksize
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = self.Kappa(numpy.dot(x1, numpy.transpose(x2)))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = self.Kappa(numpy.transpose(numpy.dot(x2, numpy.transpose(x1[lower_limit:upper_limit,]))))
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = self.Kappa(numpy.transpose(numpy.dot(x2, numpy.transpose(x1[lower_limit:n1,]))))
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix by alpha2.
# It returns a matrix with entry $(ij)$ equal to
# $sum_r K(x1_i,x2_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param x2 [read] The second set of data points.
# @param alpha2 [read] The set of coefficients.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Expand(self, x1, x2, alpha2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(x2.shape) == 2, 'Argument 2 has wrong shape'
assert len(alpha2.shape) == 2, 'Argument 3 has wrong shape'
assert x1.shape[1] == x2.shape[1], \
'Argument 1 and 2 has different dimesions'
assert x2.shape[0] == alpha2.shape[0], \
'Argument 2 and 3 has different number of data points'
if index1 is not None:
x1 = x1[index1,]
if index2 is not None:
x2 = x2[index2,]
alpha2 = alpha2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = alpha2.shape[1]
if output is not None:
output = output
else:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.dot(self.Kappa(numpy.dot(x1, numpy.transpose(x2))), alpha2)
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = numpy.dot(self.Kappa(numpy.transpose(numpy.dot(x2,numpy.transpose(x1[lower_limit:upper_limit,])))), alpha2)
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = numpy.dot(self.Kappa(numpy.transpose(numpy.dot(x2,numpy.transpose(x1[lower_limit:n1,])))), alpha2)
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2. It returns a matrix
# with entry $(ij)$ equal to $K(x1_i,x2_j) \times (y1_i \times y1_j)$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def Tensor(self, x1, y1, x2, y2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(y1.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == y1.shape[0], \
'Argument 1 and 2 has different dimensions'
assert len(x2.shape) == 2, 'Argument 3 has wrong shape'
assert len(y2.shape) == 2, 'Argument 4 has wrong shape'
assert x2.shape[0] == y2.shape[0], \
'Argument 2 and 3 has different dimensions'
if index1 is not None:
x1 = x1[index1,]
y1 = y1[index1,]
if index2 is not None:
x2 = x2[index2,]
y2 = y2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = x2.shape[0]
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.transpose(y1[:,0]*numpy.transpose(y2[:,0]*self.Kappa(numpy.dot(x1, numpy.transpose(x2)))))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = y2[:,0]*numpy.transpose(y1[lower_limit:upper_limit,0]*self.Kappa(numpy.dot(x2, numpy.transpose(x1[lower_limit:upper_limit,]))))
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = y2[:,0]*numpy.transpose(y1[lower_limit:n1,0]*self.Kappa(numpy.dot(x2, numpy.transpose(x1[lower_limit:n1,]))))
return output
## Compute the kernel between the data points in x1 and those in x2,
# then multiply the resulting kernel matrix elementwiesely by the
# the outer-product matrix between y1 and y2, and final multiply
# the resulting matrix by alpha2. It returns a matrix with entry $(ij)$
# equal to $sum_r K(x1_i,x2_r) \times (y1_i \times y1_r) \times alpha2_r$.
# Other parameters are defined similarly as those in Dot.
# @param x1 [read] The first set of data points.
# @param y1 [read] The first set of labels.
# @param x2 [read] The second set of data points.
# @param y2 [read] The second set of labels.
# @param index1 [read] The indices into the first set of data points.
# @param index2 [read] The indices into the second set of data points.
# @param output [write] The buffer where the output matrix is written into.
#
def TensorExpand(self, x1, y1, x2, y2, alpha2, index1=None, index2=None, output=None):
assert len(x1.shape) == 2, 'Argument 1 has wrong shape'
assert len(y1.shape) == 2, 'Argument 2 has wrong shape'
assert x1.shape[0] == y1.shape[0], \
'Argument 1 and 2 have different dimensions'
assert len(x2.shape) == 2, 'Argument 3 has wrong shape'
assert len(y2.shape) == 2, 'Argument 4 has wrong shape'
assert x2.shape[0] == y2.shape[0], \
'Argument 3 and 4 have different dimensions'
assert len(alpha2.shape) == 2, 'Argument 5 has wrong shape'
assert x2.shape[0] == alpha2.shape[0], \
'Argument 3 and 5 have different number of data points'
if index1 is not None:
x1 = x1[index1,]
y1 = y1[index1,]
if index2 is not None:
x2 = x2[index2,]
y2 = y2[index2,]
alpha2 = alpha2[index2,]
n1 = x1.shape[0]
nb = n1 / self._blocksize
n2 = alpha2.shape[1]
if output is None:
output = numpy.zeros((n1,n2), numpy.float64)
# handle special cases:
if index2 is not None:
if len(index2) <= self._blocksize:
output = numpy.transpose(y1[:,0] * numpy.transpose(numpy.dot(y2[:,0]*self.Kappa(numpy.dot(x1,numpy.transpose(x2))), alpha2)))
return output
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = numpy.dot(y2[:,0]*numpy.transpose(y1[lower_limit:upper_limit,0] * self.Kappa(numpy.dot(x2,numpy.transpose(x1[lower_limit:upper_limit,])))), alpha2)
lower_limit = upper_limit
if lower_limit <= n1:
output[lower_limit:n1,] = numpy.dot(y2[:,0]*numpy.transpose(y1[lower_limit:n1,0] * self.Kappa(numpy.dot(x2,numpy.transpose(x1[lower_limit:n1,])))), alpha2)
return output
## Create the cache for the base part of the kernel computed for
# data x, and index them by the id of x. If x have already been
# remembered, the old stored information is simply overwritten.
# @param x [read] The data whose base part is to be cached.
#
def CreateCacheKernel(self, x):
assert len(x.shape) == 2, 'Argument 1 has wrong shape'
n = x.shape[0]
nb = n / self._blocksize
# create the cache space
if self._cacheKernel.has_key(id(x)):
self.ClearCacheKernel(x)
tmpCacheKernel = numpy.zeros((n,n), numpy.float64)
self._cacheKernel[id(x)] = tmpCacheKernel
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
tmpCacheKernel[lower_limit:upper_limit,] = numpy.transpose(numpy.dot(x, numpy.transpose(x[lower_limit:upper_limit,])))
lower_limit = upper_limit
if lower_limit <= n:
tmpCacheKernel[lower_limit:n,] = numpy.transpose(numpy.dot(x, numpy.transpose(x[lower_limit:n,])))
return True
## Dot product of x with itself with the cached base part of the kernel.
# If param is given, the kernel matrix is computed using
# the given parameter and the current base part. Otherwise, the old
# parameters are used.
# @param x The data set.
# @param param The new parameters.
# @param output The output buffer.
#
def DotCacheKernel(self, x, param=None, output=None):
assert len(x.shape)==2, 'Argument 1 has wrong shape'
assert self._cacheKernel.has_key(id(x)) == True, \
'Argument 1 has not been cached'
n = x.shape[0]
nb = n / self._blocksize
tmpCacheKernel = self._cacheKernel[id(x)]
# set parameters.
if param is not None:
self.SetParam(param)
if output is None:
output = numpy.zeros((n,n), numpy.float64)
# blocking
lower_limit = 0
upper_limit = 0
for i in range(nb):
upper_limit = upper_limit + self._blocksize
output[lower_limit:upper_limit,] = self.Kappa(tmpCacheKernel[lower_limit:upper_limit,])
lower_limit = upper_limit
if lower_limit <= n:
output[lower_limit:n,] = self.Kappa(tmpCacheKernel[lower_limit:n,])
return output
## Decrement the base part of the kernel for x1 stored in the cache
# by x2. Note that this method updates the cache for the kernel part.