第一章主要是个导论,在里面介绍了个简单的利用机器学习预测房价的栗子:
数据预处理
- 导入相关的模块和包,主要是numpy、pandas和matplotlib.pyplot。
- 获取到两列关键的数据:size和price
- 将size标准化处理
- 标准化处理数学公式:
- 做出size和price的散点图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x, y = [], []
df = pd.read_csv("price.csv", encoding="gbk")
x_size = df["size"]
y_price = df["price"]
for _x, _y in zip(x_size, y_price):
x.append(_x)
y.append(_y)
x, y = np.array(x), np.array(y)
x = (x - x.mean()) / x.std()
plt.figure()
plt.scatter(x, y, c="r", s=50)
plt.show()
image.png
选择和训练模型
在对数据进行了预处理之后,需要选择相应的学习方法和训练模型,本栗子中通过线性回归
的多项式
来进行拟合,主要工作是编写模型函数
:
p,n
是 模型的参数;p
是多项式的系数;n
是多项式的次数- 损失函数采用常见的是
平方损失
(欧式距离或向量的二范数);损失函数为:
- 训练的过程就是正则化某个损失函数L的过程,使得损失函数
L
最小;有名的正规方程效果最好。
x0 = np.linspace(-2, 2, 500)
def get_model(n):
return lambda input_x=x0: np.polyval(np.polyfit(x, y, n), input_x)
- 其中
polyfit
函数返回的就是使得损失函数L最小的参数p,即多项式的系数p - 该函数
polyfit
就是模型F
的训练函数 polyval(p,x)
:根据多项式的x
和p
,返回多项式的值y
。
评估与可视化结果
模型建立好之后,需要通过尝试各种参数下判断模型的好坏,选择n=1,5,10
- 主要工作是编写损失函数
- 训练的目的:最小化损失函数
- 用
损失函数L
来衡量模型的好坏
def get_cost(n, input_x, input_y):
return 0.5 * ((get_model(n)(input_x) - input_y) ** 2).sum()
test_set = [1, 5, 10]
plt.scatter(x, y, c="g", s=20)
for d in test_set:
plt.plot(x0, get_model(d)(), label="deggree = {}".format(d))
plt.xlim(-2, 4)
plt.ylim(1e5, 6e5)
plt.legend()
plt.show()