tensorlow2.0中的常见优化器如下:

其中,adam是最常使用的,比如esmm论文中使用。
下面通过python实现几种常见的优化器。其中使用了tensorflow2.0 的tf.GradientTape来自动求微分。
数据集构造
build data
import tensorflow as tf
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
x = np.arange(-3, 7, 0.1)
y = np.array([0.5 * _ * _ - 2 * _ + 0.5 for _ in x])
sns.lineplot(x, y, markers=True, dashes=False)
plt.grid(True)

x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
SGD算法
- 计算损失函数(loss function, cost function)
- 计算损失函数关于模型参数θ\thetaθ的局部梯度【先求导数,然后带入点坐标】
- 沿着梯度方向进行下一次的迭代
- 知道梯度为0时,就达到了误差函数的最小值

在梯度下降中,一个最重要的参数就是学习率lr。
如果学习率太小,模型需要多次迭代才能达到最小值点,导致模型的训练时间变长;

如果学习率太大,模型在更新过程中,比较震荡,有可能会跳过最小值

# 损失函数
def sgd(a, b ,x, y, lr=0.001):
with tf.GradientTape(persistent=True) as t1, tf.GradientTape(persistent=True) as t2:
t1.watch(a)
t2.watch(b)
y_pred = tf.math.add(tf.math.multiply(a, tf.math.pow(x, 2)), tf.math.multiply(b, tf.math.pow(x, 1)))
loss = tf.keras.losses.MeanSquaredError()(y, y_pred)
dl_da = t1.gradient(loss, a)
dl_db = t2.gradient(loss, b)
a = a - lr * dl_da
b = b - lr * dl_db
return a, b
def train(x, y):
# 定义训练超参数
MAX_ITER = 500
TOL = 1e-5
# 初始化模型的参数值
a = tf.random.normal(shape = (1, ), dtype=tf.dtypes.float64)
b = tf.random.normal(shape = (1, ), dtype=tf.dtypes.float64)
cost_value_list = []
print('初始值为a={}, b={}'.format(a, b))
it = 0
patience = 0
while it < MAX_ITER:
y_pred = tf.math.add(tf.math.multiply(a, tf.math.pow(x, 2)), tf.math.multiply(b, tf.math.pow(x, 1)))
pre_cost = tf.keras.losses.MeanSquaredError()(y, y_pred)
a, b = sgd(a, b, x, y)
y_pred = tf.math.add(tf.math.multiply(a, tf.math.pow(x, 2)), tf.math.multiply(b, tf.math.pow(x, 1)))
post_cost = tf.keras.losses.MeanSquaredError()(y, y_pred)
cost_value_list.append(post_cost)
cost_delta = abs(pre_cost - post_cost)
if cost_delta < TOL:
patience += 1
if patience == 3:
break
it += 1
return a, b, cost_value_list
a, b, cost_list = train(x, y)
print('最终值为a={}, b={}'.format(a, b))
cost_list = [_.numpy() for _ in cost_list]
sns.lineplot(range(len(cost_list)), cost_list)
plt.grid(True)

动量优化Momentum
梯度下降算法的变量更行公式只是减去损失函数J(θ)J(\theta)J(

本文介绍了TensorFlow2.0中几种常见的优化算法实现,包括SGD(梯度下降)、Momentum(动量优化)、Adagrad(自适应学习率)、RMSProp(均方根传播)以及Adam(自适应矩估计)。通过Python代码展示了这些优化器的工作原理,并用实例说明它们在模型训练过程中的应用。每个优化器的实现都利用了tf.GradientTape进行自动求导,以适应不同场景下的参数更新策略。
最低0.47元/天 解锁文章
1266

被折叠的 条评论
为什么被折叠?



