问题描述
我有一个与 TensorFlow
相关的非常技术性的问题.
I have a very technical question related to TensorFlow
.
我有一个尺寸为(None,2)
的 TensorFlow矩阵
.我只需要在矩阵的维度0(即所有行)上应用一个函数,例如some_function.问题是维度0是None类型(它是动态的,因为它取决于输入到 NN模型
的输入大小),并且给出错误,显示None为不是整数类型.有两个 tf函数
: tf.map_fn
和 tf.scan
可以遍历 Tensorflow数组
.但两者都无法在无"维度上使用.
I have a TensorFlow matrix
having a dimension of (None, 2)
. I need to apply a function, say some_function, only on Dimension 0 of the matrix i.e. over all rows. The issue is dimension 0 is a None type (it is dynamic as it depends on the input size being fed to the NN model
), and it gives an error showing None is not an integer type. There are two tf functions
: tf.map_fn
and tf.scan
to iterate over a Tensorflow array
. But both won't work over a None dimension.
也许您可以通过定义形状为(None,2)
的测试TensorFlow数组并尝试将任何测试函数应用于第一维来对其进行检查.任何帮助/输入将不胜感激!
Maybe you could check it by defining a test TensorFlow array of shape (None, 2)
and try applying any test function to the first dimension. Any help/input would be appreciated!
推荐答案
由于这是keras模型的输出,如果我尝试执行以下操作,
Since this is a keras model output, if I try to do the following,
res2 = tf.map_fn(lambda y: y*2, model.output)
你明白了,
但是,以下方法会起作用,
But, the following would work,
# Inital model that produces the output you want to map
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(2, input_shape=(2,)))
res = tf.keras.layers.Lambda(lambda x: tf.map_fn(lambda y: y*2, x))(model.output)
然后,您定义一个新模型,并使用该模型获取 tf.map_fn
的结果.
Then you define a new model, and use that to get the result of the tf.map_fn
.
model2 = tf.keras.Model(inputs=model.inputs, outputs=res)
print(model2.predict(np.array([[1,2],[3,4]])))
PS :但这与第一个维度为 None
无任何关系. tf.map_fn
可以处理 None
维度.您可以通过在TF 1.x中的 tf.placeholder([None,2])
上运行 tf.map_fn
来验证这一点.
PS: But this is nothing to do with the first dimension being None
. tf.map_fn
can deal with None
dimension just fine. You can verify this by running tf.map_fn
on a tf.placeholder([None,2])
in TF 1.x.
因为它是在那个维度上迭代地应用函数,并且不需要知道大小.
Because it is iteratively applying a function over that dimension and does not need to know the size to do so.
这篇关于有没有一种方法可以将函数应用于形状为(None,2)的张量流数组的维度0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!