机器学习练手(一):逻辑回归之乳腺癌分类、二手车售价

总结:本文为和鲸python 机器学习原理与实践·闯关训练营资料整理而来,加入了自己的理解(by GPT4o)

原活动链接

目录

总结 *:

关于案例1

关于机器学习算法的线性回归,如果是二分类且分类标签是0和1,预测结果默认是为1的概率,可以这样理解吗

是的,对于二分类问题,如果使用线性回归算法(具体来说是逻辑回归),并且分类标签是0和1,那么预测结果可以理解为属于类别1的概率。

具体来说,在逻辑回归中,模型通过一个线性函数(线性回归)计算出一个实数值,然后通过一个sigmoid函数(或逻辑函数)将该值转换为一个介于0和1之间的概率。这个概率可以解释为输入样本属于类别1的概率。数学上,可以表示为:

[ P(y=1|x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_n x_n)}} ]

其中:

  • ( P(y=1|x) ) 是样本 ( x ) 属于类别1的概率。
  • ( \beta_0, \beta_1, \beta_2, ..., \beta_n ) 是模型的参数(权重)。
  • ( x_1, x_2, ..., x_n ) 是输入特征。

如果这个概率大于0.5,通常我们会将样本分类为类别1;如果小于等于0.5,则分类为类别0。

因此,你的理解是正确的,线性回归在二分类问题中可以通过逻辑回归的方式,预测类别1的概率。

关于案例2

重点关注对于数据的处理,包括:

删除空值(删除前观察空值分布)

查看非数值型数据的分布,使用LabelEncoder()处理数据

查看各维度与预测值Price的相关性,并删除相关性较小的维度

之后再进行常规的模型构建

逻辑回归

在开始逻辑回归模型实践之前,我们先复习一下逻辑回归的相关算法原理

函数公式

逻辑回归的基本函数公式如下:

y = w * x + b  

上面函数公式内的字符含义如下:

  • x: 自变量,可以理解为不确定因素。
  • y: 因变量,可以理解为不确定因素导致的结果。
  • w: 影响自变量的权重,即不同的系数会导致不同的变化。
  • b: 影响因变量的权值,b 跟w 是不同的含义。

举个最简单的例子就是初中学过的一元二次方程,yx 成正比或反比取决于w 的正负,y在纵轴上 x=0 的位置取决于 b 的大小。

那么如何将上面的式子推广到用于解决实际的问题呢?

对于某个事件,说到底其结果无非是有限,而导致该结果的变化则可能是多种的,则会出现以下情况:

y = w1 * x1 + w2 * x2 + ... + b  

其中的 x 表示的对 y 结果产生影响的变量,而 w 则是该变量产生影响的程度大小。

优化算法

提出可以解决实际问题的函数之后,xy 都是已知的,那又该如何求解 w*b 呢? (w* 表示所有的w)

随机梯度下降算法。

那又该如何理解随机梯度下降算法呢?

举个最简单的例子,一个球从群山中下到最低的山底,如何确保怎么是最底呢?

那就是准备无数多个球从山顶放下去,总会有那么一个球能到达最低的山底。但现实不太靠谱,那是不是可以优化下,比如环视 10 米找到最低的地方滚下去,然后以此类推,就可以到达最低点。

总结前面的例子就是,对目标点出发,首先给出一个初始值 w*b,然后向着这个目标点不断计算 w*b求导 ),直至到达这个目标点,通过n 次的计算,直至 w*b 可以明确的表达 xy 之间的关系就完成计算。

乳腺癌诊断之分类问题

乳腺癌是全球妇女健康的主要威胁之一,早期发现和治疗对于提高患者生存率至关重要。传统的乳腺癌诊断方法存在一定的局限性,如依赖医生经验各项检测成本较高等。为了提高乳腺癌的诊断效率和准确性,计划开发一个基于机器学习的乳腺癌诊断模型,通过分析患者的细胞分析检查数据,实现对乳腺癌的提前诊断。该数据集为 sklearn 提供的示例数据集,其中有 569 例记录,包含编号细胞大小的均匀性细胞形状的均匀性上皮细胞大小正常核苷酸数量等特征。

