📜  Python – tensorflow.ensure_shape()

📅  最后修改于: 2022-05-13 01:55:32.744000             🧑  作者: Mango

Python – tensorflow.ensure_shape()

TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

ensure_shape()用于更新和检查张量的形状。

示例 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.ensure_shape(x, (2, 3))
  
# 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.ensure_shape(x, (2, 4))
  
# 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, 3), dtype=int32)

示例 2:在此示例中,形状与 x 的形状不兼容,因此会引发错误。

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.ensure_shape(x, (2, 4))
  
# Printing the result
print('res: ', res)

输出:

x: tf.Tensor(
[[ 2  3  6]
 [ 4  8 15]], shape=(2, 3), dtype=int32)

---------------------------------------------------------------------------

InvalidArgumentError                      Traceback (most recent call last)

 in ()
      9 
     10 # Calculating result
---> 11 res = tf.ensure_shape(x, (2, 4))
     12 
     13 # Printing the result

3 frames

/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Shape of tensor dummy_input [2, 3] is not compatible with expected shape [2, 4]. [Op:EnsureShape]