【问题标题】:How to pass a sparse tensor to the Dense Layer in TF 2.0?如何将稀疏张量传递给 TF 2.0 中的密集层?
【发布时间】:2020-04-04 06:47:00
【问题描述】:

我正在使用 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 中运行良好。

【问题讨论】:

    标签: python tensorflow keras tensorflow2.0 valueerror


    【解决方案1】:

    发生这种情况是因为当输入张量是稀疏形状时,此张量的计算结果为 (None,None) 而不是 (256,)

    inputs = layers.Input(shape=(256,), sparse=True, name='name_sparse')
    print(inputs.shape) 
    # output: (?, ?)
    

    这似乎也是一个开放的issue
    一种解决方案是编写自定义层子类化层类(参考this)。

    作为 work-around(在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      相关资源
      最近更新 更多