目录
张量(tensor)
基础知识
张量是具有统一数据类型的多维数组,与numpy的np.arrays具有相似之处。
张量一旦创建就不可变:永远无法更新张量的内容,只能创建新的张量。
创建不同轴数的张量
创建0-轶张量:
标量称为0-轶张量,具有单个的值。
rank_0_tensor = tf.constant(4)
rank_0_tensor
<tf.Tensor: shape=(), dtype=int32, numpy=4>
创建1-轶张量:
向量称为1-轶张量,就像一个列表。
rank_1_tensor = tf.constant([2.0,3.0,4.0])
rank_1_tensor
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([2., 3., 4.], dtype=float32)>
创建2-轶张量:
矩阵称为2-轶张量。
rank_2_tensor = tf.constant([[1,2],
[3,4],
[5,6]], dtype=float)
rank_2_tensor
<tf.Tensor: shape=(3, 2), dtype=float32, numpy=
array([[1., 2.],
[3., 4.],
[5., 6.]], dtype=float32)>
更多轴的张量:
rank_3_tensor = tf.constant([
[[0,1,2,3,4],
[5,6,7,8,9]],
[[10,11,12,13,14],
[15,16,17,18,19]],
[[20,21,22,23,24],
[25,26,27,28,29]],
])
rank_3_tensor
<tf.Tensor: shape=(3, 2, 5), dtype=int32, numpy=
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])>
对于包含 2 个以上的轴的张量,您可以通过多种方式加以呈现。
张量转换为numpy数组
import numpy as np
np.array(rank_2_tensor) # 利用np.array()方法
rank_2_tensor