[英]Is everything a Tensor in TensorFlow, including operations?
我一直在阅读关于核心图结构的文档,似乎对TensorFlow实际上做的和文档有什么不同(除非我有一个误解,我认为我这样做)。
文档说有Operation对象和Tensor对象 。 它提供了这样的例子,因此我尝试创建一些并询问python它们是什么类型。 首先让我们做一个常数:
c = tf.constant(1.0)
print c #Tensor("Const_1:0", shape=(), dtype=float32)
print type(c) #<class 'tensorflow.python.framework.ops.Tensor'>
它说它是一个Tensor。 大! 有意义,它甚至给我有关其内容的信息。
我做了一个与我期望的操作相同的实验:
W = tf.Variable(tf.truncated_normal([784, 10], mean=0.0, stddev=0.1))
b = tf.Variable(tf.constant(0.1, shape=[10]))
Wx = tf.matmul(x, W)
print Wx #Tensor("MatMul:0", shape=(?, 10), dtype=float32)
print type(Wx) #<class 'tensorflow.python.framework.ops.Tensor'>
但是,正如您所看到的,Tensor流表示Wx和c都是相同的类型。 这是否意味着没有操作对象或者我做错了什么?
tf.Varible是一个张量,然后你为它赋值,即一个操作,一个赋值操作。 或者你使用tf.mul(),这也是一个操作
有手术。 您可以通过graph.get_operations()
获取graph
中所有操作的列表(您可以通过tf.get_default_graph()
或sess.graph
或适合您情况的任何内容获取graph
)。
只是在Python中,像tf.mul
这样的东西tf.mul
返回乘法运算产生的张量(其他一切都会令人讨厌,因为它是你在进一步操作中用作输入的张量)。
我不是专家,但也许这会让事情变得清晰起来。
x = tf.constant(1, shape=[10, 10]) y = tf.constant(1, shape=[10, 10]) z = tf.matmul(x, y, name='operation') # print(z) # tf.Tensor 'operation:0' shape=(10, 10) dtype=int32 # z is a placeholder for the result of multiplication of x and y # but it has an operation attached to it # print(z.op) # tensorflow.python.framework.ops.Operation at 0x10bfe40f0 # and so do x and y # print(x.op) # ses = tf.InteractiveSession() # now that we are in a session, we have an operation graph ses.graph.get_operation_by_name('operation') # tensorflow.python.framework.ops.Operation at 0x10bfe40f0 # same operation that we saw attached to z ses.graph.get_operations() # shows a list of three operations, just as expected # this way you can define the graph first and then run all the operations in a session
我对TensorFlow不太熟悉,但它似乎是一个基本概念, Wx
是tf.matmul(x, W)
输出的符号句柄 。 所以你实际创建了一个Operation,但是访问Wx
会给你一个结果的表示(即使它在你运行一个会话之前没有计算)。
请查看TensorFlow常见问题解答以获取更详细的说明。
在tensorflow的上下文之外考虑这个,只是在基础python中。 假设你这样做:
def f(x):
return(x+1)
x = 0
print(type(x))
print(type(f(x)))
在这两种情况下你都得到int
,对吗? 但是如果你这样做会怎样
type(f)
在这种情况下,您将获得一个function
。 与tensorflow相同:操作结果的类型是新的张量,但操作本身的类型不是张量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.