1. Adding dimension
Two samples are given below
Sample 1:
[1, 2, 3] ==> [[1],[2],[3]] import tensorflow as tf a = ([1, 2, 3]) b = tf.expand_dims(a,1) with () as sess: a_, b_ = ([a, b]) print('a:') print(a_) print('b:') print(b_)
output result
a: [1 2 3] b: [[1] [2] [3]]
Sample 2.
[1, 2, 3] ==> [[1,2,3]] import tensorflow as tf a = ([1, 2, 3]) b = tf.expand_dims(a, 0) with () as sess: a_, b_ = ([a, b]) print('a:') print(a_) print('b:') print(b_)
Output results:
a: [1 2 3] b: [[1 2 3]]
2. Reduced dimensionality
Sample 1:
[[1, 2, 3]] ==> [1, 2, 3] import tensorflow as tf a = ([[1, 2, 3]]) b = (a) with () as sess: a_, b_ = ([a, b]) print('a:') print(a_) print('b:') print(b_)
output result
a: [[1 2 3]] b: [1 2 3]
Sample 2:
[[1], [2], [3]] ==> [[1, 2, 3] import tensorflow as tf a = ([[1], [2], [3]]) b = (a, 1) with () as sess: a_, b_ = ([a, b]) print('a:') print(a_) print('b:') print(b_)
Additional knowledge:pytorch squeeze(), unsqueeze(), and some high-dimensional array manipulation
The blogger recently read the underlying code of YOLO, and there are a lot of high-dimensional operations on multi-array matrices in Torch, so after reading one side of it, I'll record it in case I forget.
()
Function: Cancel dimension of 1
squeeze(input, dim=None, out=None) -> Tensor
It's generally not clear what dim means here
An example:
input=(A , 1 , B , C ,1 , D) squeeze(input)=(A,B,C,D) input= (A, 1, B)
squeeze(input, 0)=(A, 1, B) will not change squeeze(input, 1)=(A, B) will change
Here 0, 1 and 2 stand for A, 1 and B respectively.
()
unsqueeze(input, dim, out=None) -> Tensor
Function: Inserts a one-dimensional
It's also the dim parameter that's a little harder to understand here
The values of dim are [- ()-1, ()].
Given a dim
input=(A , B , C , D)
The dimension of input input_dim is 4, and dim takes the values [-5, 4].
unsqueeze(input, 0)=(1, A , B , C , D) unsqueeze(input, 1)=(A , 1, B , C , D) unsqueeze(input, -5)=(1, A , B , C , D)
Look at a simple use case, size indicates the size of the dimension, 10 is the range of values, a = [:,:,:,:, 4] said to take the fourth element of the last dimension of a (the fourth from 0), that is, to take the [0,0,3], [5,6,1], [0,6,8], [...], the judgment is greater than 5 for true, otherwise false.
Note that b has one less dimension than a.
Continuing from the previous step, here the unsqueeze function is used to extend the dimension of b by one dimension [2,2,3]------>[2,2,3,1] At this point there is only one element in the last dimension of b. .expand_as extends the last last element by the number of elements in the last dimension of a
a[c] means take out all the elements in a for all rows that are True
The above this Python3 Tensorlfow:Increase or Decrease Matrix Dimension implementation is all that I have shared with you, I hope it can give you a reference, and I hope that you can support me more.