源码如下,麻烦改下成金字塔的PYTHON代码:
import numpy as np importmatplotlib.pyplot as plt # 目标函数:y=x^2 def func(x): return np.square(x) # 目标函数一阶导数:dy/dx=2*x def dfunc(x): return 2 * x def GD_momentum(x_start,df, epochs, lr, momentum): """ 带有冲量的梯度下降法。 :param x_start: x的起始点 :param df: 目标函数的一阶导函数 :param epochs: 迭代周期 :param lr: 学习率 :param momentum: 冲量 :return: x在每次迭代后的位置(包括起始点),长度为epochs+1 """ xs = np.zeros(epochs+1) x = x_start xs[0] = x v = 0 for i in range(epochs): dx = df(x) # v表示x要改变的幅度 v = - dx * lr + momentum * v x += v xs[i+1] = x return xs
|