-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGradientDescent.java
More file actions
65 lines (52 loc) · 1.8 KB
/
Copy pathGradientDescent.java
File metadata and controls
65 lines (52 loc) · 1.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
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class GradientDescent
{
public static void main(String[] args) throws IOException
{
ArrayList<DataPoint> dataList = new ArrayList<>();
Scanner sc = new Scanner(new File("10points.txt"));
while(sc.hasNextInt())
{
int time = sc.nextInt();
int trafficVolume = sc.nextInt();
dataList.add(new DataPoint(time, trafficVolume));
}
sc.close();
runGradientDescentSteps(dataList);
}
public static void runGradientDescentSteps(ArrayList<DataPoint> dataList)
{
double eta = 0.0003;
double epsilon = 50;
double a = 1.0;
double s = 0.0;
double sumGradS;
double sumGradA;
int step = 1;
System.out.println("---- Begin Gradient Descent training (do-while loop) ----");
do
{
sumGradS = 0;
sumGradA = 0;
for (int i = 0; i < dataList.size(); i++)
{
int xi = dataList.get(i).time;
int yi = dataList.get(i).trafficVolume;
double pred = (a * xi) + s;
sumGradS += 2 * (pred - yi);
sumGradA += 2 * xi * (pred - yi);
}
s = s - (eta * sumGradS);
a = a - (eta * sumGradA);
System.out.printf("Step %3d | a: %8.4f | s: %8.4f\n", step++, a, s);
}
while (Math.abs(sumGradS) > epsilon || Math.abs(sumGradA) > epsilon);
{
System.out.println("\n---- final step reached ----");
System.out.printf("Traffic = (%.4f * Time) + (%.4f)\n", a, s);
}
}
}