Python – tensorflow.expand_dims()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
expand_dims()用于在输入张量中插入一个附加维度。
Syntax: tensorflow.expand_dims( input, axis, name)
Parameters:
- input: It is the input Tensor.
- axis: It defines the index at which dimension should be inserted. If input has D dimensions then axis must have value in range [-(D+1), D].
- name(optional): It defines the name for the operation.
Returns: It returns a Tensor with expanded dimension.
示例 1:
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])
# Printing the input
print('x:', x)
# Calculating result
res = tf.expand_dims(x, 1)
# Printing the result
print('res: ', res)
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])
# Printing the input
print('x:', x)
# Calculating result
res = tf.expand_dims(x, 0)
# Printing the result
print('res: ', res)
输出:
x: tf.Tensor(
[[ 2 3 6]
[ 4 8 15]], shape=(2, 3), dtype=int32)
res: tf.Tensor(
[[[ 2 3 6]]
[[ 4 8 15]]], shape=(2, 1, 3), dtype=int32)
# shape has changed from (2, 3) to (2, 1, 3)
示例 2:
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])
# Printing the input
print('x:', x)
# Calculating result
res = tf.expand_dims(x, 0)
# Printing the result
print('res: ', res)
输出:
x: tf.Tensor(
[[ 2 3 6]
[ 4 8 15]], shape=(2, 3), dtype=int32)
res: tf.Tensor(
[[[ 2 3 6]
[ 4 8 15]]], shape=(1, 2, 3), dtype=int32)
# shape has changed from (2, 3) to (1, 2, 3)