首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何分配tf.placeholder?

如何分配tf.placeholder?
EN

Stack Overflow用户
提问于 2019-08-02 09:46:43
回答 1查看 58关注 0票数 1

我英语不太好。我会尽力澄清我的问题。

我的投入是多种多样的,[1,2,3,4]和[5,6,7,8,10,11]。我想要的输出是[1,0,2,0,3,0,4,0,0]和[5,0,6,0],[7,0,8,0],[10,0,11,0]

以下是我的建议:

代码语言:javascript
复制
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的代码是:

代码语言:javascript
复制
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]?,所以我得到了一个错误:

代码语言:javascript
复制
    "Cannot convert a partially known TensorShape to a Tensor: %s" % s)
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 4)

如何纠正我的密码?

补充:

这些守则适用于:

代码语言:javascript
复制
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的代码是:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-02 11:26:40

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

代码语言:javascript
复制
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.]]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57323936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档