Skip to content

Instantly share code, notes, and snippets.

@umihico
Created December 9, 2023 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umihico/b582e30ae2181da21e0f789eef2ad92c to your computer and use it in GitHub Desktop.
Save umihico/b582e30ae2181da21e0f789eef2ad92c to your computer and use it in GitHub Desktop.
slopeとinterceptをcovarianceとvarianceから求められるか実践
import { variance } from "mathjs"
import { average, linearRegression, sampleCovariance } from "simple-statistics"
describe("line regression test", () => {
/**
* https://whyitsso.net/math/statistics/statistics1.html
*/
test("実験", () => {
const data = [
[1, 1],
[2, 3],
[3, 2],
[4, 4],
[5, 9],
]
const x = data.map((d) => d[0])
const y = data.map((d) => d[1])
const { m, b } = linearRegression(data)
const averageX = average(x)
const averageY = average(y)
const covariance = sampleCovariance(x, y)
const varianceX = Number(variance(x))
const varianceY = Number(variance(y))
const slope = covariance / varianceX // slopeとinterceptはcovarianceとvarianceから求められる
const intercept = averageY - slope * averageX // interceptはslopeとaverageから求められる
console.log({
m,
b,
covariance,
varianceX,
varianceY,
slope,
averageX,
averageY,
})
expect(m).toBe(1.7)
expect(slope).toBe(m)
expect(b).toBe(-1.2999999999999998)
expect(intercept).toBe(b)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment