python - 如何将稀疏张量传递给 TF 2.0 中的密集层?
问题描述
我正在使用 TF 2.0。
在职的:
from tensorflow.keras import layers
inputs = layers.Input(shape=(256,), sparse=False, name='name_sparse')
x = layers.Dense(32, name="my_layer")(inputs)
print(x)
输出:Tensor("my_layer/Identity:0", shape=(None, 32), dtype=float32)
不工作:
如果我在上面的代码中将稀疏True
更改为,输出将更改为:
ValueError: The last dimension of the inputs to Dense should be defined. Found None.
如何将稀疏张量传递给 TF2.0 中的 Dense 层。它在 TF1.14 中运行良好。
解决方案
发生这种情况是因为当输入张量是稀疏形状时,此张量的计算(None,None)
结果为(256,)
inputs = layers.Input(shape=(256,), sparse=True, name='name_sparse')
print(inputs.shape)
# output: (?, ?)
这似乎也是一个悬而未决的问题。
一种解决方案是编写自定义层子类化层类(请参阅this)。
作为一种解决方法(在 tf-gpu 2.0.0 上测试)在输入层中添加批量大小可以正常工作:
from tensorflow.keras import layers
inputs = layers.Input(shape=(256,), sparse=True, name='name_sparse', batch_size=32)
print(inputs.shape) # (32, 256)
x = layers.Dense(32, name="my_layer")(inputs)
print(x) # Tensor("my_layer_10/BiasAdd:0", shape=(32, 32), dtype=float32)
推荐阅读
- powershell - How can I use a script to keep a remote computer from sleep mode?
- javascript - 如何在 WordPress 中使用 JavaScript 和 HTML 添加第三方门户?
- php - substr_replace 不替换西里尔文
- velo - How to make http request using wix?
- .net - Azure VM Server IIS 10 500.19 内部错误,尝试了之前帖子中给出的所有解决方案
- javascript - 我需要使用来自 HTML 表单的字符串输入将其发送到 Node.js/Exress 服务器
- android - 应用程序在启动前停止工作,没有例外(adb 设备)
- python - 无法从 python 将状态电子邮件发送到 Outlook 邮件
- strapi - 在 Strapi 的画廊中为图像添加 alt 标签和标题的解决方法
- shell - 以交互模式运行 Racket 程序的 shell 脚本出错