首页 > 解决方案 > 如何在 Python 中将 Alexnet 的梯度存储为 numpy 数组(在每次迭代中)?

问题描述

我想将模型的最终梯度向量存储为 numpy 数组。使用 Tensorflow 是否有一种简单直观的方法来做到这一点?

我想为每次迭代存储 Alexnet 的梯度向量(在一个 numpy 数组中),直到收敛。

标签: machine-learningdeep-learningtensorflowpythongradient-descent

解决方案


我们可以按照下面的代码来做 -

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'>

推荐阅读