💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 从 Python 对象创建张量 我们可以使用带有以下签名的`tf.convert_to_tensor()`操作从 Python 对象(如列表和 NumPy 数组)创建张量: ```py tf.convert_to_tensor( value, dtype=None, name=None, preferred_dtype=None ) ``` 让我们创建一些张量并打印出来进行练习: 1. 创建并打印 0-D 张量: ```py tf_t=tf.convert_to_tensor(5.0,dtype=tf.float64) print('tf_t : ',tf_t) print('run(tf_t) : ',tfs.run(tf_t)) ``` 输出如下: ```py tf_t : Tensor("Const_1:0", shape=(), dtype=float64) run(tf_t) : 5.0 ``` 1. 创建并打印 1-D 张量: ```py a1dim = np.array([1,2,3,4,5.99]) print("a1dim Shape : ",a1dim.shape) tf_t=tf.convert_to_tensor(a1dim,dtype=tf.float64) print('tf_t : ',tf_t) print('tf_t[0] : ',tf_t[0]) print('tf_t[0] : ',tf_t[2]) print('run(tf_t) : \n',tfs.run(tf_t)) ``` 输出如下: ```py a1dim Shape : (5,) tf_t : Tensor("Const_2:0", shape=(5,), dtype=float64) tf_t[0] : Tensor("strided_slice:0", shape=(), dtype=float64) tf_t[0] : Tensor("strided_slice_1:0", shape=(), dtype=float64) run(tf_t) : [ 1\. 2\. 3\. 4\. 5.99] ``` 1. 创建并打印 2-D Tensor: ```py a2dim = np.array([(1,2,3,4,5.99), (2,3,4,5,6.99), (3,4,5,6,7.99) ]) print("a2dim Shape : ",a2dim.shape) tf_t=tf.convert_to_tensor(a2dim,dtype=tf.float64) print('tf_t : ',tf_t) print('tf_t[0][0] : ',tf_t[0][0]) print('tf_t[1][2] : ',tf_t[1][2]) print('run(tf_t) : \n',tfs.run(tf_t)) ``` 输出如下: ```py a2dim Shape : (3, 5) tf_t : Tensor("Const_3:0", shape=(3, 5), dtype=float64) tf_t[0][0] : Tensor("strided_slice_3:0", shape=(), dtype=float64) tf_t[1][2] : Tensor("strided_slice_5:0", shape=(), dtype=float64) run(tf_t) : [[ 1\. 2\. 3\. 4\. 5.99] [ 2\. 3\. 4\. 5\. 6.99] [ 3\. 4\. 5\. 6\. 7.99]] ``` 1. 创建并打印 3-D Tensor: ```py a3dim = np.array([[[1,2],[3,4]], [[5,6],[7,8]] ]) print("a3dim Shape : ",a3dim.shape) tf_t=tf.convert_to_tensor(a3dim,dtype=tf.float64) print('tf_t : ',tf_t) print('tf_t[0][0][0] : ',tf_t[0][0][0]) print('tf_t[1][1][1] : ',tf_t[1][1][1]) print('run(tf_t) : \n',tfs.run(tf_t)) ``` 输出如下: ```py a3dim Shape : (2, 2, 2) tf_t : Tensor("Const_4:0", shape=(2, 2, 2), dtype=float64) tf_t[0][0][0] : Tensor("strided_slice_8:0", shape=(), dtype=float64) tf_t[1][1][1] : Tensor("strided_slice_11:0", shape=(), dtype=float64) run(tf_t) : [[[ 1\. 2.][ 3\. 4.]] [[ 5\. 6.][ 7\. 8.]]] ``` TensorFlow 可以将 NumPy `ndarray`无缝转换为 TensorFlow 张量,反之亦然。