
# 收集数据,载入数据
from matplotlib import pyplot from regex import W import numpy def get_data(): x = numpy.linspace(-1, 1, 100) y = 4 * x**4 - 5 * x**3 + 3 * x**2 - 2 * x - 1 return x, y # x, y = get_data() # pyplot.scatter(x, y) # pyplot.show() # 创建模型/假设函数形式 def f(x): global W return W[0] * x**4 + W[1] * x**3 + W[2] * x**2 + W[3] * x + W[4] # W = numpy.ones(5) # yp = f(x) # pyplot.scatter(x, y) # pyplot.plot(x, yp) # pyplot.show() # 赋初值 # W = numpy.ones(5) # 计算误差 def loss(yp, y): return numpy.sum((yp - y) ** 2) # 计算梯度 def gradient_w(x, y, yp): global W g_w = numpy.zeros_like(W) for i in range(5): g_w[i] = 2 * numpy.sum((yp - y) * x ** (4 - i)) return g_w # 更新权重 # 循环迭代 def train(x, y, epochs, lr): global W w_list = [W] l_list = [] for epoch in range(epochs): yp = f(x) l = loss(yp, y) g_w = gradient_w(x, y, yp) W = W - lr * g_w w_list.append(W) l_list.append(l) return w_list, l_list x, y = get_data() W = numpy.ones(5) lr = 0.001 epochs = 500 w_list, l_list = train(x, y, epochs, lr) print(l_list[-1]) pyplot.plot(l_list) pyplot.show() for i, W in enumerate(w_list): yp = f(x) pyplot.cla() pyplot.scatter(x, y) pyplot.plot(x, yp, color="red") pyplot.title(f"{i}") pyplot.draw() pyplot.pause(0.1) pyplot.show()