乳腺癌数据集每列的含义如下:

特征列编号 特征含义
1 平均纹理
2 平均半径
3 中值周长
4 均值面积
5 平均平滑度
6 平均紧凑度
7 平均凹点
8 平均对称性
9 均值分形维数
10 半径错误
11 纹理错误
12 周长错误
13 面积错误
14 平滑度误差
15 紧凑度误差
16 凹度误差
17 凹点误差
18 对称误差
19 分形维数误差
20 最差半径
21 最大纹理
22 最差周长
23 最差面积
24 最低平滑度
25 最差紧凑性
26 最差凹度
27 最大凹点
28 最差对称性
29 最差分形维数

乳腺癌数据集结果表示如下:

结果 含义
1 患有乳腺癌
0 未患乳腺癌
引入依赖
python 复制代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.linear_model import LinearRegression
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, mean_squared_error
from sklearn.preprocessing import LabelEncoder
加载数据及基础分析
python 复制代码
# 获取数据

cancer = datasets.load_breast_cancer()
x = pd.DataFrame(cancer.data)
y = pd.DataFrame(cancer.target)
x.head(), y.head()
(      0      1       2       3        4        5       6        7       8   \
 0  17.99  10.38  122.80  1001.0  0.11840  0.27760  0.3001  0.14710  0.2419   
 1  20.57  17.77  132.90  1326.0  0.08474  0.07864  0.0869  0.07017  0.1812   
 2  19.69  21.25  130.00  1203.0  0.10960  0.15990  0.1974  0.12790  0.2069   
 3  11.42  20.38   77.58   386.1  0.14250  0.28390  0.2414  0.10520  0.2597   
 4  20.29  14.34  135.10  1297.0  0.10030  0.13280  0.1980  0.10430  0.1809   
 
         9   ...     20     21      22      23      24      25      26      27  \
 0  0.07871  ...  25.38  17.33  184.60  2019.0  0.1622  0.6656  0.7119  0.2654   
 1  0.05667  ...  24.99  23.41  158.80  1956.0  0.1238  0.1866  0.2416  0.1860   
 2  0.05999  ...  23.57  25.53  152.50  1709.0  0.1444  0.4245  0.4504  0.2430   
 3  0.09744  ...  14.91  26.50   98.87   567.7  0.2098  0.8663  0.6869  0.2575   
 4  0.05883  ...  22.54  16.67  152.20  1575.0  0.1374  0.2050  0.4000  0.1625   
 
        28       29  
 0  0.4601  0.11890  
 1  0.2750  0.08902  
 2  0.3613  0.08758  
 3  0.6638  0.17300  
 4  0.2364  0.07678  
 
 [5 rows x 30 columns],
    0
 0  0
 1  0
 2  0
 3  0
 4  0)
python 复制代码
x[x.index == 411]

| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

411 11.04 16.83 70.92 373.2 0.1077 0.07804 0.03046 0.0248 0.1714 0.0634 ... 12.41 26.44 79.93 471.4 0.1369 0.1482 0.1067 0.07431 0.2998 0.07881

1 rows × 30 columns

python 复制代码
# 数据基础分析

