I am trying to implement (x-y)^2 for two matrices x of dimension n2 and y of dimension m2. I think to solve it, we might apply the binomial formula (x-y)^2 = x^2-2x.Ty+y^2=x.Tx-2x.Ty+y.Ty.
My first draft is the following:
tmp1 = numpy.square(input1)
tmp2 = numpy.square(input2)
res = numpy.dot(input1, input2.T)
res *= -2
res += temp1.reshape(-1, 1)
res += temp2
return np.exp(res)
Unfortunately, I still have problems with the dimensionality of my temporal variables after hours of trying. It would be great to get some further help how to code the binomial formula for different sized matrices. Thanks a lot!
Assuming you mean
xandyare two 1d arrays with different dimensions, and you want the square of theirouterdifference:Your
(x-y)^2can be easily done withbroadcasting:Or if we make:
then your binomial formula is:
xis 1d, sox.Tdoesn't change anything. What I think you were aiming for was transposing a (1,4) to (4,1).If the arrays are different, say 2d, you'll need to give a clear example.
If the arrays are "row vectors", these are equivalent:
edit
Looking for 'binomial forumala matrices' I found:
https://math.stackexchange.com/questions/2754278/binomial-formula-for-matrices
This talks a lot about whether the matrices are comutative, etc.
What I've shown is how to apply the basic scalar binomial formula element-wise to arrays. The (m,) and (n,) shaped arrays are (effectively) expanded to (m,n), and the formula is applied elementwise. The basic operator, '+-*' all apply elementwise, enhanced with
broadcasting.What's unclear in your question and comments is what
x^2,x.Txandx.Tymean whenxandyare 2d. Which are matrix multiplication, written innumpywithnp.dotor@(np.matmul)?Matrix multiplication has specific rules about how dimensions combine. A (3,2) @ (2,4) => (3,4), while a (2,4) @ (3,2) produces an error.
And (3,2) cannot be +/- with a (4,2). It is possible to expand the dimensions and produce a (3,4,2) 'outer' sum or difference.