> For the complete documentation index, see [llms.txt](https://windmising.gitbook.io/liu-yu-bo-play-with-machine-learning/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://windmising.gitbook.io/liu-yu-bo-play-with-machine-learning/src/chapter5-7/5-6.md).

# 5-6 最好的衡量线性回归法的指标 R Squared

分类问题使用accuracy来评价分类结果。\
1最好，0最差。\
即使分类的问题不同，也能很容易的比较它们之间的优劣。

但RMSE和MAE无些特性。\
解决方法：R Squared

## R Squared

$$
R^2 = 1 - \frac {SS\_{residual}}{SS\_{total}} = 1 - \frac{\sum\_i(\hat y^{(i)}- y^{(i)})^2}{\sum\_i(\bar y- y^{(i)})^2}
$$

说明：

$$SS\_{residual}$$: 使用模型预测产生的错误\
$$SS\_{total}$$: 把所有样本都预测为$$\bar y$$产生的错误\
$$\bar y$$：y的平均值\
$$\hat y^{(i)}$$：第i个样本的模型预测值

R Squared代表我们的模型拟合住的数据

R Squared的性质：

* R Squared <= 1 &#x20;
* R Squared越大越好。当我们的预测模型不犯任何错误时，R Squared达到最大值1 &#x20;
* 当我们的模型等于基准模型时，R Squared = 0 &#x20;
* 如果R Squared < 0，说明我们的模型还不如基准模型。此时很有可能数据不存在任何线性关系。

R Squared也可以写成这种形式： ![](http://windmissing.github.io/images/2019/60.png) 其中Var(y)代表方差

## 编程实现R Squared

继续使用5-4中的数据和训练结果

```python
1 - mean_squared_error(y_test, y_predict)/np.var(y_test)
```

或

```python
from sklearn.metrics import r2_score
r2_score(y_test, y_predict)
```
