在tensorflow中嵌套while循环

Dee*_*rma 5 keras tensorflow tensor

我正在尝试在keras中实现损失函数,例如以下伪代码

for i in range(N):
    for j in range(N):
        sum += some_calculations
Run Code Online (Sandbox Code Playgroud)

但是我读到张量流不支持这种for循环,因此我从这里开始了解了while_loop(cond,body,loop_vars)函数

我在这里了解了while循环的基本工作原理,因此我实现了以下代码:

def body1(i):
    global data
    N = len(data)*positive_samples     //Some length
    j = tf.constant(0)    //iterators
    condition2 = lambda j, i :tf.less(j, N)   //one condition only j should be less than N
    tf.add(i, 1)   //increment previous index i
    result = 0

    def body2(j, i):
        global similarity_matrix, U, V
        result = (tf.transpose(U[:, i])*V[:, j])   //U and V are 2-d tensor Variables and here only a column is extracted and their final product is a single value
        return result

    tf.while_loop(condition2, body2, loop_vars=[j, i])
    return result


def loss_function(x):
    global data
    N = len(data)*positive_samples
    i = tf.constant(0)
    condition1 =  lambda i : tf.less(i, N)
    return tf.while_loop(condition1, body1, [i])
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此代码时,出现错误

ValueError: The two structures don't have the same number of elements. First structure: [<tf.Tensor 'lambda_1/while/while/Identity:0' shape=() dtype=int32>, <tf.Tensor 'lambda_1/while/while/Identity_1:0' shape=() dtype=int32>], second structure: [0]
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 5

tf.while_loop可能很难使用,请确保仔细阅读文档。主体的返回值必须具有与循环变量相同的结构,并且操作的返回值tf.while_loop是变量的最终值。为了进行计算,您应该传递一个附加的循环变量来存储部分结果。您可以执行以下操作:

def body1(i, result):
    global data
    N = len(data) * positive_samples
    j = tf.constant(0)
    condition2 = lambda j, i, result: tf.less(j, N)
    result = 0

    def body2(j, i, result):
        global similarity_matrix, U, V
        result_j = (tf.transpose(U[:, i]) * V[:, j])
        return j + 1, i, result + result_j

    j, i, result = tf.while_loop(condition2, body2, loop_vars=[j, i, result])
    return i + 1, result

def loss_function(x):
    global data
    N = len(data)*positive_samples
    i = tf.constant(0)
    result = tf.constant(0, dtype=tf.float32)
    condition1 = lambda i, result: tf.less(i, N)
    i, result = tf.while_loop(condition1, body1, [i, result])
    return result
Run Code Online (Sandbox Code Playgroud)

从您的代码尚不清楚在哪里x使用。但是,在这种情况下,运算的结果应该简单地等于:

result = tf.reduce_sum(tf.transpose(U) @ V)
# Equivalent
result = tf.reduce_sum(tf.matmul(tf.transpose(U), V))
Run Code Online (Sandbox Code Playgroud)

这也将更快。