Skip to content

Instantly share code, notes, and snippets.

@julienetie
Created March 24, 2022 00:59
Show Gist options
  • Save julienetie/9f72fe4de9da786b092ae0e0787837af to your computer and use it in GitHub Desktop.
Save julienetie/9f72fe4de9da786b092ae0e0787837af to your computer and use it in GitHub Desktop.
Linear Regression experiment
//const data = [1.5, 3.8, 6.7, 9.0, 11.2, 13.6, 16]
const data = [4, 4, 3, 5, 4, 3, 2, 2, 3, 4, 1, 1, 3]
const x = data.map((_, i) => i + 1)
const y = data
const xy = data.map((value, i) => (i + 1) * value)
const xPow2 = data.map((_, i) => (i + 1) ** 2)
//const sumOfX =data.reduce((acc, _, i) => acc + i
const sum = arr => arr.reduce((acc,value)=> acc + value)
// Max
const n = x[x.length - 1]
// Sloap
const m = ((n * sum(xy)) - (sum(x)) * sum(y)) / ((n * sum(xPow2)) - (sum(x) ** 2))
//
const b = (sum(y) - (m * sum(x))) / n
const Y = xPos => (m * xPos) + b
document.body.insertAdjacentHTML('afterbegin',
`
<div>x: ${x}</div>
<div>y: ${y}</div>
<div>xy: ${xy}</div>
<div>x^2: ${xPow2}</div>
<br>
<div> Σx: ${sum(x)}</div>
<div>y: ${sum(y)}</div>
<div>xy: ${sum(xy)}</div>
<div>x^2: ${sum(xPow2)}</div>
<br>
<div>m (Sloap): ${m}</div>
<div>b: ${b}</div>
<br>
Example of 2
<div>Y: ${Y(2)}</div>
Example of 5
<div>Y: ${Y(5)}</div>
Example of 7
<div>Y: ${Y(7)}</div>
`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment