TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。
ensure_shape()用於更新和檢查Tensor的形狀。
用法:tensorflow.ensure_shape( x, shape, name)
參數:
- x:它是輸入張量。
- shape:TensorShape代表輸入Tensor的形狀。
- name(optional):它定義了操作的名稱。
返回值:
如果形狀不兼容,則返回與x相同的張量或提高tf.errors.InvalidArgumentError。
範例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)
輸出:
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) <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]
相關用法
注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.ensure_shape()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。