# How can I calculate all cross-terms in pytorch?

I would like to calculate all cross-terms of each vector in a matrix.
For example, consider the following matrix:

``````X = tensor([[1, 2, 3],
[4, 5, 6]]),
``````

and I would like to obtain all cross-terms of each vector in this matrix as:

``````Y = [[1*1, 1*2, 1*3, 2*2, 2*3, 3*3],
[4*4, 4*5, 4*6, 5*5, 5*6, 6*6]].
= [[1, 2, 3, 4, 6, 9],
[16, 20, 24, 25, 30, 36]].
``````

That is, this is the all combination values of the vector elements and I believe that this can be calculated using torch.combinations; however, torch.combinations does not provide the batch implementation and I couldn’t produce the above result in pytorch.

How can I calculate all cross-terms in pytorch? I assume that X is the batch of feature vectors and I would like to implement a regression model with the cross terms of the feature vectors Y as input.

should be doable if you make combinations of indexes instead (i.e. of elements from arange(K,dtype=int64)), and use the resulting tensor for “advanced indexing” on X. so you’ll get value pairs and prod(dim=x) reduction will finally yield the desired output.

``````Y = torch.cat([(X[0:1,:].T@X[0:1,:]), (X[1:2,:].T@X[1:2,:])]).unique().view(2, -1)
``````

Typed on my phone so please excuse any typos. But should be something like this.