TensorFlow:在图中使用张量作为列表参数

时间:2017-05-18 23:48:18

标签: python tensorflow

我想使用tf.Tensor作为TensorFlow图中另一个操作的类型(python)列表的参数。 换句话说,我想将Tensor用作另一个操作的动态列表参数。这可能吗?

可执行示例:

import tensorflow as tf
import numpy as np

graph = tf.Graph()
var1 = np.random.randn(2, 3)
var2 = np.random.randn(2, 3, 4)

with graph.as_default():
    def getRange(myTensor):
        myRank = tf.rank(myTensor)
        return tf.range(tf.constant(1), tf.squeeze(myRank))

    def getMoments(myTensor):
        myMoments = tf.nn.moments(myTensor, axes=getRange(myTensor))
        return myMoments
    var1tf = tf.Variable(var1)
    var2tf = tf.Variable(var2)
    var1moments = getMoments(var1tf)
    var2moments = getMoments(var2tf)
    rangeVar1 = getRange(var1tf)
    rangeVar2 = getRange(var2tf)
    init = tf.global_variables_initializer()

with tf.Session(graph=graph) as sess:
    sess.run([init])
    print(sess.run([rangeVar1])) # outputs [1], ok
    print(sess.run([rangeVar2])) # outputs [1, 2], ok
    print(sess.run([var1moments]))
    print(sess.run([var2moments]))

这引发:

raise TypeError("'Tensor' object is not iterable.")

1 个答案:

答案 0 :(得分:0)

我找到了一个使用get_shape()的解决方案:

def getMoments(myTensor):
    myRank = len(myTensor.get_shape().as_list())
    print('rank via shape:', myRank)
    myMoments = tf.nn.moments(myTensor, axes=list(range(1, myRank)))
    return myMoments