Mozzie
Mozzie

Reputation: 353

How do I compute the MSE of two tensors elegantly?

Suppose there are two tensor lists:

r1 = K.variable(1)
r2 = K.variable(2)
v1 = K.variable(3)
v2 = K.variable(4)
l1 = [r1,r2]
l2 = [v1,v2]

I'm trying to compute the MSE of these two tensors. What I am doing is:

res = []
for i in range(len(l1)):
    res.append(K.square(l1[i] - l2[i]))
return sum(res)/len(res)

But I think this code is a mess. Is there any more effective and elegant way to do this?

Upvotes: 2

Views: 259

Answers (1)

javidcf
javidcf

Reputation: 59721

I think you should be able to simply do:

return K.mean(K.square(K.stack(l1) - K.stack(l2)))

Note here I am assuming all the tensors in the lists have the same shape (like in your snippet, which would also fail otherwise anyway).

Upvotes: 3

Related Questions