() Function usage
1. Basic functions
The official pytroch documentation describes this function very briefly.
Only one sentence:
Connect on dimensions (concatenate) Several tensors. (These tensors are the same shape).
After code summary, you can getstack(tensors,dim=0,out=None)
Functions:
Connect several tensors on the dim dimension to generate an expanded tensor. For example, if you have several 2-dimensional tensors, you can get a 3-dimensional tensor.
Suppose the tensor dimension to be connected is n and the value range of dim is -n-1~n. Here we have to mention the meaning of negative: -i is the i-th last dimension.
For example:
For 2-dimensional tensors to be connected, -1 dimension is 3 dimensions, and -2 dimension is 2 dimensions.
On code:
a=([[1,2,3],[4,5,6]]) b=([[10,20,30],[40,50,60]]) c=([[100,200,300],[400,500,600]]) print(([a,b,c],dim=0)) print(([a,b,c],dim=1)) print(([a,b,c],dim=2)) print(([a,b,c],dim=0).size()) print(([a,b,c],dim=1).size()) print(([a,b,c],dim=2).size()) #The output result is:tensor([[[ 1, 2, 3], [ 4, 5, 6]], [[ 10, 20, 30], [ 40, 50, 60]], [[100, 200, 300], [400, 500, 600]]]) tensor([[[ 1, 2, 3], [ 10, 20, 30], [100, 200, 300]], [[ 4, 5, 6], [ 40, 50, 60], [400, 500, 600]]]) tensor([[[ 1, 10, 100], [ 2, 20, 200], [ 3, 30, 300]], [[ 4, 40, 400], [ 5, 50, 500], [ 6, 60, 600]]]) ([3, 2, 3]) ([2, 3, 3]) ([2, 3, 3])
2. Regular analysis
It is not difficult to find out through the code running results.stack(tensors,dim=0,out=None)
The function's running mechanism can be equivalent to:
- When dim=0, connect tensors in one dimension. Simply put, connect tensor1, tensor2…tensor n, to [tensor1, tensor2…tensor n] (This is where the expanded dimension is generated)
- When dim=1, connect the i-th row of each tensor to form a new 2-dimensional tensor, and then connect these new tensors in the way dim=0.
- When dim=2, transpose the i-th row of each tensor and connect it into a new 2-dimensional tensor according to columns, and then connect these new tesnors according to dim=0
You can get a conclusion: n-dimensional (n>=2) tensors to be connected in dim=x are equivalent to:
- If x=0, connect according to the above rules
- If x>0, the tensors in the first dimension of each tensor are connected according to the method of dim=x-1 to obtain several new tensors, and these new tensors are connected according to the method of dim=0.
- It is obvious that this law has the characteristics of recursion, and the basic situation of x=0,1,2 has been given.
Note: The above rules are unproven guesses based on the source code of the function implementation.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.