tensorflow 中查看张量值的方法

本文介绍在TensorFlow中查看张量值的两种方法:使用tf.Session或tf.InteractiveSession类及tf.Print()函数。前者适用于构建完整的计算图,后者可在运行时插入打印语句,方便调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:aidazheng
原文地址:https://blog.youkuaiyun.com/aidazheng/article/details/78426368

在调试用TensorFlow编写的程序的时候,需要知道某个tensor的值是什么。直接print只能打印输出张量的shape,dtype等信息,而要查看张量的值的方法如下:

【1】用class tf.Session或 class tf.InteractiveSession类

import tensorflow as tf x = tf.Variable(tf.constant(0.1, shape = [10])) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(x.eval())

[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]

或者是这样 :


import tensorflow as tf x = tf.Variable(tf.constant(0.1, shape = [10])) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(sess.run(x))

[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]

就能显示了。

关于Session 和 InteractiveSession的区别,别人是这么总结的:tf.InteractiveSession():它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。这对于工作在交互式环境中的人们来说非常便利,比如使用IPython。

tf.Session():需要在启动session之前构建整个计算图,然后启动该计算图。

意思就是在我们使用tf.InteractiveSession()来构建会话的时候,我们可以先构建一个session然后再定义操作(operation),如果我们使用tf.Session()来构建会话我们需要在会话构建之前定义好全部的操作(operation)然后再构建会话。

【2】用tf.Print()函数

这篇博客写的比较明白了,给的例子也能用。http://blog.youkuaiyun.com/qq_34484472/article/details/75049179?locationNum=5&fps=1

首先给出函数说明:

tf.Print(input_, data, message=None,first_n=None, summarize=None, name=None)

打印张量列表

输入: input_:通过此op的一个tensor.

    data: 当此op被计算之后打印输出的tensorlist。

    message: 错误消息的前缀,是一个string。

    first_n: 只记录first_n次. 总是记录负数;这是个缺省.

    summarize: 对每个tensor只打印的条目数量。如果是None,对于每个输入   tensor只打印3个元素。

    name: op的名字.

返回:与input_相同的张量

例子:import tensorflow as tf sess = tf.InteractiveSession() a = tf.constant([1.0, 3.0]) sess.run(tf.Print(a, [a], message="This is a: "))

能得到打印结果。


import tensorflow as tf sess = tf.InteractiveSession() x = tf.Variable(tf.constant(0.1, shape = [10])) sess.run(x.initializer) sess.run(tf.Print(x, [x], message = 'This is x:'))

这段程序能打印我定义的x变量,但是如果我把tf.Print放在with tf.Session()中 就 不打印,但是也不报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值