首页 > 解决方案 > 如何显示字典的值?

问题描述

我正在尝试为我的 ANN 实现创建一个每层重量的字典。

init_weight问题是,虽然我创建了以字符串为键、张量为值的字典,但我不知道在调用该方法时如何显示它们

def init_weights(topology):
#topology: dimensions of the network

for i in range(1,len(topology)):
parameters['W' + str(i)] = tf.Variable(tf.random_normal([topology[i-1],topology[i]]))

该方法的输出显示如下:

{'W1': <tf.Variable 'Variable_1:0' shape=(2, 5) dtype=float32_ref>,
 'W2': <tf.Variable 'Variable_3:0' shape=(5, 5) dtype=float32_ref>,
 'W3': <tf.Variable 'Variable_5:0' shape=(5, 5) dtype=float32_ref>,
 'W4': <tf.Variable 'Variable_7:0' shape=(5, 10) dtype=float32_ref>}

如何打印权重矩阵?

标签: pythondictionarytensorflowneural-network

解决方案


Tensorflow 是一个静态类型的框架(猜想这在 2.0 中有所改变)。这意味着,您首先构建一个静态图,并且该图仅在使用 Tf.Session() 运行时才具有值。现在回答你的问题。有两种方法可以得到你想要的。

  1. tf.enable_eager_execution()在脚本的开头添加。这将创建一个动态图(类似于 Pytorch)。您无需任何额外添加的相同代码将为您提供所需的内容。

  2. 将所有内容包装成 atf.Session()并运行它。你会得到权重矩阵


推荐阅读