Created
December 9, 2023 01:28
-
-
Save umihico/b582e30ae2181da21e0f789eef2ad92c to your computer and use it in GitHub Desktop.
slopeとinterceptをcovarianceとvarianceから求められるか実践
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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