-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRidge.py
More file actions
executable file
·49 lines (36 loc) · 1.34 KB
/
Ridge.py
File metadata and controls
executable file
·49 lines (36 loc) · 1.34 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
## author: Mingyu Liu
## author: Shi He
import numpy as np
import string
from Dataset import *
def main():
d = Dataset("rec.sport.hockey.txt", "rec.sport.baseball.txt", cutoff=1000)
(Xtrain, Ytrain, Xtest, Ytest) = d.getTrainAndTestSets(0.8, seed=100)
lam = 100
print lam
w = trainRidge(Xtrain, Ytrain, lam)
trainError = computeError(Xtrain, Ytrain, w)
print 'Train error rate is ' + str(trainError)
testError = computeError(Xtest, Ytest, w)
print 'Test error rate is ' + str(testError)
def trainRidge(Xtrain, Ytrain, lam):
Xmatrix = np.asmatrix(Xtrain)
Ymatrix = np.asmatrix(Ytrain)
return np.linalg.inv(Xmatrix.T * Xmatrix + lam * np.eye(Xmatrix.shape[1])) * Xmatrix.T * Ymatrix
def computeError(Xtest, Ytest, w):
correctCount = 0
incorrectCount = 0
for testIndex in range(Ytest.size):
xtest = Xtest[testIndex]
xtestw = xtest * w
## if sign(xtestw) > 0, expected = 1; if sign(xtestw) <= 0, expected = -1
expected = -1
if xtestw > 0:
expected = 1
if expected == Ytest[testIndex]:
correctCount += 1
else:
incorrectCount += 1
return incorrectCount * 1.0 / (correctCount + incorrectCount)
if __name__ == "__main__":
main()