TensorFlow中的一切都是Tensor,包括操作吗?

问题描述 投票:3回答:5

我一直在阅读文档on core graph structures,似乎对TensorFlow实际上和文档有什么不同(除非我有误解,我认为我这样做)。

文档说有Operation objectsTensor objects。它提供了这样的例子,因此我尝试创建一些并询问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都是相同的类型。这是否意味着没有操作对象或者我做错了什么?

python tensorflow
5个回答
0
投票

tf.Variable是张量,然后为其赋值,即操作,赋值操作。或者你使用tf.mul(),这也是一个操作


0
投票

有手术。您可以通过graph.get_operations()获取图表中所有操作的列表(您可以通过graphtf.get_default_graph()获取sess.graph或适用于您的情况)。

只是在Python中,像tf.mul这样的东西会返回乘法运算产生的张量(其他一切都会令人烦恼,因为它是你在进一步操作中用作输入的张量)。


0
投票

我不是专家,但也许这会让事情变得清晰起来。

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

0
投票

我对TensorFlow不是很熟悉,但它似乎是一个基本概念,Wxtf.matmul(x, W)输出的象征性手柄。所以你实际创建了一个Operation,但是访问Wx会给你一个结果的表示(即使它在你运行一个会话之前没有计算)。

请查看TensorFlow FAQ以获得更详细的解释。


0
投票

在tensorflow的上下文之外考虑这个,只是在基础python中。假设你这样做:

def f(x):
    return(x+1)

x = 0

print(type(x))
print(type(f(x)))

在这两种情况下你都得到int,对吗?但是如果你这样做会怎样

type(f)

在这种情况下,你得到一个function。与tensorflow相同:操作结果的类型是新的张量,但操作本身的类型不是张量。

© www.soinside.com 2019 - 2024. All rights reserved.