Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

torch.cat

torch.cat(tensors, dim=0,  * , out=None) – > Tensor

Join the tensors of the parameters. The tensors must be at the same latitude or empty.

  • parameter
    • tensors (sequence of Tensors) — multiple tensors are passed in as tuples
    • dim (int . optional) — the dimension of a tensor connection. Take two dimensions: 0 is a row, 1 is a column… You can pick a few dimensions if the tensors you connect are parameters of several dimensions. If you have two two-dimensional tensors you can only pick (-2, -1, 0, 1), if you have three dimensions you can only pick (-3, -2, -1, 0, 1, 2)
      • In my tests, negative 2 is the same as 0, negative 1 is the same as 1. My guess is minus one and zero, a few on the right and a few on the left, and it works the same from left to right.
import torch

t1 = torch.rand(2.3)
t2 = torch.rand(2.3)
t3 = torch.cat((t1, t2), dim=0)
print(t1)
print(t2)
print(t3)

t4 = torch.cat((t1, t2), dim=1)
print(t4)
Copy the code

Output:

Tensor ([[0.7839, 0.1447, 0.4310], [0.9642, 0.5121, 0.3178]]) tensor ([[0.7691, 0.2200, 0.8842], [0.6078, 0.9669, 0.9191]]) tensor ([[0.7839, 0.1447, 0.4310], [0.9642, 0.5121, 0.3178], [0.7691, 0.2200, 0.8842], [0.6078, 0.9669, Tensor ([[0.7839, 0.1447, 0.4310, 0.7691, 0.2200, 0.8842], [0.9642, 0.5121, 0.3178, 0.6078, 0.9669, 0.9191]])Copy the code

torch.stack

Torch. Stack (Tensors, Dim =0, *, out=None) → Tensor

Link tensors into a new tensor, in terms of new dimensions

  • parameter
    • tensors (sequence of Tensors) — tensors that need to be connected
    • dim (intThe inserted dimension must be between 0 and the dimension of the joined tensor.
      • So this is going to add one dimension, two dimensions connected into three. Dim can be selected after the connection. So in two dimensions it’s [-3,2], and in three dimensions it’s [-4,3].

This output is not done, look at a string of numbers is not interesting. Multidimensional doesn’t look good to the naked eye either.