简单线性模型拟合
适合一维的数据
定义模型

定义平均损失函数:

问题转化为求最小时,
的值,即

求偏导然后联立求解
令:

求得:

更复杂的线性关系模型
利用矩阵推导更一般的模型
令:
![\bf x_n=\left[ \begin{matrix} 1 \\ x_n \end{matrix} \right] , \bf w = \left[ \begin{matrix} w_0\\ w_1 \end{matrix} \right] \\ \\ \tag{6}](https://i-blog.csdnimg.cn/blog_migrate/48ad57e6cc92ab7b7bda301859a51908.png)
得到:
![\bf X=\left[ \begin{matrix} \bf x_1^T \\ \bf x_2^T \\ \vdots \\ \bf x_N^T \\ \end{matrix} \right] = \left[ \begin{matrix} 1 & x_1 \\ 1 & x_2 \\ \vdots & \vdots \\ 1 & x_N \\ \end{matrix} \right] , \bf y = \left[ \begin{matrix} y_1 \\ y_2 \\ \vdots \\ y_N \end{matrix} \right]](https://i-blog.csdnimg.cn/blog_migrate/2aae89f71d8dd986b07aa68790c42c0f.png)
平均损失函数可以表示为:

求偏导:

得到:

即:

简单线性模型拟合实现
推导出来结果后,代码比较简单了,我是用js写的
// 模型
// y = w0 + w1*x
export class Liner {
constructor(public inputs: number[] = [], public outputs: number[] = []) {}
// 求w1
getW1(): number {
const xt = this.inputs.map((item: number, index: number) => {
return item * this.outputs[index];
});
const xx = this.inputs.map(item => item * item);
const xtMean = Liner.mean(xt);
const _x = Liner.mean(this.inputs);
const _y = Liner.mean(this.outputs);
return (xtMean - _x * _y) / (Liner.mean(xx) - _x * _x);
}
// 求w0
getW0() {
return Liner.mean(this.outputs) - this.getW1() * Liner.mean(this.inputs);
}
// 预测值
get(input: number) {
return this.getW0() + this.getW1() * input;
}
// 求平均值
static mean(arr: number[]): number {
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
}
复制代码