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()
|