【问题标题】:How to assign a tf.placeholder?如何分配 tf.placeholder?
【发布时间】:2019-08-02 09:46:43
【问题描述】:

我的英语很差。我会尽力澄清我的问题。

我的输入是多种多样的,[[1,2],[3,4]] 和 [[5,6],[7,8],[10,11]]。 我想要的输出是 [[1,0,2,0],[3,0,4,0]] 和 [[5,0,6,0],[7,0,8,0],[ 10,0,11,0]](表示在数字之间加零)

这是我的实现:

import tensorflow as tf
import numpy as np
matrix1=[[1,2],[3,4]]
matrix2 = [[5,6],[7,8],[10,11]]
with tf.Session() as sess:
   input = tf.placeholder(tf.float32, [None, 2])
   output=how_to_add(input)
   sess.run(tf.global_variables_initializer())
   [matrix3] = sess.run([output], feed_dict={input:matrix1})
   print(matrix3)

how_to_add的代码是:

def how_to_add(input):
    shape = input.get_shape().as_list()
    output=tf.Variable(tf.zeros(([shape[0],4))
    with tf.control_dependencies([output[:,1::2].assign(input) ]): 
        output = tf.identity(output)
    return output

但是shape[0]?,所以出现错误:

    "Cannot convert a partially known TensorShape to a Tensor: %s" % s)
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 4)

如何更正我的代码?

补充:

这些代码有效:

import tensorflow as tf
import numpy as np
matrix1=[[1,2],[3,4]]
matrix2 = [[5,6],[7,8],[10,11]]
with tf.Session() as sess:
   input = tf.placeholder(tf.float32, [2, 2]) #'None' is repalced with '2'
   output=how_to_add(input)
   sess.run(tf.global_variables_initializer())
   [matrix3] = sess.run([output], feed_dict={input:matrix1})
   print(matrix3)

how_to_add 的代码是:

def how_to_add(input):
    #shape = input.get_shape().as_list()
    output=tf.Variable(tf.zeros(([2,4)) # 'shape[0]' is replaced with '2'
    with tf.control_dependencies([output[:,1::2].assign(input) ]): 
        output = tf.identity(output)
    return output

虽然这些代码有效,但它们只能处理 matrix1 而不是 matrix2。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    不要为此使用变量,这不是他们的目的。您应该创建一个由输入张量制成的新张量。对于您的问题,您可以这样做:

    import tensorflow as tf
    
    def interleave_zero_columns(matrix):
        # Add a matrix of zeros along a new third dimension
        a = tf.stack([matrix, tf.zeros_like(matrix)], axis=2)
        # Reshape to interleave zeros across columns
        return tf.reshape(a, [tf.shape(matrix)[0], -1])
    
    # Test
    matrix1 = [[1, 2], [3, 4]]
    matrix2 = [[5, 6], [7, 8], [10, 11]]
    with tf.Session() as sess:
        input = tf.placeholder(tf.float32, [None, 2])
        output = interleave_zero_columns(input)
        print(sess.run(output, feed_dict={input: matrix1}))
        # [[1. 0. 2. 0.]
        #  [3. 0. 4. 0.]]
        print(sess.run(output, feed_dict={input: matrix2}))
        # [[ 5.  0.  6.  0.]
        #  [ 7.  0.  8.  0.]
        #  [10.  0. 11.  0.]]
    

    【讨论】:

    • 谢谢!我修改了您的代码以适应我的任务,并且它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2019-02-20
    • 2018-09-20
    • 2016-08-10
    相关资源
    最近更新 更多