x.info(), y.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 569 entries, 0 to 568
Data columns (total 30 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   0       569 non-null    float64
 1   1       569 non-null    float64
 2   2       569 non-null    float64
 3   3       569 non-null    float64
 4   4       569 non-null    float64
 5   5       569 non-null    float64
 6   6       569 non-null    float64
 7   7       569 non-null    float64
 8   8       569 non-null    float64
 9   9       569 non-null    float64
 10  10      569 non-null    float64
 11  11      569 non-null    float64
 12  12      569 non-null    float64
 13  13      569 non-null    float64
 14  14      569 non-null    float64
 15  15      569 non-null    float64
 16  16      569 non-null    float64
 17  17      569 non-null    float64
 18  18      569 non-null    float64
 19  19      569 non-null    float64
 20  20      569 non-null    float64
 21  21      569 non-null    float64
 22  22      569 non-null    float64
 23  23      569 non-null    float64
 24  24      569 non-null    float64
 25  25      569 non-null    float64
 26  26      569 non-null    float64
 27  27      569 non-null    float64
 28  28      569 non-null    float64
 29  29      569 non-null    float64
dtypes: float64(30)
memory usage: 133.5 KB
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 569 entries, 0 to 568
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   0       569 non-null    int32
dtypes: int32(1)
memory usage: 2.3 KB





(None, None)
python 复制代码
x.describe().T, y.describe().T
(    count        mean         std         min         25%         50%  \
 0   569.0   14.127292    3.524049    6.981000   11.700000   13.370000   
 1   569.0   19.289649    4.301036    9.710000   16.170000   18.840000   
 2   569.0   91.969033   24.298981   43.790000   75.170000   86.240000   
 3   569.0  654.889104  351.914129  143.500000  420.300000  551.100000   
 4   569.0    0.096360    0.014064    0.052630    0.086370    0.095870   
 5   569.0    0.104341    0.052813    0.019380    0.064920    0.092630   
 6   569.0    0.088799    0.079720    0.000000    0.029560    0.061540   
 7   569.0    0.048919    0.038803    0.000000    0.020310    0.033500   
 8   569.0    0.181162    0.027414    0.106000    0.161900    0.179200   
 9   569.0    0.062798    0.007060    0.049960    0.057700    0.061540   
 10  569.0    0.405172    0.277313    0.111500    0.232400    0.324200   
 11  569.0    1.216853    0.551648    0.360200    0.833900    1.108000   
 12  569.0    2.866059    2.021855    0.757000    1.606000    2.287000   
 13  569.0   40.337079   45.491006    6.802000   17.850000   24.530000   
 14  569.0    0.007041    0.003003    0.001713    0.005169    0.006380   
 15  569.0    0.025478    0.017908    0.002252    0.013080    0.020450   
 16  569.0    0.031894    0.030186    0.000000    0.015090    0.025890   
 17  569.0    0.011796    0.006170    0.000000    0.007638    0.010930   
 18  569.0    0.020542    0.008266    0.007882    0.015160    0.018730   
 19  569.0    0.003795    0.002646    0.000895    0.002248    0.003187   
 20  569.0   16.269190    4.833242    7.930000   13.010000   14.970000   
 21  569.0   25.677223    6.146258   12.020000   21.080000   25.410000   
 22  569.0  107.261213   33.602542   50.410000   84.110000   97.660000   
 23  569.0  880.583128  569.356993  185.200000  515.300000  686.500000   
 24  569.0    0.132369    0.022832    0.071170    0.116600    0.131300   
 25  569.0    0.254265    0.157336    0.027290    0.147200    0.211900   
 26  569.0    0.272188    0.208624    0.000000    0.114500    0.226700   
 27  569.0    0.114606    0.065732    0.000000    0.064930    0.099930   
 28  569.0    0.290076    0.061867    0.156500    0.250400    0.282200   
 29  569.0    0.083946    0.018061    0.055040    0.071460    0.080040   
 
             75%         max  
 0     15.780000    28.11000  
 1     21.800000    39.28000  
 2    104.100000   188.50000  
 3    782.700000  2501.00000  
 4      0.105300     0.16340  
 5      0.130400     0.34540  
 6      0.130700     0.42680  
 7      0.074000     0.20120  
 8      0.195700     0.30400  
 9      0.066120     0.09744  
 10     0.478900     2.87300  
 11     1.474000     4.88500  
 12     3.357000    21.98000  
 13    45.190000   542.20000  
 14     0.008146     0.03113  
 15     0.032450     0.13540  
 16     0.042050     0.39600  
 17     0.014710     0.05279  
 18     0.023480     0.07895  
 19     0.004558     0.02984  
 20    18.790000    36.04000  
 21    29.720000    49.54000  
 22   125.400000   251.20000  
 23  1084.000000  4254.00000  
 24     0.146000     0.22260  
 25     0.339100     1.05800  
 26     0.382900     1.25200  
 27     0.161400     0.29100  
 28     0.317900     0.66380  
 29     0.092080     0.20750  ,
    count      mean       std  min  25%  50%  75%  max
 0  569.0  0.627417  0.483918  0.0  0.0  1.0  1.0  1.0)

在对数据经过初步分析之后,发现数据未出现缺失值(nan值或空字符串等),也不存在异常值(明显超出数据范围或与数据定义取值区间不符等)。

训练模型并计算指标
python 复制代码
# 模型训练

# 1. 拆分数据训练集和测试集,比例 7:3
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)
x_train.head(), x_test.head(), y_train.head(), y_test.head()
(        0      1      2      3        4        5        6        7       8   \
 149  13.74  17.91  88.12  585.0  0.07944  0.06376  0.02881  0.01329  0.1473   
 124  13.37  16.39  86.10  553.5  0.07115  0.07325  0.08092  0.02800  0.1422   
 421  14.69  13.98  98.22  656.1  0.10310  0.18360  0.14500  0.06300  0.2086   
 195  12.91  16.33  82.53  516.4  0.07941  0.05366  0.03873  0.02377  0.1829   
 545  13.62  23.23  87.19  573.2  0.09246  0.06747  0.02974  0.02443  0.1664   
 
           9   ...     20     21      22     23       24      25      26  \
 149  0.05580  ...  15.34  22.46   97.19  725.9  0.09711  0.1824  0.1564   
 124  0.05823  ...  14.26  22.75   91.99  632.1  0.10250  0.2531  0.3308   
 421  0.07406  ...  16.46  18.34  114.10  809.2  0.13120  0.3635  0.3219   
 195  0.05667  ...  13.88  22.00   90.81  600.6  0.10970  0.1506  0.1764   
 545  0.05801  ...  15.35  29.09   97.58  729.8  0.12160  0.1517  0.1049   
 
           27      28       29  
 149  0.06019  0.2350  0.07014  
 124  0.08978  0.2048  0.07628  
 421  0.11080  0.2827  0.09208  
 195  0.08235  0.3024  0.06949  
 545  0.07174  0.2642  0.06953  
 
 [5 rows x 30 columns],
         0      1       2       3        4       5        6        7       8   \
 204  12.47  18.60   81.09   481.9  0.09965  0.1058  0.08005  0.03821  0.1925   
 70   18.94  21.31  123.60  1130.0  0.09009  0.1029  0.10800  0.07951  0.1582   
 131  15.46  19.48  101.70   748.9  0.10920  0.1223  0.14660  0.08087  0.1931   
 431  12.40  17.68   81.47   467.8  0.10540  0.1316  0.07741  0.02799  0.1811   
 540  11.54  14.44   74.65   402.9  0.09984  0.1120  0.06737  0.02594  0.1818   
 
           9   ...     20     21      22      23      24      25      26  \
 204  0.06373  ...  14.97  24.64   96.05   677.9  0.1426  0.2378  0.2671   
 70   0.05461  ...  24.86  26.58  165.90  1866.0  0.1193  0.2336  0.2687   
 131  0.05796  ...  19.26  26.00  124.90  1156.0  0.1546  0.2394  0.3791   
 431  0.07102  ...  12.88  22.91   89.61   515.8  0.1450  0.2629  0.2403   
 540  0.06782  ...  12.26  19.68   78.78   457.8  0.1345  0.2118  0.1797   
 
           27      28       29  
 204  0.10150  0.3014  0.08750  
 70   0.17890  0.2551  0.06589  
 131  0.15140  0.2837  0.08019  
 431  0.07370  0.2556  0.09359  
 540  0.06918  0.2329  0.08134  
 
 [5 rows x 30 columns],
      0
 149  1
 124  1
 421  1
 195  1
 545  1,
      0
 204  1
 70   0
 131  0
 431  1
 540  1)
