Linear Regression in JS

This code is mainly based on the p5js library, which provide us an accessible sketchbook to interactive with HTML objects.

In p5, we only need to make our own changes to the file named sketch.js.

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
var data = [];

var m = 1;
var b = 0;

function setup() {
createCanvas(400, 400);
}

function linearRegression() {
var xsum = 0;
var ysum = 0;
for (var i = 0; i < data.length; i++) {
xsum += data[i].x;
ysum += data[i].y;
}
var xmean = xsum / data.length;
var ymean = ysum / data.length;
var num = 0;
var den = 0;
for (var i = 0; i < data.length; i++) {
var x = data[i].x;
var y = data[i].y;
num += (x - xmean) * (y - ymean);
den += (x - xmean) * (x - xmean);
}

m = num / den;
b = ymean - m * xmean;
}

function drawLine() {
var x1 = 0;
var y1 = m * x1 + b;
var x2 = 1;
var y2 = m * x2 + b;

x1 = map(x1, 0, 1, 0, width);
y1 = map(y1, 0, 1, height, 0);
x2 = map(x2, 0, 0, width);
y2 = map(y2, 0, 1, height, 0);

stroke(255, 0, 255);
line(x1, y1, x2, y2);
}

function mousePressed() {
var x = map(mouseX, 0, width, 0, 1);
var y = map(mouseY, 0, height, 1, 0);
var point = createVector(x, y);
data.push(point);
}

function draw() {
background(51);

for (var i = 0; i < data.length; i++) {
var x = map(data[i].x, 0, 1, 0, width);
var y = map(data[i].y, 0, 1, height, 0);
fill(255);
stroke(255);
ellipse(x, y, 8, 8);
}

if (data.length > 1) {
linearRegression();
drawLine();
}
}

Click on the index.html file, and we can make our regression on any browser support javascript. Here is the design sketch.



文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/02/23/Linear-Regression-in-JS/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