Cme*_*tin 6 python neural-network deep-learning tensorflow
我正在尝试为我正在实现的NN定义一个操作,但为了这样做,我需要迭代一个张量的维度.我在下面有一个小工作示例.
X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(X.get_shape()[0])]
Run Code Online (Sandbox Code Playgroud)
这会产生错误说明
ValueError: Cannot convert an unknown Dimension to a Tensor: ?
Run Code Online (Sandbox Code Playgroud)
使用相同的代码但使用tf.shape
相反的代码时,会导致代码存在
X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(tf.shape(X)[0])]
Run Code Online (Sandbox Code Playgroud)
给出以下错误
TypeError: 'Tensor' object is not iterable.
Run Code Online (Sandbox Code Playgroud)
我正在实现这个NN的方式,batch_size
直到训练函数(在代码末尾)才定义.这就是我自己构建图形的地方,因此在batch_size
这一点上是未知的,并且它无法修复,因为训练batch_size
和测试集batch_sizes是不同的.
解决这个问题的最佳方法是什么?这是保持我的代码运行的最后一件事,因为我让它运行一个固定的batch_size
,虽然这些结果没用.我一直在倾注TensorFlow API文档和堆栈溢出数周无济于事.
我也尝试将占位符输入到范围内,所以当我运行测试/训练集时,代码将是以下
X = tf.placeholder(tf.float32, shape=[None, 10])
bs = tf.placeholder(tf.int32)
def My_Function(X):
# Do some stuff to X
idx = [[i] for i in tf.range(bs)]
# return some tensor
A = tf.nn.relu(My_Function(X))
Run Code Online (Sandbox Code Playgroud)
但是,这会产生与上述相同的错误
TypeError: 'Tensor' object is not iterable.
Run Code Online (Sandbox Code Playgroud)
可能tf.map_fn
是您正在寻找的东西?
x = tf.placeholder(tf.float32, shape=[None, 10])
f = tf.map_fn(lambda y: y, x) # or perhaps something more useful than identity
Run Code Online (Sandbox Code Playgroud)
编辑
现在我更好地理解了,我认为问题在于您试图在创建图形时获取范围,而不是在运行图形时获取范围。
此外,您需要tf.range
在运行时查询形状。
In [2]: import numpy as np
...: import tensorflow as tf
...: x = tf.placeholder(tf.float32, shape=[None, 10])
...: sess = tf.InteractiveSession()
...: sess.run(tf.range(tf.shape(x)[0]), {x: np.zeros((7,10))})
Out[2]: array([0, 1, 2, 3, 4, 5, 6])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2891 次 |
最近记录: |