我正在使用 tensorflow v2.7.0 并尝试使用不规则张量创建 ML 模型。
问题是 tf.linalg.diag、tf.matmul 和 tf.linalg.det 不适用于不规则张量。我通过在 numpy 中转换参差不齐的张量并将其转换回参差不齐的张量找到了一种解决方法,但是在全局模型中应用图层时它不起作用。
以下代码正在运行
import tensorflow as tf
class LRDet(tf.keras.layers.Layer):
def __init__(self,numItems,rank=10):
super(LRDet,self).__init__()
self.numItems = numItems
self.rank = rank
def build(self,input_shape):
V_init = tf.random_normal_initializer(mean=0.0,stddev=0.01)
D_init = tf.random_normal_initializer(mean=1.0,stddev=0.01)
self.V = tf.Variable(name='V',initial_value=V_init(shape=(self.numItems, self.rank)),trainable=True)
self.D = tf.Variable(name='D',initial_value=D_init(shape=(self.numItems,)),trainable=True)
def call(self,inputs):
batch_size = inputs.nrows()
subV = tf.gather(self.V,inputs)
subD = tf.square(tf.gather(self.D,inputs,batch_dims=0))#tf.linalg.diag(tf.square(tf.gather(D,Xrag,batch_dims=0)))
subD = tf.ragged.constant([tf.linalg.diag(subD[i]).numpy() for i in tf.range(batch_size)])
K = tf.ragged.constant([tf.matmul(subV[i],subV[i],transpose_b=True).numpy() for i in tf.range(batch_size)])
K = tf.add(K,subD)
res = tf.ragged.constant([tf.linalg.det(K[i].to_tensor()).numpy() for i in tf.range(batch_size)])
return res
numItems = 10
rank = 3
detX = LRDet(numItems,rank)
X = [[1,2],[3],[4,5,6]]
Xrag = tf.ragged.constant(X)
_ = detX(Xrag)
但是一旦我在更全局的模型中使用了这一层,我就会遇到以下错误
OperatorNotAllowedInGraphError:调用层“lr_det_10”(类型 LRDet)时遇到异常。
in user code: File "<ipython-input-57-6b073a14386e>", line 18, in call * subD = tf.ragged.constant([tf.linalg.diag(subD[i]).numpy() for i in tf.range(batch_size)]) OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
我尝试使用 tf.map_fn 而不是 .numpy() 的列表理解,但没有成功。
任何帮助将不胜感激。