如何将稀疏张量传递给 TF 2.0 中的 Dense Layer?
How to pass a sparse tensor to the Dense Layer in 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)
不工作:
如果我在上面的代码中将 sparse 更改为 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: (?, ?)
这似乎也是一个开放issue。
一种解决方案是编写自定义层子classing层class(参考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)
我正在使用 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)
不工作:
如果我在上面的代码中将 sparse 更改为 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: (?, ?)
这似乎也是一个开放issue。
一种解决方案是编写自定义层子classing层class(参考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)