python 复制代码
# 2. 构建模型

model = LinearRegression()
python 复制代码
# 3. 训练模型

model.fit(x_train, y_train)
复制代码
LinearRegression()

In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

LinearRegression?Documentation for LinearRegressioniFitted

复制代码
LinearRegression()
python 复制代码
# 4. 使用测试集测试模型获取测试结果

y_pred = model.predict(x_test)
y_pred[:10]
# 此输出的是预测为1 的概率
array([[ 0.63641068],
       [ 0.19893156],
       [ 0.25993004],
       [ 1.1312271 ],
       [ 1.12862197],
       [-0.71286467],
       [-0.08514511],
       [ 0.40315066],
       [ 0.25276242],
       [ 0.95836231]])
python 复制代码
# 5. 计算指标

# mse 均方误差
# rmse 均方根误差
# 对于这两个指标,数值越小越好,因为它们衡量了模型预测值与真实值之间的差异,越小表示模型的预测越接近真实值
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
mse, rmse
(0.06728376859363167, 0.2593911497981989)
python 复制代码
# 输出模型的斜率、倾斜量和测试集的准确率

model.coef_, model.intercept_, model.score(x_test, y_test)
(array([[ 1.37372577e-01,  7.79428357e-03, -1.82105707e-02,
         -9.78666191e-05, -1.90315420e+00,  5.26086706e+00,
         -3.35439139e-01, -6.69106766e+00,  3.21568985e-01,
         -4.27164704e+00, -4.61122438e-01,  7.97442502e-02,
         -3.75583740e-03,  1.66070766e-03, -2.38396965e+01,
          2.29146524e+00,  4.20544140e+00, -1.97044602e+01,
          1.78524925e+00, -9.75990317e-01, -1.81809089e-01,
         -2.03391654e-02,  7.82072632e-03,  8.10744800e-04,
          1.29891730e+00, -8.91398060e-01, -8.93861181e-01,
          2.23179043e+00, -1.02916501e+00, -8.55319728e-01]]),
 array([3.01708661]),
 0.7108399944964163)
