欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

TensorFlow打印输出tensor的值

时间:2021-07-16 10:42:26|栏目:Python代码|点击:

在学习TensorFlow的过程中,我们需要知道某个tensor的值是什么,这个很重要,尤其是在debug的时候。也许你会说,这个很容易啊,直接print就可以了。其实不然,print只能打印输出shape的信息,而要打印输出tensor的值,需要借助class tf.Session, class tf.InteractiveSession。因为我们在建立graph的时候,只建立tensor的结构形状信息,并没有执行数据的操作。

一 class tf.Session 

运行tensorflow操作的类,其对象封装了执行操作对象和评估tensor数值的环境。这个我们之前介绍过,在定义好所有的数据结构和操作后,其最后运行。

import tensorflow as tf
 
# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# Launch the graph in a session.
sess = tf.Session()
# Evaluate the tensor `c`.
print(sess.run(c))

二 class tf.InteractiveSession

顾名思义,用于交互上下文的session,便于输出tensor的数值。与上一个Session相比,其有默认的session执行相关操作,比如:Tensor.eval(), Operation.run()。Tensor.eval()是执行这个tensor之前的所有操作,Operation.run()也同理。

import tensorflow as tf
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
with tf.Session():
 # We can also use 'c.eval()' here.
 print(c.eval())

打印输出张量的值的方法

import tensorflow as tf

zeros = tf.zeros([3,3])

# 方法1
with tf.Session():
 print(zeros.eval())

# 方法2
sess = tf.Session()
print(sess.run(zeros))

打印输出tensor变量的值的方法

import tensorflow as tf

ones=tf.Variable(tf.ones([3,3]))

# 方法1 InteractiveSession + initializer
inter_sess=tf.InteractiveSession()
ones.initializer.run()
print(inter_sess.run(ones))

# 方法2
inter_sess=tf.InteractiveSession()
tf.global_variables_initializer().run()
print(inter_sess.run(ones))

# 方法3 Session + global_variables_initializer
sess=tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(ones))

# 方法4 with Session + global_variables_initializer
with tf.Session() as sess:
 sess.run(tf.global_variables_initializer())
 print(sess.run(ones))

Reference:

[1] https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#InteractiveSession 

[2] http://stackoverflow.com/questions/33633370/how-to-print-the-value-of-a-tensor-object-in-tensorflow

上一篇:python 请求服务器的实现代码(http请求和https请求)

栏    目:Python代码

下一篇:python中列表的切片与修改知识点总结

本文标题:TensorFlow打印输出tensor的值

本文地址:http://www.codeinn.net/misctech/157906.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有