Python TensorFlow ``convert_to_tensor()`` 方法详解与实例


发布日期 : 2021-01-17 05:24:11 UTC

访问量: 10 次浏览

Python – tensorflow.convert\_to\_tensor()

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

convert\_to\_tensor()用于将给定值转换为张量。

语法:
tensorflow.convert_to_tensor( value, dtype, dtype_hint, name )

参数:

  • value: 它是需要被转换为张量的值。
  • dtype(可选):它定义了输出张量的类型。
  • dtype\_hint(可选):当 dtype 为None时,它被使用。在某些情况下,调用者在转换为张量时可能没有想到一个 dtype ,所以 dtype\_hint 可以作为一个软偏好。如果不可能转换为 dtype\_hint ,这个参数就没有作用。
  • name(optiona) :它定义了操作的名称。

返回:它返回一个张量。

例子1:来自Python列表

# Importing the library
import tensorflow as tf

# Initializing the input
l = [1, 2, 3, 4]

# Printing the input
print('l: ', l)

# Calculating result
x = tf.convert_to_tensor(l)


# Printing the result
print('x: ', x)

输出:

l: [1, 2, 3, 4]
x: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)

例子2:来自Python元组

# Importing the library
import tensorflow as tf

# Initializing the input
l = (1, 2, 3, 4)

# Printing the input
print('l: ', l)

# Calculating result
x = tf.convert_to_tensor(l, dtype = tf.float64)


# Printing the result
print('x: ', x)

输出:

l: (1, 2, 3, 4)
x: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)