总结

在实际训练模型时,大部分花费的时间都在于如何处理数据上:特征归一化、空值处理、缺失值填充等,不过现在不需要处理这些,现在的主要目的在于学习如何训练模型以及评估模型指标。

二手车价格之回归问题

随着二手车市场的快速发展,如何准确评估二手车价格成为买卖双方关注的焦点。传统的定价方法存在效率低、主观性强、欺诈风险等问题。为了解决这一问题,计划开发一个基于机器学习的二手车交易售价预测模型,通过分析历史交易数据,实现对二手车价格的快速、准确评估。该数据集收集了 8015 例记录,其中包含车辆名称、行驶公里数、注册年份、品牌、燃油类型、变速箱、发动机功率等特征,本小结将从日常可收集到的数据预测其实际市场价格。

二手车数据集特征含义说明:

特征列名称 特征含义
Car Name 汽车品牌或汽车型号
Year Bought 购车年份
Distance 行驶里程 (单位:公里)
Owner 持有类型 '个人或机构'
Fuel 燃料类型 'petrol 汽油, diesel 柴油, CNG 压缩天然气, other 其他'
Location 车管所所在地
Drive 变速箱类型 'Automatic 自动, Manual 手动'
Type 车型 'Sedan 轿车, SUV SUV, HatchBack 两厢车, Lux_SUV 豪华SUV, Lux_sedan 豪华轿车'
Price 价格
加载数据
python 复制代码
# 读取数据

cars = pd.read_csv('./data/cars_24.csv', index_col='Index')
cars.head()

| | Car Name | Year | Distance | Owner | Fuel | Location | Drive | Type | Price |
| Index | | | | | | | | | |
| 0 | Maruti S PRESSO | 2022.0 | 3878 | 1 | PETROL | HR-98 | Manual | HatchBack | 514000 |
| 1 | Hyundai Xcent | 2018.0 | 32041 | 1 | PETROL | TN-22 | Manual | Sedan | 674000 |
| 2 | Tata Safari | 2021.0 | 96339 | 1 | DIESEL | TS-08 | Automatic | SUV | 1952000 |
| 3 | Maruti Vitara Brezza | 2019.0 | 51718 | 1 | DIESEL | WB-24 | Manual | SUV | 690000 |

