人工智能/模式识别/机器学习精华专题大数据,机器学习,人工智能呆鸟的Python数据分析

《Python与机器学习实战》——第一章

2019-08-04  本文已影响5人  皮皮大

第一章主要是个导论,在里面介绍了个简单的利用机器学习预测房价的栗子:

数据预处理

# 导入相关的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 定义两个列表用来存储输入数据和输出数据y
x, y = [], []

# 通过pandas分别获取两个列属性
df = pd.read_csv("price.csv", encoding="gbk")
x_size = df["size"]
y_price = df["price"]

# 利用zip函数
for  _x, _y in zip(x_size, y_price):
    x.append(_x)
    y.append(_y)

# for _x in x_size:
#     x.append(_x)
# for _y in y_price:
#     y.append(_y)

# 读取完后保存为Numpy的一维数组
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

选择和训练模型

在对数据进行了预处理之后,需要选择相应的学习方法和训练模型,本栗子中通过线性回归多项式来进行拟合,主要工作是编写模型函数

f(x|p;n) = p_0x^n + p_1x^{n-1} + ... + p_n

# 构造训练函数

# 区间作为作图的基础
x0 = np.linspace(-2, 2, 500)

# 参数n代表模型函数中的多项式次数
# 返回的模型能够根据输入的x,输出相对应的y
def get_model(n):
    return lambda input_x=x0: np.polyval(np.polyfit(x, y, n), input_x)

评估与可视化结果

模型建立好之后,需要通过尝试各种参数下判断模型的好坏,选择n=1,5,10

# 用损失函数衡量模型的好坏

# 根据输入的参数和x\y返回对应的损失函数
def get_cost(n, input_x, input_y):
    return 0.5 * ((get_model(n)(input_x) - input_y) ** 2).sum()   # 返回的就是损失函数L

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))
    # print(get_cost(d, x, y))

# 限制x,y的范围
plt.xlim(-2, 4)
plt.ylim(1e5, 6e5)

# 图例和显示 
plt.legend()
plt.show()
image.png
上一篇 下一篇

猜你喜欢

热点阅读