怀念夏天 发表于 2025-1-23 10:48:47

Sklearn 中的线性回归模子

线性回归的数学模子

假设单变量回归模子:
                                                    h                               θ                                    (                            x                            )                            =                                       θ                               T                                    x                            =                                       θ                               0                                    +                                       θ                               1                                                 x                               1                                          h_\theta(x) = \theta^T x = \theta_0 + \theta_1 x_1                     hθ​(x)=θTx=θ0​+θ1​x1​
这里的                                              θ                            0                                       \theta_0                  θ0​ 就是偏置,而                                              θ                            1                                       \theta_1                  θ1​ 就是权重,而                                              x                            1                                       x_1                  x1​ 就是特征。
线性回归方程的代价函数为:
                                       J                            (                            θ                            )                            =                                       1                                           2                                  m                                                            ∑                               m                                                 i                               =                               1                                    (                                       h                               θ                                    (                                       x                                           (                                  i                                  )                                                 )                            −                                       y                                           (                                  i                                  )                                                            )                               2                                          J(\theta) = \frac{1}{2m} \sum^{m}{i = 1}(h_\theta(x^{(i)}) - y^{(i)})^2                     J(θ)=2m1​∑m​i=1(hθ​(x(i))−y(i))2
这里根据代价函数来计算当前权重与偏置得到的方程与实际情况差距有多大,线性回归题目就是要通过一定方法找到最符合的参数来构造这个方程,也就是找到符合的                                              θ                            0                                       \theta_0                  θ0​ 和                                              θ                            1                                       \theta_1                  θ1​ 来使代价函数的值最小,也就是最符合实际情况。
一样平常来说通过梯度降落的方法来让参数不绝靠近最优解:
                                                    θ                               j                                    :                            =                                       θ                               j                                    −                            α                                       1                               m                                                 ∑                                           i                                  =                                  1                                          m                                    (                                       h                               θ                                    (                                       x                               i                                    )                            −                                       y                                           (                                  i                                  )                                                 )                                       x                               j                                           (                                  i                                  )                                                       \theta_j:= \theta_j - \alpha \frac{1}{m}\sum^m_{i = 1}(h_\theta(x^{i}) - y^{(i)})x_j^{(i)}                     θj​:=θj​−αm1​i=1∑m​(hθ​(xi)−y(i))xj(i)​
每次跟新都会根据代价函数来更改参数,代价函数在这里反应了与最优解的差距。而式中                                    α                              \alpha                  α 为学习率,也就是每次更新的幅度。学习率过大会导致降落大概会跳过最优解甚至导致当前值与最优解越来越远,太小会导致循环次数过多靠近最优解的速度太慢。
https://i-blog.csdnimg.cn/direct/f51ba39aca0847dc8b0586110eb8dbfe.png
   图 1 代建函数与两个参数的关系当然,在这里我们使用 python scikit-learn 库来构建线性回归模子,不需要完全读懂数学模子。只需要理解这个模子需要进行什么操作得到终极效果即可。
Sklearn 单变量线性回归

假设有一份食品供应商的数据,包罗了都会的生齿(population)和在这个都会的利润(profit),需要以生齿作为特征来猜测在某个都会的利润。
数据处理

假设数据保存在本地的 ex1data1.txt 中并以 csv 文件格式保存,那么需要起首用 pandas 读取数据。
import numpy as np
import pandas as pd

data = pd.read_csv('ex1data1.txt', header=none, names=['population', 'profit'])
print(data.head())
检察到数据的头部信息:
   population   profit
0      6.110117.5920
1      5.5277   9.1302
2      8.518613.6620
3      7.003211.8540
4      5.8598   6.8233
然后需要将特征和答案传入 Sklearn 线性回归模子,需要注意的是,这里是单变量回归,而一样平常的线性回归模子接受的参数是一个特征矩阵,那么这里需要将一维的特征向量转换成矩阵形式才行。
X = data['population'].values.reshape(-1, 1) # 重构特征的数据形状
y = data['profit'].values
构建模子

起首利用构造函数初始化一个线性回归模子对象 model ,然后利用现有的练习数据练习模子。
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X, y) # 输入训练数据训练模型
验证

从模子中取出终极练习后的参数:
slope = model.coef_
intercept = model.intercept_
print(f"Linear model equations: y = {slope:.2f}x + {intercept:.2f}")
检察终极的模子:
Linear model equations: y = 1.19x + -3.90
通过取出的参数来绘制图形,检察模子的拟合效果是否精良:
import matplotlib.pyplot as plt

data.plot(kind='scatter', x='population', y='profit', label='Data')
plt.plot(X, model.predict(X), color='red', label='Linear Fit')
plt.legend()
plt.show()
https://i-blog.csdnimg.cn/direct/edf8741a54124f819c798c1db281742e.png
   图 2 线性回归模子的拟合效果Sklearn 多变量线性回归

多变量回归模子的构建大同小异,也是一样的步骤。这里假设有数据 ex1data2.txt,数据包罗了房屋面积,卧室数量和房屋的价格,以前两者为特征来猜测房屋价格。
数据处理与练习

起首读取数据:
data = pd.read_csv('ex1data2.txt', header=None, names=['area', 'bedrooms', 'price'])
print(data.head())
   areabedrooms   price
02104         3399900
11600         3329900
22400         3369000
31416         2232000
43000         4539900
练习模子
X = data[['area', 'bedrooms']].values
y = data['price'].values

model = LinearRegression()
model.fit(X, y)
验证

检察练习后的模子的参数:
coefficients = model.coef_
intercept = model.intercept_

print(f"Linear model equation: y = {coefficients:.2f} * area + {coefficients:.2f} * bedrooms + {intercept:.2f}")

Linear model equation: y = 139.21 * area + -8738.02 * bedrooms + 89597.91
这里假如需要画图,则需要绘制一个三维图片,因为此处的特征是二维的。
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

ax.scatter(data['area'], data['bedrooms'], data['price'], color='blue')

area_range = np.linspace(data['area'].min(), data['area'].max(), 100)
bedrooms_range = np.linspace(data['bedrooms'].min(), data['bedrooms'].max(), 100)
area_grid, bedrooms_grid = np.meshgrid(area_range, bedrooms_range)

# 使用模型的预测方法
price_grid = model.predict(np.c_).reshape(area_grid.shape)

ax.plot_surface(area_grid, bedrooms_grid, price_grid, color='red', alpha=0.5, rstride=100, cstride=100)

ax.set_xlabel('Area')
ax.set_ylabel('Bedrooms')
ax.set_zlabel('Price')
ax.legend()
plt.show()
https://i-blog.csdnimg.cn/direct/8cb32f2a6c6e46789414af2d0eb81ab8.png
   图 3 多变量模子的拟合效果
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Sklearn 中的线性回归模子