其中x'是所有点x坐标的平均数,同样的,y'是所有点y坐标的平均数。
代码请戳:linearRegression.js
通过这条公式,我们可以轻易得到数组[1, 3]的斜率和偏移量为{ a: 2, b:1 },然后就可以知道以后的数据走向将会是[5, 7, 9, ...]。
这就是整一个“智能填充”的核心原理,接下来我们就可以依靠这个原理去实现数据的预测了。
Predictor
借助线性回归的力量,我们可以通过设置预测的次数,挨个挨个地对每一个分组数据进行预测,然后再把它们组合到一起形成一个新的结果数组。
以上文Classifier中的分组数据为例,对它预测一次,结果如下:
{ 'Number': [{ realValue: '1', index: 0, ... }, { realValue: '2', index: 1, ... }, { realValue: '3', index: 6, ... }, { realValue: '4', index: 7, ... }], 'ac': [{ realValue: 'a1c', index: 2, ... }, { realValue: 'a2c', index: 3, ... }, { realValue: 'a3c', index: 8, ... }, { realValue: 'a4c', index: 9, ... }], 'Number1': [{ realValue: '6', index: 4, ... }, { realValue: '8', index: 5 ... }, { realValue: '10', index: 10, ... }, { realValue: '12', index: 11 ... }] }
代码请戳:predictor.js
由于我们知道每一个数据的下标,所以我们可以简单又准确地把它们放到正确的位置去,最后输出如下:
[1, 2, 'a1c', 'a2c', 6, 8, 3, 4, 'a3c', 'a4c', 10, 12]
接下来我们可以来看看测试用例对比Excel表现:
More
当前的smart-predictor仍然不够“smart”,它只能预测自然数字,或者自然数字与字符串的结合,但仍然不支持对日期格式,字母列表等数据的预测。如果各位读者有兴趣,也非常欢迎大家来贡献脑洞,让smart-predicotr变得更加智能。
总结