Tensorlfow:增加或者减小矩阵维度(Python3)

1.增加维度

下面给出两个样例

样例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]]

样例2:

[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:

[[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]

样例2:

[[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_)

你可能感兴趣的:(python3,tensorflow)