首页 > 解决方案 > 如何将稀疏张量传递给 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 中运行良好。

标签: pythontensorflowkerastensorflow2.0valueerror

解决方案


发生这种情况是因为当输入张量是稀疏形状时,此张量的计算(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)

推荐阅读