將給定的 value 轉換為 Tensor 。
用法
tf.convert_to_tensor(
value, dtype=None, dtype_hint=None, name=None
)參數
-
value其類型具有已注冊的Tensor轉換函數的對象。 -
dtype返回張量的可選元素類型。如果缺少,則從value的類型推斷類型。 -
dtype_hint返回張量的可選元素類型,當 dtype 為 None 時使用。在某些情況下,調用者在轉換為張量時可能沒有考慮 dtype,因此 dtype_hint 可以用作軟首選項。如果無法轉換為dtype_hint,則此參數無效。 -
name創建新Tensor時使用的可選名稱。
返回
-
Tensor基於value。
拋出
-
TypeError如果沒有為value注冊到dtype的轉換函數。 -
RuntimeError如果注冊的轉換函數返回無效值。 -
ValueError如果value不是圖形模式下給定dtype的張量。
此函數將各種類型的 Python 對象轉換為 Tensor 對象。它接受Tensor 對象、numpy 數組、Python 列表和 Python 標量。
例如:
import numpy as np
def my_func(arg):
arg = tf.convert_to_tensor(arg, dtype=tf.float32)
return arg
# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
print(value_1)
tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float32)
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
print(value_2)
tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float32)
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
print(value_3)
tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float32)
在 Python 中編寫新操作時,此函數很有用(例如上麵示例中的 my_func)。所有標準 Python 操作構造函數都將此函數應用於它們的每個 Tensor-valued 輸入,這允許這些操作除了接受 Tensor 對象之外還接受 numpy 數組、Python 列表和標量。
注意:當 Python 列表或標量中存在 None 時,此函數不同於 float 和 string 類型的默認 Numpy 行為。而不是靜默轉換 None 值,而是會引發錯誤。
相關用法
- Python tf.config.list_logical_devices用法及代碼示例
- Python tf.config.experimental.get_memory_usage用法及代碼示例
- Python tf.config.list_physical_devices用法及代碼示例
- Python tf.config.get_logical_device_configuration用法及代碼示例
- Python tf.config.experimental.get_memory_info用法及代碼示例
- Python tf.concat用法及代碼示例
- Python tf.config.run_functions_eagerly用法及代碼示例
- Python tf.config.experimental.enable_tensor_float_32_execution用法及代碼示例
- Python tf.config.experimental_connect_to_cluster用法及代碼示例
- Python tf.config.experimental.set_memory_growth用法及代碼示例
- Python tf.config.experimental_connect_to_host用法及代碼示例
- Python tf.config.set_visible_devices用法及代碼示例
- Python tf.config.set_logical_device_configuration用法及代碼示例
- Python tf.config.experimental.enable_op_determinism用法及代碼示例
- Python tf.constant_initializer.from_config用法及代碼示例
- Python tf.config.get_visible_devices用法及代碼示例
- Python tf.config.experimental.get_device_details用法及代碼示例
- Python tf.config.experimental.ClusterDeviceFilters用法及代碼示例
- Python tf.constant用法及代碼示例
- Python tf.config.experimental.reset_memory_stats用法及代碼示例
注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.convert_to_tensor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
