访问量: 9 次浏览
TensorFlow库中的 tf.convert\_to\_tensor() 方法用于将NumPy数组转换为Tensor。
NumPy数组和张量的区别在于,张量与NumPy数组不同,是由GPU等加速器内存支持的,它们有更快的处理速度。
还有一些其他方法来实现这一任务。
tf.convert\_to\_tensor() 函数:
语法:
tf.convert_to_tensor( value, dtype=None, dtype_hint=None, name=None)
参数:
value : 具有注册张量转换功能的对象的类型。dtype:默认为无。返回的张量的元素类型是可选的。如果没有指定类型,则从值的类型中推断出来。dtype\_hint : 默认为None。当 dtype 为None时,这是返回张量的一个可选的组件类型。当转换为张量时,调用者可能没有想到一个数据类型,因此dtype提示可以作为一个优先选择。如果不可能转换到dtype hint,这个参数就没有作用。name : 默认为None。如果产生一个新的张量,这是一个可选的名字,可以使用。通过使用 np.array() 方法创建一个NumPy数组。
使用 tf.convert\_to\_tensor() 方法将NumPy数组转换为张量,并返回一个张量对象。
# 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)
输出:
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int64)
特殊情况:
如果我们希望我们的张量是一个特定的 dtype ,我们应该绕过数据类型指定 dtype 。在下面的例子中, float 被指定为 dtype 。
# 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
输出:
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
我们也可以使用 tf.Variable() 方法将NumPy数组转换为Tensor。
tf.Variable() 函数也有参数 dtype 和 name 。它们是可选的,我们可以在需要时指定它们。
# 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.Variable 'tensor1:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>