-
Notifications
You must be signed in to change notification settings - Fork 7
/
example-regression-2.html
81 lines (70 loc) · 2.37 KB
/
example-regression-2.html
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
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" type="text/javascript"></script>
<script src="https://rawgit.com/chen0040/js-regression/master/build/jsregression.min.js" type="application/javascript"></script>
<!--<script src="./src/jsregression.js" type="application/javascript"></script>-->
</head>
<body>
<h2>Linear Regression Demo</h2>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
// === training data generated from y = 2.0 + 5.0 * x + 2.0 * x^2 === //
var data = [];
for(var x = 1.0; x < 100.0; x += 1.0) {
var y = 1300.0 - 25.0 * x - 2.0 * x * x + (Math.random()-0.5) * 1000;
data.push([x, x * x, y]); // Note that the last column should be y the output
}
// === Create the linear regression === //
var regression = new jsregression.LinearRegression({
alpha: 0.0000001, //
iterations: 3000,
lambda: 0.0,
trace: false
});
// can also use default configuration: var regression = new jsregression.LinearRegression();
// === Train the linear regression === //
var model = regression.fit(data);
// === Print the trained model === //
console.log(model);
// === Testing the trained linear regression === //
var items = [
];
var items_predicted = [];
for(var x = 1.0; x < 100.0; x += 0.5) {
var actual_y = 1300.0 - 25.0 * x - 2.0 * x * x + (Math.random()-0.5) * 1000;
var predicted_y = regression.transform([x, x * x]);
items.push({x: x, y: actual_y});
items_predicted.push({x: x, y: predicted_y});
console.log("actual: " + actual_y + " predicted: " + predicted_y);
}
console.log(items);
var pointBackgroundColors = [];
var pointBackgroundColors2 = [];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Actual',
data: items,
pointBackgroundColor: pointBackgroundColors,
pointBorderColor: []
}, {
label: 'Predicted',
data: items_predicted,
pointBackgroundColor: pointBackgroundColors2,
pointBorderColor: []
}
]
},
options: {
}
});
for (i = 0; i < myChart.data.datasets[0].data.length; i++) {
pointBackgroundColors.push("#90cd8a");
pointBackgroundColors2.push("#f58368");
}
myChart.update();
</script>
</body>
</html>