我想将模型的最终梯度向量存储为 numpy 数组。有没有一种简单直观的方法可以使用 Tensorflow 来做到这一点?
我想为每次迭代存储 Alexnet 的梯度向量(在 numpy 数组中),直到收敛。
最佳答案
我们可以按照下面的代码来做到这一点 -
import tensorflow as tf
import numpy as np
print(tf.__version__)
#Define the input tensor
x = tf.constant([3.0,6.0,9.0])
#Define the Gradient Function
with tf.GradientTape() as g:
g.watch(x)
y = x * x
dy_dx = g.gradient(y, x)
#Output Gradient Tensor
print("Output Gradient Tensor:",dy_dx)
#Convert to array
a = np.asarray(dy_dx)
print("Gradient array:",a)
print("Array shape:",a.shape)
print("Output type:",type(a))
代码的输出是-
2.1.0
Output Gradient Tensor: tf.Tensor([ 6. 12. 18.], shape=(3,), dtype=float32)
Gradient array: [ 6. 12. 18.]
Array shape: (3,)
Output type: <class 'numpy.ndarray'>
关于machine-learning - 如何在Python中将Alexnet的梯度存储为numpy数组(在每次迭代中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60557095/