简体   繁体   English

在张量流中将张量的形状作为数组

[英]get shape of tensor as array in tensorflow

I have a saved model from which I want the final weights that are applied in the final layer. 我有一个保存的模型,我希望从该模型中将最终权重应用于最终图层。 I have loaded the graph and know the where the tensor is but I can't get the shape of the tensor as an array. 我已经加载了图形并知道张量在哪里,但是我无法获得张量的形状作为数组。 I know the array has the shape 2048x6. 我知道数组的形状为2048x6。 How do I get the actual values like so 我如何获得这样的实际值
[[1,2,3],[1,2,3]...]. [[1,2,3],[1,2,3] ...]。 Thanks 谢谢

Here is my code 这是我的代码

import tensorflow as tf

saver = tf.train.import_meta_graph('_retrain_checkpoint.meta')
graph = tf.get_default_graph()

tensor = tf.get_default_graph().get_tensor_by_name("final_retrain_ops/weights/final_weights:0")

print(tensor)
print(tf.TensorShape(tensor.get_shape()).as_list()




>>>Tensor("final_retrain_ops/weights/final_weights:0", shape=(2048, 6), dtype=float32_ref)
>>>(2048, 6)

To print the values of the weight tensor, you can do the following: 要打印重量张量的值,可以执行以下操作:

with tf.Session() as sess:
    print( sess.run( tensor ) )

sess.run() evaluates the tensor(s) in it argument, which here just means it will print the values. sess.run() 计算其参数中的张量,这仅表示它将打印值。

There is a bit of an issue, however, that your code only loads the structure of the graph ( tf.train.import_meta_graph('_retrain_checkpoint.meta') ), not the pretrained values. 但是,您的代码仅加载图的结构( tf.train.import_meta_graph('_retrain_checkpoint.meta') ),而不是预训练的值,这是一个问题。 Therefore you get the error that you're trying to use uninitialized values. 因此,您会收到错误消息,您尝试使用未初始化的值。

You need to have something like: 您需要具有以下内容:

saver.restore(sess,tf.train.latest_checkpoint('./'))

to load it, right after sess has been defined, and of course, you need to point to the correct checkpoint directory instead of ./ . 要在sess定义之后立即加载它,当然,您需要指向正确的检查点目录而不是./

So something like this: 所以像这样:

with tf.Session() as sess:
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    print( sess.run( tensor ) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM