如何将 Numpy 数组转换为张量?
TensorFlow 库中的 tf.convert_to_tensor() 方法用于将 NumPy 数组转换为张量。 NumPy 数组和张量的区别在于,张量与 NumPy 数组不同,由 GPU 等加速器内存支持,它们具有更快的处理速度。还有其他几种方法可以完成此任务。
tf.convert_to_tensor()函数:
Syntax:
tf.convert_to_tensor( value, dtype=None, dtype_hint=None, name=None)
parameters:
- value : The type of an object with a registered Tensor conversion function.
- dtype: by default it is None. The returned tensor’s element type is optional. If the type isn’t specified, the type is inferred from the value type.
- dtype_hint: by default None. When dtype is None, this is an optional component type for the returned tensor. When converting to a tensor, a caller may not have a datatype in mind, hence dtype hint can be used as a preference. This parameter has no effect if the conversion to dtype hint is not possible.
- name : by default None. If a new Tensor is produced, this is an optional name to use.
示例 1:
Tensorflow 和 NumPy 包被导入。使用 np.array() 方法创建 NumPy 数组。使用 tf.convert_to_tensor() 方法将 NumPy 数组转换为张量。返回一个张量对象。
Python3
# import packages
import tensorflow as tf
import numpy as np
#create numpy_array
numpy_array = np.array([[1,2],[3,4]])
# convert it to tensorflow
tensor1 = tf.convert_to_tensor(numpy_array)
print(tensor1)
Python3
# import packages
import tensorflow as tf
import numpy as np
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
tensor1 = tf.convert_to_tensor(numpy_array, dtype=float, name='tensor1')
tensor1
Python3
# import packages
import tensorflow as tf
import numpy as np
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
tensor1 = tf.Variable(numpy_array, dtype=float, name='tensor1')
tensor1
输出:
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int64)
特例:
如果我们希望我们的张量具有特定的数据类型,我们应该指定绕过数据类型的数据类型。在下面的示例中,float 被指定为 dtype。
Python3
# import packages
import tensorflow as tf
import numpy as np
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
tensor1 = tf.convert_to_tensor(numpy_array, dtype=float, name='tensor1')
tensor1
输出:
示例 2:
我们还可以使用 tf.Variable() 方法将 NumPy 数组转换为张量。 tf.Variable()函数也有参数 dtype 和 name。它们是可选的,我们可以在需要时指定它们。
Python3
# import packages
import tensorflow as tf
import numpy as np
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
tensor1 = tf.Variable(numpy_array, dtype=float, name='tensor1')
tensor1
输出: