访问量: 10 次浏览
tensorflow.ensure\_shape()TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
ensure\_shape()
用于更新和检查Tensor的形状。
语法:
tensorflow.ensure_shape( x, shape, name)
参数:
返回值:
它返回一个与x相同的张量,如果形状不兼容,则引发 tf.errors.InvalidArgumentError 。
示例 1:
# 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)
输出:
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的形状不兼容,所以产生了错误。
# 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)
<ipython-input-1-ab1be364fadb> in <module>()
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]