使用js机器学习库了解简单线性回归


一元线性回顾概述

回归分析(Regression Analysis)是确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法。在回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析。

一元线性回归图解

一元线性回归图解

一元线性回归的js库的使用

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
50
51
52
53
54
55
56
57
58
59
const csv = require('csvtojson');
const ml = require("ml-regression")
const csvFilePath = "Advertising.csv"
/**
* 数据示例
* "","TV","Radio","Newspaper","Sales"
"1",230.1,37.8,69.2,22.1
"2",44.5,39.3,45.1,10.4
"3",17.2,45.9,69.3,9.3
"4",151.5,41.3,58.5,18.5
"5",180.8,10.8,58.4,12.9
"6",8.7,48.9,75,7.2
"7",57.5,32.8,23.5,11.8
"8",120.2,19.6,11.6,13.2
"9",8.6,2.1,1,4.8
*/

const _ = require("lodash")
const readline = require("readline")
const SLR = ml.SLR

let csvData = [],
x = [],
y = []

let regressionModel

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

csv().fromFile(csvFilePath)
.on("json", (jsonObj)=> {
csvData.push(jsonObj)
})
.on("done", ()=> {

_.each(csvData, (n)=> {
x.push(_.toNumber(n.Radio))
y.push(_.toNumber(n.Sales))
})
//生成回归方程
regressionModel = new SLR(x, y)

console.log(regressionModel)
console.log(regressionModel.toString())

predictOutput()
})

//递归输出结果
function predictOutput() {
rl.question('Enter input X for prediction (Press CTRL+C to exit) : ', (answer) => {
console.log(`At X = ${answer}, y = ${regressionModel.predict(parseFloat(answer))}`);
predictOutput()
});
}


文章作者: Callable
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Callable !
评论
  目录