python - tf.reshape 没有为第一个元素提供 ?(None)

标签 python python-3.x tensorflow

我是 tensorflow 的新手,我有如下的张量,

a = tf.constant([[1, 2, 3], [4, 5, 6]])
a.shape 的输出是

TensorShape([Dimension(2), Dimension(3)])



对于我的计算过程,我想将张量 reshape 为 (?, 2, 3)
我无法将其 reshape 为所需的格式。

我试过,
tf.reshape(a, [-1, 2, 3])

但它回来了,
<tf.Tensor 'Reshape_18:0' shape=(1, 2, 3) dtype=int32> # 1 has to be replaced by ?

我进一步尝试,
tf.reshape(a, [-1, -1, 2, 3])

它返回,
<tf.Tensor 'Reshape_19:0' shape=(?, ?, 2, 3) dtype=int32> # two ? are there

我怎样才能得到想要的结果?

对不起,如果这听起来很简单的问题。

最佳答案

“问题”是 TensorFlow 尽可能多地进行形状推断,这通常是件好事,但如果您明确想要 None,它会使事情变得更加复杂。方面。不是一个理想的解决方案,但一种可能的解决方法是使用 tf.placeholder_with_default ,例如像这样:

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
# This placeholder is never actually fed
z = tf.placeholder_with_default(tf.zeros([1, 1, 1], a.dtype), [None, 1, 1])
b = a + z
print(b)
# Tensor("add:0", shape=(?, 2, 3), dtype=int32)

或另一个类似的选项,只是 reshape :
import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]])
s = tf.placeholder_with_default([1, int(a.shape[0]), int(a.shape[1])], [3])
b = tf.reshape(a, s)
b.set_shape(tf.TensorShape([None]).concatenate(a.shape))
print(b)
# Tensor("Reshape:0", shape=(?, 2, 3), dtype=int32)

关于python - tf.reshape 没有为第一个元素提供 ?(None),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620552/

相关文章:

python - Python 中的方程解析

python - openAi-gym 名称错误

python - 如何在Python中将整数时间转换为时间对象

python - 如何使用 Python 启动应用程序实例?

python - 如何从上传文件中删除内容处置

python - 如何使fastapi中的查询参数接受两种类型的输入?

tensorflow - 将模型热加载到 tensorflow 服务容器中

python - 我可以将多个不同的图像作为 channel 吗?

python - 使用 keras 自定义层时构建错误

python - 这个返回或设置变量的代码可以变得更简单吗?