Tensorflow实现自动求梯度

自动求梯度

在深度学习中,我们经常需要对函数求梯度(gradient)。在tensorflow2.0中可以使用GradientTape来自动求梯度。

1.简单示例

简单例子:对函数 y = 2 x T x y = 2x^Tx y=2xTx求关于列向量 x x x的梯度。

x = tf.reshape(tf.Variable(range(4), dtype=tf.float32), (4, 1))
x

输出结果:

<tf.Tensor: id=10, shape=(4, 1), dtype=float32, numpy=
array([[0.],
       [1.],
       [2.],
       [3.]], dtype=float32)>

函数 y = 2 x T x y = 2x^Tx y=2xTx关于 x x x的梯度应该为 4 x 4x 4x
tensorflow中实现求梯度:

with tf.GradientTape() as t:
	t.watch(x)
	y = 2 * tf.matmul(tf.transpose(x), x)
dy_dx = t.gradient(y, x)
dy_dx

输出结果:

<tf.Tensor: id=30, shape=(4, 1), dtype=float32, numpy=
array([[ 0.],
       [ 4.],
       [ 8.],
       [12.]], dtype=float32)>

2.训练模式和预测模式

with tf.GradientTape(persistent=True) as g:
	g.watch(x)
	y = x * x
	z = y * y
	dz_dx = g.gradient(z, x)
	dy_dx = g.gradient(y, x)
dz_dx, dy_dz

输出结果:

WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.
WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.

(<tf.Tensor: id=41, shape=(4, 1), dtype=float32, numpy=
 array([[  0.],
        [  4.],
        [ 32.],
        [108.]], dtype=float32)>,
 <tf.Tensor: id=47, shape=(4, 1), dtype=float32, numpy=
 array([[0.],
        [2.],
        [4.],
        [6.]], dtype=float32)>)

3.对python控制流求梯度

即使函数的计算图包含了Python的控制流(如条件和循环控制),我们也有可能对变量求梯度。
这里我也没看懂,就不放代码了。需要的同学请点击原文链接查看

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用TensorFlow 2.0实现梯度下降的示例代码: ``` import tensorflow as tf # 定义训练数据 x_train = [1.0, 2.0, 3.0, 4.0] y_train = [2.0, 4.0, 6.0, 8.0] # 定义模型参数 W = tf.Variable(1.0) b = tf.Variable(1.0) # 定义模型 def model(x): return W * x + b # 定义损失函数 def loss(predicted_y, desired_y): return tf.reduce_mean(tf.square(predicted_y - desired_y)) # 定义训练函数 def train(x, y, learning_rate): with tf.GradientTape() as t: current_loss = loss(model(x), y) dW, db = t.gradient(current_loss, [W, b]) W.assign_sub(learning_rate * dW) b.assign_sub(learning_rate * db) # 训练模型 for epoch in range(100): for x, y in zip(x_train, y_train): train(x, y, learning_rate=0.01) current_loss = loss(model(x_train), y_train) print(f"Epoch {epoch}: Loss: {current_loss.numpy()}") # 测试模型 x_test = [5.0, 6.0, 7.0, 8.0] y_test = [10.0, 12.0, 14.0, 16.0] predicted_y = model(x_test) print(f"Predicted Y: {predicted_y.numpy()}") print(f"Desired Y: {y_test}") ``` 在这个例子中,我们使用TensorFlow 2.0实现了一个简单的线性回归模型,并使用梯度下降算法对其进行了训练。我们首先定义了训练数据,然后定义了模型参数W和b。接下来,我们定义了模型函数,它将输入x映射到输出y。然后,我们定义了损失函数,它将模型的预测输出y与真实输出y进行比较,并计算它们之间的平方差。最后,我们定义了一个训练函数,它使用梯度自动计算模型参数W和b的梯度,并使用学习率更新它们。在训练过程中,我们迭代地将训练数据馈送给训练函数,直到达到指定的训练轮数。最后,我们使用训练好的模型对测试数据进行预测,并将预测结果与真实结果进行比较。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值