Spaces:
Sleeping
Sleeping
Download SimpleLinearRegression.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 1.42 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/SimpleLinearRegression.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem/SimpleLinearRegression.js
-
curl -L -o SimpleLinearRegression.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/SimpleLinearRegression.js
1.42 kB
| 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; | |
| } | |
| } | |