- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
前言
- 机器学习是深度学习和数据分析的基础,接下来将更新常见的机器学习算法
- 注意:在打数学建模比赛中,机器学习用的也很多,可以一起学习
- 欢迎收藏 + 点赞 + 关注
文章目录
1、基础概念简介
1、什么是回归?
- 回归的目的是预测,如我们高中学过的最小二乘回归,通过自变量(X)预测因变量(Y)。
- 回归之所以能预测,是因为它通过大量的自变量(X)去拟合因变量(Y),寻找他们之间的线性关系。
2、什么是线性
- 线性关系就是可以用一个线性方程来表示(通过一个或者多个变量来表示另外一个变量)
- 如图一个最简单的一元线性回归:
 
3、什么是线性回归?
一句话概括就是:通两个或者多个变量来预测结果
4、西瓜书中回归表达式
给定由d个属性描述的示例 x = ( x 1 ; x 2 ; ... ; x d ) \boldsymbol{x}=(x_1;x_2;\ldots;x_d) x=(x1;x2;...;xd) ,其中心是x在第i个属性上的取值,线性模型(linear model)试图学得一个通过属性的线性组合来进行预测的函数,即
 
向量表达式为:
 f ( x ) = w T x + b , ‾ \underline{f(\boldsymbol{x})=\boldsymbol{w}^\mathrm{T}\boldsymbol{x}+b ,} f(x)=wTx+b,
线性回归的求解就是解 w \boldsymbol{w} w 和 b参数
2、一元线性回归
1、表达式
 f ( x ) = w x + b f(x)=wx+b f(x)=wx+b
- w w w在高中学习中叫做斜率,b叫做截距,但是,在机器学习中 w w w叫做权重,b叫做偏置
- 回归问题的求解就是求解 w \boldsymbol{w} w 和 b参数
2、案例求解
以一个成绩预测为例,步骤为:
- 导入库和数据
- 数据预处理
- 创建简单线性回归模型
- 预测结果
- 误差分析
- 模型展示
1、导入库
            
            
              python
              
              
            
          
          import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
data = pd.read_csv("./studentscores.csv")
data|    | Hours | Scores |
| 0  |  2.5  |   21   |
| 1  |  5.1  |   47   |
| 2  |  3.2  |   27   |
| 3  |  8.5  |   75   |
| 4  |  3.5  |   30   |
| 5  |  1.5  |   20   |
| 6  |  9.2  |   88   |
| 7  |  5.5  |   60   |
| 8  |  8.3  |   81   |
| 9  |  2.7  |   25   |
| 10 |  7.7  |   85   |
| 11 |  5.9  |   62   |
| 12 |  4.5  |   41   |
| 13 |  3.3  |   42   |
| 14 |  1.1  |   17   |
| 15 |  8.9  |   95   |
| 16 |  2.5  |   30   |
| 17 |  1.9  |   24   |
| 18 |  6.1  |   67   |
| 19 |  7.4  |   69   |
| 20 |  2.7  |   30   |
| 21 |  4.8  |   54   |
| 22 |  3.8  |   35   |
| 23 |  6.9  |   76   |
| 24 |  7.8  |   86   |
| 25 |  9.1  |   93   |
| 26 |  9.2  |   93   |
| 27 | 9.5 | 93 | 
|---|
2、数据预处理
            
            
              python
              
              
            
          
          # 获取数据和数据划分
from sklearn.model_selection import train_test_split
x = data.iloc[:, :1].values   # data.iloc[:, 1] 与 data.iloc[:, :1] 的区别,前者返回一维数组,后者返回二维数组
y = data.iloc[:, 1].values 
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)3、创建简单的线性回归模型
            
            
              python
              
              
            
          
          from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train)  # 模型拟合4、预测结果
            
            
              python
              
              
            
          
          y_pred =  model.predict(x_test)
y_pred结果:
array([29.72354202, 91.35223136, 83.64864519, 49.94545571, 27.79764548,
       47.0566109 , 22.01995585])5、误差分析
            
            
              python
              
              
            
          
          from sklearn.metrics import mean_squared_error 
mse = mean_squared_error(y_test, y_pred)  # 计算均分误差,回归最常用的评价指标
print(mse)结果:
19.327533697713523    结合成绩数据,误差还可以,想要更直观,可以先对数据进行标准化
6、模型展示
            
            
              python
              
              
            
          
          from matplotlib import rcParams
