machine-learning - 如何在 Python 中将 Alexnet 的梯度存储为 numpy 数组(在每次迭代中)?
问题描述
我想将模型的最终梯度向量存储为 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'>
推荐阅读
- ruby-on-rails - 在 Rails API 中使用局部变量或实例变量有什么区别?
- jquery - .insertBefore 创建重复项
- r - 基于行值的新列 - 更好的方法?
- width - Ext JS 如何设置文本域正文的最小宽度?
- excel - 通过单元格值引用工作表 - Excel
- c++ - 引发编译时错误
- node.js - 使用 node.js 和 react.js 客户端启动一个 firebase 功能项目
- reactjs - 向 Graphcool 电子邮件密码模板突变添加字段
- bootstrap-4 - 重新排序 Bootstrap 4 网格
- javascript - 绘图图表不适用于 JSON 数据 PHP