仅供测试,请忽略


import numpy as np
from decorator import append

x = np.array([1, 2, 1.2, 1.5])
y = x * 2 + np.random.randn()
print(('x是房屋面积'))
print(('y是房屋价格'))

# 绘制散点图
import matplotlib.pyplot as plt

plt.scatter(x, y)
plt.xlabel("house area")
plt.ylabel("house price")
plt.show()


# 定义误差函数
def mse(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)


# 定义梯度公式
def grad(y_true, w, x):
return np.mean(2 * (y_true - w * x)*(-x))


# 定义梯度下降迭代
def grad_decent(y_ture, w, x, learning_rate):
w = w - learning_rate * grad(y_ture, w, x)
return w


# 训练部分
w = np.random.rand()
learning_rate = 0.001
num_iteration = 100000
loss = []

for step in range(num_iteration):
w = grad_decent(y, w, x, learning_rate)
loss_step = mse(y, w * x)
loss.append(loss_step)


# 绘制迭代损失值图像
plt.figure()
plt.plot(loss)
plt.xlabel("iteration")
plt.ylabel("mse_loss")
plt.show()

# 绘制真实值与预测值图像
plt.figure()
plt.scatter(x,y,label = "ture",marker='s')
plt.scatter(x,w*x,label = "predict",marker='^')
plt.legend()
plt.show()