Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.cross function

PyTorch torch.cross function


PyTorch torch reference manual PyTorch torch reference manual

torch.cross is a PyTorch function for computing the cross product of two 3D vectors (or batches of 3D vectors). The cross product produces a new vector perpendicular to both input vectors.

Function definition

torch.cross(input, other, dim=-1)


Usage examples

Example

import

torch

Cross product of two 3D vectors

a

=

torch.

tensor

(

[

1

,

0

,

0

]

)

b

=

torch.

tensor

(

[

0

,

1

,

0

]

)

c

=

torch.

cross

(

a

,

b

)

print

(

"a:"

,

a

)

print

(

"b:"

,

b

)

print

(

"a x b:"

,

c

)

Output: tensor([0, 0, 1])

Batch computation of cross products

a

=

torch.

tensor

(

[

[

1

,

0

,

0

]

,

[

0

,

1

,

0

]

]

)

b

=

torch.

tensor

(

[

[

0

,

1

,

0

]

,

[

1

,

0

,

0

]

]

)

result

=

torch.

cross

(

a

,

b

)

print

(

"Batch cross product:"

)

print

(

result

)

tensor([[0, 0, 1],

        [0, 0, -1]])

Specify a dimension

a

=

torch.

randn

(

3

,

4

,

3

)

b

=

torch.

randn

(

3

,

4

,

3

)

result

=

torch.

cross

(

a

,

b

,

dim

=

2

)

print

(

"Shape of cross product along specified dimension:"

,

result.

shape

)


PyTorch torch reference manual PyTorch torch reference manual