# 设置字体为SimHei显示中文
rcParams['font.family'] = 'SimHei'
# 创建画布
plt.figure(figsize=(12, 3))
# 创建子图
plt.subplot(1, 2, 1)
plt.scatter(x_train, y_train, color='red')
plt.plot(x_train, model.predict(x_train), label='训练集拟合', color='blue')
plt.title('训练集拟合')
# 创建子图
plt.subplot(1, 2, 2)
plt.scatter(x_test, y_test, color='red')
plt.plot(x_test, model.predict(x_test), label='测试集拟合', color='blue')
plt.title('测试集拟合')
plt.show()
3、多元线性回归
1、表达式
 
- 多元线性回归:影响Y的因素不唯一,有多个
- 一元线性回归:影响Y的因素唯一,只有一个
2、案例求解
鸢尾花数据集,预测花瓣长度
- 因变量Y:花瓣宽度
- 自变量X:花萼长度,花萼宽度,花瓣长度
1、数据预处理
1、导入数据集
            
            
              python
              
              
            
          
          import numpy as np 
import pandas as pd 
# 网络下载 鸢尾花 数据集合
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
name = ['花萼-length', '花萼-widget', '花瓣-length', '花瓣-widget', 'class']
data = pd.read_csv(url, names=name)
data.dataframe tbody tr th {
    vertical-align: top;
}
.dataframe thead th {
    text-align: right;
}|     | 花萼-length | 花萼-widget | 花瓣-length | 花瓣-widget |     class      |
|  0  |    5.1    |    3.5    |    1.4    |    0.2    |  Iris-setosa   |
|  1  |    4.9    |    3.0    |    1.4    |    0.2    |  Iris-setosa   |
|  2  |    4.7    |    3.2    |    1.3    |    0.2    |  Iris-setosa   |
|  3  |    4.6    |    3.1    |    1.5    |    0.2    |  Iris-setosa   |
|  4  |    5.0    |    3.6    |    1.4    |    0.2    |  Iris-setosa   |
| ... |    ...    |    ...    |    ...    |    ...    |      ...       |
| 145 |    6.7    |    3.0    |    5.2    |    2.3    | Iris-virginica |
| 146 |    6.3    |    2.5    |    5.0    |    1.9    | Iris-virginica |
| 147 |    6.5    |    3.0    |    5.2    |    2.0    | Iris-virginica |
| 148 |    6.2    |    3.4    |    5.4    |    2.3    | Iris-virginica |
| 149 | 5.9 | 3.0 | 5.1 | 1.8 | Iris-virginica | 
|---|
150 rows × 5 columns
2、数据分析
            
            
              python
              
              
            
          
          # 展示 不同 变量 对花瓣宽度的影响长度
import matplotlib.pyplot as plt 
plt.plot(data['花萼-length'], data['花瓣-widget'], 'x', label="marker='x'")
plt.plot(data['花萼-widget'], data['花瓣-widget'], 'o', label="marker='o'")
plt.plot(data['花瓣-length'], data['花瓣-widget'], 'v', label="marker='v'")
plt.legend()
plt.show()

通过观察发现:没有聚类特征,各变量之间没有什么关系,没有什么规律可言
3、划分测试集和训练集
            
            
              python
              
              
            
          
          from sklearn.model_selection import train_test_split
X = data.iloc[:, :2].values
y = data.iloc[:, 3].values
# 训练集:0.8,测试集:0.2
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 4、数据标准化
            
            
              python
              
              
            
          
          from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train_scaler = scaler.fit_transform(X_train)
X_test_sacler = scaler.transform(X_test)2、模型创建和训练
            
            
              python
              
              
            
          
          from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train_scaler, y_train)3、模型预测
            
            
              python
              
              
            
          
          y_pred = model.predict(X_test_sacler)4、误差计算
            
            
              python
              
              
            
          
          # 采用均方根误差计算
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y_pred, y_test)
print("mse", mse)mse 0.122909925062170095、结果图示
            
            
              python
              
              
            
          
          # 展示预测值和真实值分布
plt.scatter(y_test,y_pred, color='red')
plt.xlabel("Prediction")
plt.ylabel("True");
plt.show()
