什么是张量

张量的数学概念

在数学里,张量是一种几何实体,广义上表示任意形式的“数据”。张量可以理解为0阶(rank)标量、1阶向量和2阶矩阵在高维空间上的推广,张量的阶描述它表示数据的最大维度。

数据实体 Python样例
0 标量 scalar=1
1 向量 vector=[1,2,3]
2 矩阵 matrix=[[1,2,3], [4,5,6], [7,8,9]]
3 数据立方 tensor=[[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]]
n n阶张量

TensorFlow中的张量

在TensorFlow中,张量(Tensor)表示某种相同数据类型多维数组

因此,张量有两个重要属性:

  1. 数据类型(如浮点型、整型、字符串等)
  2. 数组形状(各个维度的大小)

Q: TensorFlow张量是什么?

  • 张量是用来表示多维数据的
  • 张量是执行操作时的输入或输出数据。
  • 用户通过执行操作来创建或计算张量。
  • 张量的形状不一定在编译时确定,可以在运行时通过形状推断计算得出。

在TensorFlow中,有几类比较特别的张量,由以下操作产生:

  • tf.constant //常量
  • tf.placeholder //占位符
  • tf.Variable //变量

代码示例

0阶张量

1
2
3
4
mammal = tf.Variable("Elephant", tf.string)
ignition = tf.Variable(451, tf.int16)
floating = tf.Variable(3.14159265359, tf.float64)
its_complicated = tf.Variable(12.3 - 4.85j, tf.complex64)

输出:

1
2
3
4
[<tf.Variable 'Variable:0' shape=() dtype=string_ref>,
<tf.Variable 'Variable_1:0' shape=() dtype=int32_ref>,
<tf.Variable 'Variable_2:0' shape=() dtype=float32_ref>,
<tf.Variable 'Variable_3:0' shape=() dtype=complex128_ref>]

1阶张量

1
2
3
4
mystr = tf.Variable(["Hello", "World"], tf.string)
cool_numbers = tf.Variable([3.14159, 2.71828], tf.float32)
first_primes = tf.Variable([2, 3, 5, 7, 11], tf.int32)
its_very_complicated = tf.Variable([12.3 - 4.85j, 7.5 - 6.23j], tf.complex64)

输出:

1
2
3
4
[<tf.Variable 'Variable_4:0' shape=(2,) dtype=string_ref>,
<tf.Variable 'Variable_5:0' shape=(2,) dtype=float32_ref>,
<tf.Variable 'Variable_6:0' shape=(5,) dtype=int32_ref>,
<tf.Variable 'Variable_7:0' shape=(2,) dtype=complex128_ref>]

2阶张量

1
2
3
4
5
6
mymat = tf.Variable([[7],[11]], tf.int16)
myxor = tf.Variable([[False, True],[True, False]], tf.bool)
linear_squares = tf.Variable([[4], [9], [16], [25]], tf.int32)
squarish_squares = tf.Variable([ [4, 9], [16, 25] ], tf.int32)
rank_of_squares = tf.rank(squarish_squares)
mymatC = tf.Variable([[7],[11]], tf.int32)

输出:

1
2
3
4
5
6
[<tf.Variable 'Variable_8:0' shape=(2, 1) dtype=int32_ref>,
<tf.Variable 'Variable_9:0' shape=(2, 2) dtype=bool_ref>,
<tf.Variable 'Variable_10:0' shape=(4, 1) dtype=int32_ref>,
<tf.Variable 'Variable_11:0' shape=(2, 2) dtype=int32_ref>,
<tf.Tensor 'Rank:0' shape=() dtype=int32>,
<tf.Variable 'Variable_12:0' shape=(2, 1) dtype=int32_ref>]

4阶张量

1
my_image = tf.zeros([10, 299, 299, 3])  # batch x height x width x color

输出:

1
<tf.Tensor 'zeros:0' shape=(10, 299, 299, 3) dtype=float32>
加载评论框需要科学上网