Python 有没有一种方法可以使用tf.keras输出稀疏张量?

Python 有没有一种方法可以使用tf.keras输出稀疏张量?,python,tensorflow,keras,sparse-matrix,Python,Tensorflow,Keras,Sparse Matrix,我想训练一个语义分割模型,所以输出张量包含很多零。我创建了一个tf.data数据集,它返回一个包含输出掩码的tensorflow稀疏张量,以便在训练时消耗更少的RAM,但是当我尝试tf.keras.fit时,我得到了 TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: Spars

我想训练一个语义分割模型,所以输出张量包含很多零。我创建了一个tf.data数据集,它返回一个包含输出掩码的tensorflow稀疏张量,以便在训练时消耗更少的RAM,但是当我尝试tf.keras.fit时,我得到了

TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: SparseTensor(indices=Tensor("cond_2/Identity_1:0", shape=(None, 4), dtype=int64, device=/job:localhost/replica:0/task:0/device:GPU:0), values=Tensor("cond_2/Identity_2:0", shape=(None,), dtype=float32, device=/job:localhost/replica:0/task:0/device:GPU:0), dense_shape=Tensor("stack:0", shape=(4,), dtype=int64, device=/job:localhost/replica:0/task:0/device:GPU:0)). Consider casting elements to a supported type.
但现在的错误是

AttributeError: 'Tensor' object has no attribute 'indices'
我猜模型的输出应该是一个张量对象,这个错误发生在模型的编译过程中。
有没有办法强制tf.keras模型输出为稀疏张量?

请参考示例代码将张量转换为稀疏张量

import numpy as np
import tensorflow as tf

# Make a tensor from a constant
a = np.reshape(np.arange(24), (3, 4, 2))
a_t = tf.constant(a)
# Find indices where the tensor is not zero
idx = tf.where(tf.not_equal(a_t, 0))
# Make the sparse tensor
# Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape()
# if tensor shape is dynamic
sparse = tf.SparseTensor(idx, tf.gather_nd(a_t, idx), a_t.get_shape())
选中此项:
import numpy as np
import tensorflow as tf

# Make a tensor from a constant
a = np.reshape(np.arange(24), (3, 4, 2))
a_t = tf.constant(a)
# Find indices where the tensor is not zero
idx = tf.where(tf.not_equal(a_t, 0))
# Make the sparse tensor
# Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape()
# if tensor shape is dynamic
sparse = tf.SparseTensor(idx, tf.gather_nd(a_t, idx), a_t.get_shape())