TensorFlow 初始化张量 [英] TensorFlow initializing Tensor of ones

查看:39
本文介绍了TensorFlow 初始化张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有一个张量

X = tf.placeholder("float", [None, 5])

这样我就知道列数而不是行数.我需要初始化一个维度为 nrows x 1

So that I know the number of columns but not the number of rows. I need to initialize a vector of ones of dimension nrows x 1

现在下面的代码块不起作用了,

Now the following block of code does not work,

o = tf.ones(shape=(tf.shape(X)[0], 1))
==> TypeError: List of Tensors when single Tensor expected

也没有,

o = tf.ones(shape=(X.get_shape()[0].value, 1))
==> TypeError: Input 'dims' of 'Fill' Op has type 
    string that does not match expected type of int32.

现在,我发现解决这个问题的一种方法是将我的向量作为占位符,

Now, I have found that one way to get around this is to actually make my vector of ones a placeholder,

o = tf.placeholder(dtype=tf.float32, shape=[None, 1])

并在我的 feed_dict 中传入一个大小合适的 numpy 数组.但是这个解决方案让我觉得不优雅,而不是占位符的预期用途.我在这里可能是错的,但肯定有更好的方法.

And to pass in a numpy array of ones of appropriate size in my feed_dict. But this solution strikes me as inelegant and not the intended use of a placeholder. I could be wrong here, but surely there's a better way.

推荐答案

解决你问题的方法是使用tf.pack操作:

The way to solve your problem is to use tf.pack operation:

o = tf.ones(shape=tf.pack([tf.shape(X)[0], 1]))

您出现错误的原因是 TensorFlow 形状应该是整数列表或张量 链接.tf.pack 可以轻松地将整数列表和/或 TensorFlow 标量转换为 Tensor 对象.

The reason you had errors is that TensorFlow shape is expected to be a list of integers or a tensor link. tf.pack makes it easy to convert a list of integers and/or TensorFlow scalars into a Tensor object.

这篇关于TensorFlow 初始化张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