# Python3 Tensorlfow:增加或者减小矩阵维度的实现

1.增加维度

```[1, 2, 3] ==> [[1],[2],[3]]

import tensorflow as tf

a = tf.constant([1, 2, 3])
b = tf.expand_dims(a,1)

with tf.Session() as sess:
a_, b_ = sess.run([a, b])
print('a:')
print(a_)
print('b:')
print(b_)
```

```a:
[1 2 3]
b:
[[1]
[2]
[3]]```

```[1, 2, 3] ==> [[1,2,3]]

import tensorflow as tf

a = tf.constant([1, 2, 3])
b = tf.expand_dims(a, 0)

with tf.Session() as sess:
a_, b_ = sess.run([a, b])
print('a:')
print(a_)
print('b:')
print(b_)
```

```a:
[1 2 3]
b:
[[1 2 3]]```

2.降低维度

```[[1, 2, 3]] ==> [1, 2, 3]

import tensorflow as tf

a = tf.constant([[1, 2, 3]])
b = tf.squeeze(a)

with tf.Session() as sess:
a_, b_ = sess.run([a, b])
print('a:')
print(a_)
print('b:')
print(b_)
```

```a:
[[1 2 3]]
b:
[1 2 3]```

```[[1], [2], [3]] ==> [[1, 2, 3]

import tensorflow as tf

a = tf.constant([[1], [2], [3]])
b = tf.squeeze(a, 1)

with tf.Session() as sess:
a_, b_ = sess.run([a, b])
print('a:')
print(a_)
print('b:')
print(b_)
```

torch.squeeze()

squeeze(input, dim=None, out=None) -> Tensor

```input=(A ， 1 ， B ， C ，1 ， D)
squeeze(input)=(A，B，C，D)
input= （A, 1, B）```

squeeze(input, 0)=(A, 1, B) 不会改变 squeeze(input, 1)=(A, B) 会改变

torch.unsqueeze()

unsqueeze(input, dim, out=None) -> Tensor

dim的取值是[- input.dim()-1, imput.dim()]

input=(A ， B ， C ， D)

input的维度input_dim为4, dim的取值[-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)```

a[c] 表示取出为True的所有行在a中的元素