4 Tata Tiago 2021.0 19811 1 PETROL HR-51 Manual HatchBack 526000
数据基础性分析
python 复制代码
# 数据基础分析

cars.info()

# 通过数据详情查看Car Name、Year 缺少 1 行,Location 缺少 213 行。
<class 'pandas.core.frame.DataFrame'>
Index: 8015 entries, 0 to 8014
Data columns (total 9 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Car Name  8014 non-null   object 
 1   Year      8014 non-null   float64
 2   Distance  8015 non-null   int64  
 3   Owner     8015 non-null   int64  
 4   Fuel      8015 non-null   object 
 5   Location  7802 non-null   object 
 6   Drive     8015 non-null   object 
 7   Type      8015 non-null   object 
 8   Price     8015 non-null   int64  
dtypes: float64(1), int64(3), object(5)
memory usage: 626.2+ KB
python 复制代码
# 删除所有空的数据

cars.dropna(inplace=True)
cars.info()
<class 'pandas.core.frame.DataFrame'>
Index: 7801 entries, 0 to 8014
Data columns (total 9 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Car Name  7801 non-null   object 
 1   Year      7801 non-null   float64
 2   Distance  7801 non-null   int64  
 3   Owner     7801 non-null   int64  
 4   Fuel      7801 non-null   object 
 5   Location  7801 non-null   object 
 6   Drive     7801 non-null   object 
 7   Type      7801 non-null   object 
 8   Price     7801 non-null   int64  
dtypes: float64(1), int64(3), object(5)
memory usage: 609.5+ KB
python 复制代码
cars.describe().T

| | count | mean | std | min | 25% | 50% | 75% | max |
| Year | 7801.0 | 2017.043584 | 2.847698 | 2010.0 | 2015.0 | 2017.0 | 2019.0 | 2023.0 |
| Distance | 7801.0 | 50936.111524 | 25866.884915 | 0.0 | 30198.0 | 49245.0 | 69981.0 | 153870.0 |
| Owner | 7801.0 | 1.298936 | 0.510013 | 1.0 | 1.0 | 1.0 | 2.0 | 4.0 |

Price 7801.0 578755.935137 266132.614326 119000.0 396000.0 538000.0 702000.0 3300000.0
python 复制代码
# 分类型数据查看分布

columns = ['Drive', 'Type', 'Fuel' , 'Location']
for col in columns:
    print('-'*30)
    print(cars[col].value_counts())
------------------------------
Drive
Manual       6271
Automatic    1530
Name: count, dtype: int64
------------------------------
Type
HatchBack    4952
Sedan        1557
SUV          1155
Lux_SUV        80
Lux_sedan      57
Name: count, dtype: int64
------------------------------
Fuel
PETROL    6199
DIESEL    1066
CNG        535
LPG          1
Name: count, dtype: int64
------------------------------
Location
MH-12    286
GJ-01    245
HR-26    228
KA-03    198
TS-07    189
        ... 
TS-27      1
HR-07      1
HR-27      1
TN-34      1
PB-46      1
Name: count, Length: 436, dtype: int64
训练模型并计算指标
python 复制代码
# 训练模型

# 1. 数据预处理

# 用来对分类型特征值进行编码,即对不连续的数值或文本进行编码
lb = LabelEncoder()
columns = ['Drive', 'Fuel', 'Type', 'Location']

for col in columns:
    cars[col] = lb.fit_transform(cars[col])
python 复制代码
cars.info()
<class 'pandas.core.frame.DataFrame'>
Index: 7801 entries, 0 to 8014
Data columns (total 9 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Car Name  7801 non-null   object 
 1   Year      7801 non-null   float64
 2   Distance  7801 non-null   int64  
 3   Owner     7801 non-null   int64  
 4   Fuel      7801 non-null   int32  
 5   Location  7801 non-null   int32  
 6   Drive     7801 non-null   int32  
 7   Type      7801 non-null   int32  
 8   Price     7801 non-null   int64  
dtypes: float64(1), int32(4), int64(3), object(1)
memory usage: 487.6+ KB
python 复制代码
# 2. 查看数据特征与结果之间的相关性

# 1. 选择数值型列
numeric_cols = cars.select_dtypes(include=[float, int]).columns

# 2. 计算相关性矩阵
correlation_matrix = cars[numeric_cols].corr()

# 3. 提取与 'Price' 列相关的相关性值
price_correlation = correlation_matrix['Price']

# 打印结果
print(price_correlation)
# print(cars.corr()['Price'])

# Car Name 与 Price 的相关性太小训练模型时可以删除该列
Year        0.496389
Distance   -0.195088
Owner      -0.151772
Fuel       -0.147064
Location    0.040065
Drive      -0.363527
Type        0.449268
Price       1.000000
Name: Price, dtype: float64
python 复制代码
# 3. 构建模型训练数据

y = cars['Price']
x = cars.drop(['Price', 'Car Name'], axis=1)
x.head(), y.head()
(         Year  Distance  Owner  Fuel  Location  Drive  Type
 Index                                                      
 0      2022.0      3878      1     3       102      1     0
 1      2018.0     32041      1     3       313      1     4
 2      2021.0     96339      1     1       368      0     3
 3      2019.0     51718      1     1       425      1     3
 4      2021.0     19811      1     3        90      1     0,
 Index
 0     514000
 1     674000
 2    1952000
 3     690000
 4     526000
 Name: Price, dtype: int64)
python 复制代码
# 4. 拆分数据训练集和测试集,比例 7:3

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)
x_train.head(), x_test.head(), y_train.head(), y_test.head()
(         Year  Distance  Owner  Fuel  Location  Drive  Type
 Index                                                      
 4036   2018.0     78356      1     1       304      0     4
 7773   2011.0     52946      2     3       156      1     0
 2215   2019.0     34284      1     0        31      1     0
 2719   2018.0     76611      1     3        42      0     4
 7671   2012.0     97763      2     3       103      1     0,
          Year  Distance  Owner  Fuel  Location  Drive  Type
 Index                                                      
 2170   2018.0     70968      1     3       105      1     4
 2136   2021.0     31793      1     1       105      0     3
 1109   2020.0     13150      1     3       202      1     4
 5551   2018.0     38995      3     3       103      1     3
 106    2014.0     63838      2     3       397      1     0,
 Index
 4036    942000
 7773    199650
 2215    533000
 2719    689000
 7671    425000
 Name: Price, dtype: int64,
 Index
 2170     617000
 2136    1295000
 1109     714350
 5551     631000
 106      281000
 Name: Price, dtype: int64)
python 复制代码
# 5. 构建模型

model_2 = LinearRegression()
python 复制代码
# 6. 训练模型

model_2.fit(x_train, y_train)
复制代码
LinearRegression()

In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

LinearRegression?Documentation for LinearRegressioniFitted

复制代码
LinearRegression()
python 复制代码
# 7. 预测测试集

y_pred = model_2.predict(x_test)
y_pred
array([ 709301.25445336, 1040053.77189565,  838302.19949879, ...,
        674032.59566195,  742026.31668977,  772885.15245588])
python 复制代码
# 8. 计算指标

mse = mean_squared_error(y_test, y_pred)
mse

# 从该指标可以看出,逻辑回归对于解决回归问题有一点有力无心。不过不要灰心!现阶段的重点在于了解模型、训练模型,后面会学习到如何解决该问题。
32537438119.812634

课后思考题

  1. 随机梯度算法为什么不是全局最优,而是当前最优?

闯关题

STEP1:请根据要求完成题目

Q1. 优化算法是基于什么进行计算?

A. 随机梯度下降算法。

B. 随机梯度上升算法。

C. 随机梯度算法。

Q2. 假如你在训练一个线性回归模型,有下面两句话:

如果数据量较少,容易发生过拟合。 如果假设空间较小,容易发生过拟合。

关于这两句话,下列说法正确的是? (过拟合是指模型在训练集上表现很好,但在测试集上却表现很差。即模型对训练集有点死记硬背的意思,对于测试集完全随机给出结果,泛化能力很差。)

A. 1 和 2 都错误

B. 1 正确,2 错误

C. 1 错误,2 正确

D. 1 和 2 都正确

关于这两句话的正确说法如下:

  1. 数据量较少,容易发生过拟合:

    • 正确。过拟合是指模型在训练数据上表现很好,但在测试数据上表现较差。这通常发生在模型记住了训练数据中的噪声或特定样本的情况下。如果数据量较少,模型可能会倾向于记住这些数据点,而不是学习到数据的整体规律,从而导致过拟合。
  2. 假设空间较小,容易发生过拟合:

    • 不正确。假设空间(hypothesis space)是指模型可能的参数和结构的集合。假设空间较小通常意味着模型的复杂度较低,模型能够表示的函数或关系的范围较小。假设空间较小会导致欠拟合(underfitting),因为模型可能无法捕捉到数据的复杂模式。过拟合通常发生在假设空间较大、模型复杂度较高的情况下,因为这样的模型更容易在训练数据上表现良好,但在新数据上表现不佳。

综上所述,只有第一句话是正确的,第二句话是不正确的。

Q3. 现在有一个病人的检测数据,根据已经训练的糖尿病模型预测其是否会患有乳腺癌?

(11.04, 16.83, 70.92, 373.2, 0.1077, 0.07804, 0.03046, 0.0248, 0.1714, 0.0634, 0.1967, 1.387, 1.342, 13.54, 0.005158, 0.009355, 0.01056, 0.007483, 0.01718, 0.002198, 12.41, 26.44, 79.93, 471.4, 0.1369, 0.1482, 0.1067, 0.07431, 0.2998, 0.07881)

A. 1(是)

B. 0(否)

python 复制代码
data_tmp = pd.DataFrame({0:11.04, 1:16.83, 2:70.92, 3:373.2, 4:0.1077, 5:0.07804, 6:0.03046, 7:0.0248, 8:0.1714, 9:0.0634, 10:0.1967, 11:1.387, 12:1.342, 13:13.54, 14:0.005158, 
                        15:0.009355, 16:0.01056, 17:0.007483, 18:0.01718, 19:0.002198, 20:12.41, 21:26.44, 22:79.93, 23:471.4, 24:0.1369, 25:0.1482, 26:0.1067, 
                        27:0.07431, 28:0.2998, 29:0.07881}, index=[0])
data_tmp

# 使用训练好的模型预测数据集

| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

0 11.04 16.83 70.92 373.2 0.1077 0.07804 0.03046 0.0248 0.1714 0.0634 ... 12.41 26.44 79.93 471.4 0.1369 0.1482 0.1067 0.07431 0.2998 0.07881

1 rows × 30 columns

python 复制代码
model.predict(data_tmp)
array([[0.965385]])
python 复制代码
#填入你的答案并运行,注意大小写
a1 = 'A'  # 如 a1= 'B'
a2 = 'B'  # 如 a2= 'B'
a3 = 'A'  # 如 a3= 'B'
相关推荐
y_dd1 小时前
【machine learning-12-多元线性回归】
算法·机器学习·线性回归
小魏冬琅1 小时前
K-means 算法的介绍与应用
算法·机器学习·kmeans
aWty_1 小时前
机器学习--K-Means
人工智能·机器学习·kmeans
wx7408513262 小时前
小琳AI课堂:机器学习
人工智能·机器学习
鸽芷咕3 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
qq_15321452643 小时前
【2023工业异常检测文献】SimpleNet
图像处理·人工智能·深度学习·神经网络·机器学习·计算机视觉·视觉检测
徳一4 小时前
【线性回归模型】
决策树·机器学习·线性回归
青椒大仙KI115 小时前
24/9/19 算法笔记 kaggle BankChurn数据分类
笔记·算法·分类
潮汐退涨月冷风霜6 小时前
机器学习之非监督学习(四)K-means 聚类算法
学习·算法·机器学习
LQS20206 小时前
机器学习与深度学习之间的区别
机器学习