How do I compute the MSE of two tensors elegantly?

Question:

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?

Asked By: Mozzie

||

Answers:

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).

Answered By: jdehesa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.