线性回归
预测值
从上面分散的数据中,我们如何预测未来的价格?
- 使用手绘线性图
- 为线性关系建模
- 为线性回归建模
线性图
这是一个基于最低价和最高价预测价格的线性图:
实例
var xArray = [50,60,70,80,90,100,110,120,130,140,150];
var yArray = [7,8,8,9,9,9,9,10,11,14,14,15];
var data = [
{x:xArray, y:yArray, mode:"markers"},
{x:[50,150], y:[7,15], mode:"line"}
];
var layout = {
xaxis: {range: [40, 160], title: "Square Meters"},
yaxis: {range: [5, 16], title: "Price in Millions"},
title: "House Prices vs. Size"
};
Plotly.newPlot("myPlot", data, layout);
Try it Yourself »
来自上一章
线性图可以写成y = ax + b
Where:
- y 是我们要预测的价格
- a 是直线的斜率
- x 是输入值
- b 是截距
线性关系
这个模型使用价格和尺寸之间的线性关系来预测价格:
实例
var xArray = [50,60,70,80,90,100,110,120,130,140,150];
var yArray = [7,8,8,9,9,9,10,11,14,14,15];
// Calculate Slope
var xSum = xArray.reduce(function(a, b){return a + b;}, 0);
var ySum = yArray.reduce(function(a, b){return a + b;}, 0);
var slope = ySum / xSum;
// 生成值
var xValues = [];
var yValues = [];
for (var x = 50; x <= 150; x += 1) {
xValues.push(x);
yValues.push(x * slope);
}
亲自试一试 »
在上面的示例中,斜率是计算的平均值,截距 = 0。
使用线性回归函数
此模型使用线性回归函数预测价格:
实例
var xArray = [50,60,70,80,90,100,110,120,130,140,150];
var yArray = [7,8,8,9,9,9,10,11,14,14,15];
// 计算总和
var xSum=0, ySum=0 , xxSum=0, xySum=0;
var count = xArray.length;
for (var i = 0, len = count; i < count; i++) {
xSum += xArray[i];
ySum += yArray[i];
xxSum += xArray[i] * xArray[i];
xySum += xArray[i] * yArray[i];
}
// 计算斜率和截距
var slope = (count * xySum - xSum * ySum) / (count * xxSum - xSum * xSum);
var intercept = (ySum / count) - (slope * xSum) / count;
// 生成值
var xValues = [];
var yValues = [];
for (var x = 50; x <= 150; x += 1) {
xValues.push(x);
yValues.push(x * slope + intercept);
}
亲自试一试 »