我一直在努力让这个工作一段时间,但我不知道如何。我试了十几种组合。
我要做的就是获取输入数组,比较每个元素,看看它是正的还是负的。根据积极性或消极性应用独特的转换。取平均值并返回结果。这是我的,但它不工作。
edit: my latest attempt
@tf.function
def transform(x, y):
et = tf.math.subtract(x, y)
et_variable = tf.Variable(et)
max_loop = tf.shape(x)[0]
loss = tf.TensorArray(tf.float32, size=et.shape[0], clear_after_read=False)
loss = loss.unstack(et_variable)
i = tf.constant(0)
while tf.math.less(i, max_loop):
if loss.gather([i])[0] > 0:
val = 3 * loss.gather([i])[0]
else:
val = 2 * loss.gather([i])[0]
loss = loss.scatter([i], value=[val])
i = tf.Variable(i)
i = i + 1
i = tf.constant(i)
return(K.mean(loss.stack()))
我得到一个错误:
ValueError: condition of if statement expected to be `tf.bool` scalar, got Tensor("loss_funk/while/Greater:0", shape=(11,), dtype=bool); to check for None, use `is not None`
我试过使用tf。变量和tf。Tensorarray,但都不能使用tf.function.
下面是一个满足您期望的示例。Tensor没有gather_nd,它是tensorflow的API。我的tensorflow版本是2.3
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
y_true = np.random.normal(size=(30, 50)).astype('float32')
x = np.random.normal(size=(30, )).astype('float32')
y = np.random.normal(size=(30, )).astype('float32')
@tf.function
def transform(x, y):
et = tf.math.subtract(x, y)
max_loop = tf.shape(y_true)[0]
res = tf.TensorArray(tf.float32, size=et.shape[0], clear_after_read=False)
i = tf.constant(0)
while tf.math.less(i, max_loop):
if tf.gather_nd(et, [i]) > 0:
val = 0.03 * tf.gather_nd(et, [i])
else:
val = 0.05 * tf.gather_nd(et, [i])
res = res.write(i, val)
i = i + 1
return K.mean(res.stack())
transform(x, y)