TensorFlow `py_func` 的输出具有未知的等级/形状 [英] Output from TensorFlow `py_func` has unknown rank/shape

查看:31
本文介绍了TensorFlow `py_func` 的输出具有未知的等级/形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 TensorFlow 中创建一个简单的神经网络.唯一棘手的部分是我有一个使用 py_func 实现的自定义操作.当我将 py_func 的输出传递到 Dense 层时,TensorFlow 会抱怨排名应该是已知的.具体错误是:

I am trying to create a simple neural net in TensorFlow. The only tricky part is I have a custom operation that I have implemented with py_func. When I pass the output from py_func to a Dense layer, TensorFlow complains that the rank should be known. The specific error is:

ValueError: Inputs to `Dense` should have known rank.

当我通过 py_func 传递数据时,我不知道如何保留数据的形状.我的问题是如何获得正确的形状?我下面有一个简单的例子来说明这个问题.

I don't know how to preserve the shape of my data when I pass it through py_func. My question is how do I get the correct shape? I have a simple example below to illustrate the problem.

def my_func(x):
    return np.sinh(x).astype('float32')

inp = tf.convert_to_tensor(np.arange(5))
y = tf.py_func(my_func, [inp], tf.float32, False)

with tf.Session() as sess:
    with sess.as_default():
        print(inp.shape)
        print(inp.eval())
        print(y.shape)
        print(y.eval())

这个片段的输出是:

(5,)
[0 1 2 3 4]
<unknown>
[  0.       
1.17520118   3.62686038  10.01787472  27.28991699]

为什么是 y.shape ?我希望形状是 (5,)inp 相同.谢谢!

Why is y.shape <unknown>? I want the shape to be (5,) the same as inp. Thanks!

推荐答案

由于 py_func 可以执行任意 Python 代码并输出任何东西,TensorFlow 无法弄清楚形状(它需要分析 Python 代码函数体)您可以改为手动给出形状

Since py_func can execute arbitrary Python code and output anything, TensorFlow can't figure out the shape (it would require analyzing Python code of function body) You can instead give the shape manually

y.set_shape(inp.get_shape())

这篇关于TensorFlow `py_func` 的输出具有未知的等级/形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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