1, 简单线性回归概念
简单线性回归通过拟合线性方程 y=wx+b 得到预测值, 通过取得预测值和真实值的最小差距, 得到 w 和 b 的值.
公式: J(w,b)min=Σ(yi-yipre)2=∑(yi-wxi+b)2, 即公式取最小值
2, 通过最小二乘法求解 w 和 b
w = ∑(xi-xmean)(yi-ymean)/∑*(xi-xmean)
b = ymean-axmean
向量化公式: w = XY/XX
- import numpy as np
- from sklearn import datasets
- from sklearn.model_selection import train_test_split
- # 导入线性回归库
- from sklearn.linear_model import LinearRegression
- boston = datasets.load_boston()
- a = boston.data
- y = boston.target
- a = a[y<50.0]
- y = y[y<50.0]
- X_train, X_test, y_train, y_test = train_test_split(a, y, random_state=666)
- lin_reg = LinearRegression()
- lin_reg.fit(X_train, y_train)
- # 权重系数
- lin_reg.coef_
- # 截距
- lin_reg.intercept_
- # R2 准确率
- lin_reg.score
- View Code
3, 线性回归准确性的衡量标准
一般 J(w,b) 值最小时预测准确率最高, 但考虑样本集的数量, 如: 10000 个样本误差为 1000,100 个样本误差为 500, 这样误差为 1000 的预测效果好, 所以要去掉样本集的影响.
均方误差: MSE=J(w,b)/m
均方根误差: RMSE=sqrt(MSE)
平均绝对值误差: MAE=∑|yi-yipre|/m
4, 最好的线性回归准确性的衡量标准 R Squared
公式: R2=1-∑(yi-yipre)2/∑(ymean-yi)2
分子: 表示自定义模型预测产生的误差
分母: 使用 y=ymean 基准模型预测产生的误差
公式表示自定义模型对比基准模型的百分比
R2<=1 且值越大表示自定义模型预测的效果越好
R2<0 表面自定义模型预测效果极差, 不如基准模型, 数据之间大概率不是线性关系
R2 分子分母同时除以样本 m 得到: R2 = 1-MSE(ypre-y)/var(y) (var 是方差)
- import numpy as np
- from sklearn import datasets
- from sklearn.model_selection import train_test_split
- # 导入线性回归库
- from sklearn.linear_model import LinearRegression
- # 导入 (MSE)
- from sklearn.metrics import mean_squared_error
- # 导入 (MAE)
- from sklearn.metrics import mean_absolute_error
- # 导入 (R2)
- from sklearn.metrics import r2_score
- boston = datasets.load_boston()
- a = boston.data
- y = boston.target
- a = a[y<50.0]
- y = y[y<50.0]
- X_train, X_test, y_train, y_test = train_test_split(a, y, random_state=666)
- lin_reg = LinearRegression()
- lin_reg.fit(X_train, y_train)
- MSE = mean_squared_error(y, y_calculate)
- MAE = mean_absolute_error(y, y_calculate)
- # RMSE
- RMSE = np.sqrt(MSE)
- # R2
- r2_score(y, y_calculate)
- View Code
5, 多元线性回归
一个样本具有 N 个特征值: y = b + w1x1 + w2x2 + ...+ wmxm
6, 线性回归模型的解释
w 系数的正负分别代表正负相关, 数值大小代表相关程度
来源: http://www.bubuko.com/infodetail-2972650.html