机器学习之房价预测程序

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x, y = [], []
for sample in open('D:/MLData/prices.txt',"r"):
# 遍历数据集 simple代表样本
    _x, _y = sample.split(',')
    x.append(float(_x))
    y.append(float(_y))
x, y = np.array(x), np.array(y)
x = (x - x.mean()) / x.std()
plt.figure()
plt.scatter(x, y, c='g', s=6)
# plt.show()

x0 = np.linspace(-2, 4,100)
def get_model(deg):
    return lambda input_x =x0:np.polyval(np.polyfit(x, y,deg),input_x)
# polyfit(x, y, deg):该函数返回使得损失函数中最小的参数p,即该函数是模型的训练函数
# polyval(p,x):根据多项式的各项系数p和多项式中x的值,返回多项式的值y
def get_cost(deg, input_x, input_y):
    return 0.5 * ((get_model(deg)(input_x) - input_y) ** 2).sum()
 # 定义设置各个参数n来查看线性回归的拟合情况,即寻找出最优的拟合函数
test_set = (1, 2, 3, 4, 10)
for d in test_set:
    print(get_cost(d, x, y))
plt.scatter(x, y, color='g', s=20)
for d in test_set:
    plt.plot(x0,get_model(d)(), label="degree={}".format(d))
plt.xlim(-2,4)
plt.ylim(1e5,8e5)
plt.title('房价预测')
# 将x控制在-2,4
plt.legend()
plt.show()

猜你喜欢

转载自blog.csdn.net/qq_40605167/article/details/81275273