我有模型
def apk(x: SymbolicTensor, y: SymbolicTensor, k=10):
"""
Computes the average precision at k.
"""
#here I need to find number of elements x, existed in y.
@tf.function
def my_map_k(actual, predicted, k=10):
"""
Computes the mean average precision at k.
"""
results = tf.map_fn(lambda x: apk(x[0], x[1]), (actual, predicted), dtype=tf.float32)
return tf.reduce_mean(results)
""""
data preparation here. Every element of data X and Y is an array int[10]
""""
model = Sequential()
model.add(SimpleRNN(300, input_shape=(1, 10))) # input_shape=(None, 1)
model.add(Dense(10))
model.compile(loss=my_map_k, optimizer='adam', run_eagerly=True)
model.fit(X2, Y2, epochs=1000, batch_size=32)
在此模型中,我需要开发自定义损失函数,将预测元素查找到 Y 元素中,并计算这些数组之间的二进制差异。
我所有迭代或转换 x、实际、y 或预测的尝试都会导致一种错误 - “符号张量不支持操作” 如果有人能告诉我如何在一个符号张量中找到另一个符号张量中的元素,我将不胜感激。 我已经尝试过这个:
Compare = tf.reduce_any(int(x[:, None]) == int(y))
exists = tf.math.count_nonzero(comparison_matrix)
return float(exists) / float(min(len(x), k))
或者这个
score = tf.math.count_nonzero(tf.reduce_any(int(x[:])==int(y[:]), axis=-1))
return float(score) / float(min(len(x), k))
并且始终保持零损失... PS:需要转换为 int() ,因为实际张量是整数,但预测张量是浮点。 更新:
def apk(x: SymbolicTensor, y: SymbolicTensor, k=10):
exists = tf.math.count_nonzero((x == tf.transpose(tf.cast(y, tf.int64))))
return float(exists) / k
相同的结果 - 损失:0.0000e+00
我找到了一个可行的解决方案:
def apk(x: SymbolicTensor, y: SymbolicTensor, k=10):
score = tf.math.count_nonzero((x == tf.transpose([tf.cast(y, tf.int64)])))
return float (k-score)/k