File size: 1,424 Bytes
27bc6cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export default class SimpleLinearRegression {
   constructor(x, y) {
      this.x = x.map(val => Array.isArray(val) ? val[0] : val);
      this.y = y;
      this.n = this.x.length;
      
      let sumX = 0;
      let sumY = 0;
      let sumXY = 0;
      let sumX2 = 0;
      
      for (let i = 0; i < this.n; i++) {
         sumX += this.x[i];
         sumY += this.y[i];
         sumXY += this.x[i] * this.y[i];
         sumX2 += this.x[i] * this.x[i];
      }
      
      const denominator = (this.n * sumX2 - sumX * sumX);
      if (denominator === 0) {
         this.slope = 0;
         this.intercept = sumY / this.n || 0;
      } else {
         this.slope = (this.n * sumXY - sumX * sumY) / denominator;
         this.intercept = (sumY - this.slope * sumX) / this.n;
      }
      
      this.coefficients = [this.slope, this.intercept];
      
      // Calculate R2
      const yMean = this.n > 0 ? sumY / this.n : 0;
      let ssTot = 0;
      let ssRes = 0;
      
      for (let i = 0; i < this.n; i++) {
         const prediction = this.predict(this.x[i]);
         ssTot += Math.pow(this.y[i] - yMean, 2);
         ssRes += Math.pow(this.y[i] - prediction, 2);
      }
      
      this.r2 = ssTot === 0 ? 1 : 1 - (ssRes / ssTot);
   }
   
   predict(x) {
      const xVal = Array.isArray(x) ? x[0] : x;
      return this.slope * xVal + this.intercept;
   }
}