-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGradientDescent.R
73 lines (51 loc) · 1.1 KB
/
GradientDescent.R
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
h<-function(X, theta){
sum=0
for(i in 1:length(X)){
sum=sum+X[1, i]*theta[i]
}
#print("Finished h\n")
return(sum)
}
sd<-function(calc_val, orig_val){
return((calc_val-orig_val)*(calc_val-orig_val))
}
J<-function(X, theta, y){
diff=0
for(i in 1:length(y)){
diff=diff+sd(h(X[i,], theta), y[i])
}
return(0.5*diff/length(y))
}
calctheta<-function(X, theta, y, j){
diff=0
for(i in 1:length(y)){
diff=diff+(h(X[i,], theta)-y[i])*X[i, j]
}
#print(diff/length(y))
return(diff/length(y))
}
minimizeJ<-function(X, theta, y, alpha=1, c=0.01, num_of_iteration=100){
i=1
temptheta=(1:length(theta))
print(temptheta[length(theta)])
Jval=(1:num_of_iteration)
prev=as.integer(.Machine$integer.max)
while(i<=num_of_iteration)
{
for(j in 1:length(theta))
{
temptheta[j]=theta[j]-alpha*(calctheta(X, theta, y, j))
#print("Inside "+j+"\n")
}
for(j in 1:length(theta))
{
theta[j]=temptheta[j]
}
val=J(X, theta, y)
Jval[i]=val
prev=Jval[i]
i=i+1
#print(i)
}
return(list(theta, Jval))
}