TensorFlow中tensor

    在TensorFlow中,我们使用张量表示数据,使用计算图搭建神经网络,使用会话训练神经网络,执行训练过程。首先我们先了解张量的运行机制和原理。

张量的理解

      简单来说,张量就是N维数组。在Python中,tensor的形式的Numpy ndarray。N维数组(N维张量)表征了数据的不同形状,比如0维张量表示标量、1维张量表示向量,2维张量表示矩阵,下面我们直观的给出0维到4维的张量,更高维度的张量很少用,而且理解起来也比较困难,这里不做介绍。

维度 属性 shape 示例
0维张量 标量 [ ]<=>shape=() 1,2,3
1维张量 向量 [a]<=>shape=(a,) [1, 2, 3]
2维张量 矩阵 [a, b]<=>shape(a,b) [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
3维张量 数据立体   [[[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
4维张量 通道   [[[[1, 2, 3], [1, 2, 3], [1, 2, 3]]]]

     从示例中,我们不难发现,随着张量维度的增加,能表示的数据形状就越丰富,数据的表示含义也各不相同。那我们就来介绍对于不同维度的张量,其具体的内涵有何不同。

  • 对于0阶张量,只有大小。A,B,C表示单一的特征值
  • 对于1阶张量,既有大小也有方向。[A, B, C]表示有一个样本,里面含有3个特征
  • 对于2阶张量,数据表。[[A, B, C], [D, E, F], [G, H, I]]表示有3个样本,每个样本分别有3个特征
  • 对于3阶张量,时间序列。[[[A, B, C], [D, E, F], [G, H, I]]]特征随时间同步更新
  • 对于4阶张量,通道。特征和样本随时间同步更新。

张量的创建

tf.constant(value,tf.float32) 

  • value可以是以上的各个维度的张量,如1, [1], [[1]]
t = tf.constant(1, tf.float32)
t = tf.constant([1,2,3], tf.float32)
t = tf.constant([[1, 2, 3],[1, 2, 3],[1,2,3], tf.float32)

tf.zeros(shape, tf.float32)

  • shape为数据的维度。比如[]表示标量,[a]表示a行,[a, b]表示a行b列
tf.zeros([])   # tf.Tensor(0.0, shape=(), dtype=float32)
tf.zeros([1])   # tf.Tensor([0.], shape=(1,), dtype=float32)
tf.zeros([1,2])   # tf.Tensor([[0. 0.]], shape=(1, 2), dtype=float32)

tf.ones(shape, tf.float32)

  • shape为数据的维度。比如[]表示标量,[a]表示a行,[a, b]表示a行b列
tf.ones([])   # tf.Tensor(1.0, shape=(), dtype=float32)
tf.ones([1])   # tf.Tensor([1.], shape=(1,), dtype=float32)
tf.ones([1,2])   # tf.Tensor([[1. 1.]], shape=(1, 2), dtype=float32)

tf.fill(shape, value)

tf.fill([2,3],4)
# tf.Tensor(
# [[4 4 4]
# [4 4 4]], shape=(2, 3), dtype=int32)

猜你喜欢

转载自blog.csdn.net/Stybill_LV_/article/details/105804472