将给定的 value 转换为 Tensor 。
用法
tf.compat.v1.convert_to_tensor(
value, dtype=None, name=None, preferred_dtype=None, dtype_hint=None
)参数
-
value其类型具有已注册的Tensor转换函数的对象。 -
dtype返回张量的可选元素类型。如果缺少,则从value的类型推断类型。 -
name创建新Tensor时使用的可选名称。 -
preferred_dtype返回张量的可选元素类型,当 dtype 为 None 时使用。在某些情况下,调用者在转换为张量时可能没有考虑 dtype,因此 preferred_dtype 可以用作软首选项。如果无法转换为preferred_dtype,则此参数无效。 -
dtype_hint与preferred_dtype 的含义相同,并覆盖它。
返回
-
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 tf.matmul(arg, arg) + arg
# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
在 Python 中编写新操作时,此函数很有用(例如上面示例中的 my_func)。所有标准 Python 操作构造函数都将此函数应用于它们的每个 Tensor-valued 输入,这允许这些操作除了接受 Tensor 对象之外还接受 numpy 数组、Python 列表和标量。
注意:当 Python 列表或标量中存在 None 时,此函数不同于 float 和 string 类型的默认 Numpy 行为。而不是静默转换 None 值,而是会引发错误。
相关用法
- Python tf.compat.v1.confusion_matrix用法及代码示例
- Python tf.compat.v1.cond用法及代码示例
- Python tf.compat.v1.constant用法及代码示例
- Python tf.compat.v1.count_nonzero用法及代码示例
- Python tf.compat.v1.case用法及代码示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代码示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代码示例
- Python tf.compat.v1.data.TFRecordDataset.interleave用法及代码示例
- Python tf.compat.v1.distributions.Bernoulli.cross_entropy用法及代码示例
- Python tf.compat.v1.Variable.eval用法及代码示例
- Python tf.compat.v1.train.FtrlOptimizer.compute_gradients用法及代码示例
- Python tf.compat.v1.layers.conv3d用法及代码示例
- Python tf.compat.v1.strings.length用法及代码示例
- Python tf.compat.v1.data.Dataset.snapshot用法及代码示例
- Python tf.compat.v1.data.experimental.SqlDataset.reduce用法及代码示例
- Python tf.compat.v1.feature_column.categorical_column_with_vocabulary_file用法及代码示例
- Python tf.compat.v1.data.TextLineDataset.from_tensors用法及代码示例
- Python tf.compat.v1.variable_scope用法及代码示例
- Python tf.compat.v1.data.experimental.SqlDataset.as_numpy_iterator用法及代码示例
- Python tf.compat.v1.distributions.Bernoulli.covariance用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.compat.v1.convert_to_tensor。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
