【发布时间】:2018-05-08 13:50:33
【问题描述】:
我正在尝试在 keras 中实现损失函数,例如以下伪代码
for i in range(N):
for j in range(N):
sum += some_calculations
但我读到张量流不支持这种 for 循环,因此我从 here 了解了 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])
但是当我运行这段代码时,我得到了一个错误
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]
【问题讨论】:
标签: tensorflow keras tensor