线性模型|线性回归
基本形式
给定由d个属性描述的示例,其中是在第i个属性上的取值,线性模型想要通过一个属性的线性组合来得到一个预测的函数,即:
一般用向量的形式可以写成:
其中,当w和b学得之后,模型就得以确定。
回归分析
回归分析是用来评估变量之间关系的统计过程,用来解释自变量x与因变量y之间的关系,即当自变量x发生改变时,因变量y会如何发生改变。
线性回归
线性回归是回归分析的一种,评估的自变量x和因变量y之间是一种线性关系。当只有一个自变量时,称为简单线性回归,当具有多个自变量时,称为多元线性回归。
对线性关系的理解:
- 画出来的图像是直的。
- 每个自变量的最高次项是1。
简单的线性回归我们可以直接表示成如下形式:
注:此时的自变量只有一个值。
多元线性回归有多个自变量的值,而对于每一个自变量x都有一个与其对应的参数w,我们可以把x和w表示出向量或者矩阵的形式,表示方法如下:
对于向量来说可以展开成下面的形式:
简单线性回归的代码展示如下
import numpy as np
# 线性回归函数
from sklearn.linear_model import LinearRegression
# 用于切分数据集
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# 加载鸢尾花数据集
iris = load_iris()
# 使用花瓣长和花瓣宽作为x,y
X, y = iris.data[:, 2].reshape(-1, 1), iris.data[:, 3]
lr = LinearRegression()
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.25,
random_state=0)
lr.fit(X_train, y_train)
print("权重:", lr.coef_)
print("截距:", lr.intercept_)
y_hat = lr.predict(X_test)
print("拟合函数:", 'y={}x+{}'.format(lr.coef_[0], lr.intercept_))
import matplotlib.pyplot as plt
# mac下使用中文
plt.rcParams["font.family"] = 'Arial Unicode MS'
# win下使用中文
# plt.rcParams["font.family"] = 'SimHei'
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["font.size"] = 15
plt.figure(figsize=(10, 6), dpi=300)
plt.scatter(X_train, y_train, c='orange', label='训练集')
plt.scatter(X_test, y_test, c='blue', marker='D', label='测试集')
plt.plot(X, lr.predict(X), 'r-')
plt.legend()
plt.xlabel("花瓣长")
plt.ylabel("花瓣宽")
plt.figure(figsize=(15, 6), dpi=300)
plt.plot(y_test, label="真实值", color='r', marker='o')
plt.plot(y_hat, label="预测值", ls='--', color='g', marker='o')
plt.xlabel("测试集数据序号")
plt.ylabel("数据值")
plt.legend()
多元线性回归的代码如下:
import numpy as np
# 线性回归函数
from sklearn.linear_model import LinearRegression
# 用于切分数据集
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# 加载鸢尾花数据集
iris = load_iris()
# 使用鸢尾花的data和target作为x和y
X, y = iris.data, iris.target
lr = LinearRegression()
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.25,
random_state=0)
lr.fit(X_train, y_train)
print("权重:", lr.coef_)
print("截距:", lr.intercept_)
y_hat = lr.predict(X_test)
print(
"拟合函数:",
'y={}x1+{}x2+{}x3+{}x4+{}'.format(lr.coef_[0], lr.coef_[1], lr.coef_[2],
lr.coef_[3], lr.intercept_))
线性回归的损失函数
损失函数:
理论值于观测值之差(误差、残差)的平方和。
其中表示预测值,表示真实值。
损失函数的求解
-
列出目标函数E(损失函数),此时的样本值用来表示。
-
求损失函数关于参数的导数,使导数为0,代表损失函数最小。
-
此时的参数即为我们所求未知解的参数。
矩阵下最小二乘法的求解过程:
首先明确一下向量和矩阵的导数:
假设一个条件 :满足正定矩阵
- 第一步(这里的1/2)是为了方便后面的计算。
- 第二步
令
- 第三步
解得:
最小二乘法的求解代码
import numpy as np
import matplotlib.pyplot as plt
# 在直线 y = 5x+3 附近生成随机点
X = np.arange(0, 5, 0.1)
Z = [5 * x + 3 for x in X]
Y = [np.random.normal(z, 0.5) for z in Z]
plt.plot(X, Y, 'ro')
plt.show()
from scipy.optimize import leastsq
# 需要拟合的函数func :指定函数的形状
def func(p,x):
k,b=p
return k*x+b
# 误差函数:
def error(p,x,y):
# yi-y
return func(p,x)-y
# 设置函数的初始参数
p0=[1,20]
Para=leastsq(error,p0,args=(X,Y))
print(Para)
k,b=Para[0]
_X = [0, 5]
_Y = [b + k * x for x in _X]
plt.plot(X, Y, 'ro', _X, _Y, 'b', linewidth=2)
plt.title("y = {}x + {}".format(k, b))
plt.show()