machine-learning - 如何在Python中将Alexnet的梯度存储为numpy数组(在每次迭代中)?

标签 machine-learning deep-learning tensorflow python gradient-descent

我想将模型的最终梯度向量存储为 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/

相关文章:

python - 如何向量化 scatter-matmul 运算

linux - 包装 python+keras+tensorflow 'as a service' 以接收来自 PHP 的预测请求?

c++ - 实现结构化张量

python - tensorflow keras RandomForestModel get_config() 为空

matlab - 在 MATLAB 中使用 PCA 和 scatter3 可视化大型监督学习数据集

machine-learning - 如何将不适合内存的巨大数据集拆分并加载到pytorch Dataloader中?

python - 目标编码 : Fill NaN generated in expanding mean encoded values

python - Tensorflow slim 训练和验证初始模型

machine-learning - 加载 doc2vec 的预训练 word2vec 模型

machine-learning - 神经网络中不同类别的不同权重以及学习后如何使用它们