forked from fullmetalfelix/ML-CSC-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyKRR.py
70 lines (35 loc) · 1.65 KB
/
pyKRR.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
import numpy
class KRRsolver:
def __init__(self):
self.kmatrix = None
self.Dmatrix = None
self.alpha = 0.5
self.nTrain = 0
self.trainIn = None
self.trainOut = None
print("KRR solver initialised.")
def Train(self, trainIn, trainOut):
self.nTrain = trainIn.shape[0]
self.trainIn = trainIn
self.trainOut = trainOut
# start with a 0 matrix of the right size
self.kmatrix = numpy.zeros((self.nTrain,self.nTrain))
for i in range(self.nTrain):
for j in range(0,i+1):
# compute the distance between molecule i and j
self.kmatrix[i,j] = numpy.linalg.norm(trainIn[i]-trainIn[j])
# it is the same between j and i!
self.kmatrix[j,i] = self.kmatrix[i,j]
# add the -alpha on the diagonal
self.kmatrix[i,i] -= self.alpha
# invert the matrix
self.kmatrix = numpy.linalg.inv(self.kmatrix)
print("Training completed.");
def Evaluate(self, validM):
nValid = validM.shape[0]
self.Dmatrix = numpy.zeros((nValid, self.nTrain))
for i in range(nValid):
for j in range(self.nTrain):
self.Dmatrix[i,j] = numpy.linalg.norm(validM[i]-self.trainIn[j])
Epredict = numpy.dot(self.trainOut, numpy.dot(self.kmatrix, numpy.transpose(self.Dmatrix)))
return Epredict