tensorflow2.0---笔记2 tensor高阶操作

文章目录

  • tensor的合并与分割
      • 合并
      • 分割
  • 数据统计
      • tf.norm (范数)
      • reduce_min/max/mean
      • tf.argmax、tf.argmin
      • tf.equal(a, b)
      • tf.unique(a)
  • 张量排序
      • tf.sort (a, axis = -1, direction="")、tf.argsort (a, direction="")
      • tf.math.top_k (a, k)
  • 填充与复制
      • tf.pad(a, [[行维度上,下],[列维度左,右]])
      • tf.tile(a, [维度1复制倍数, 维度2复制倍数,……])
  • 张量限幅
      • tf.clip_by_value(a, min, max)
      • tf.clip_by_norm(a, 15)
      • tf.clip_by_global_norm(grads, 15)
  • 其他高阶操作
      • tf.where(mask)
      • tf.scatter_nd(indices, updates, shape)
      • tf.meshgrid(x, y)

tensor的合并与分割

tensorflow2.0---笔记2 tensor高阶操作_第1张图片

合并

tensorflow2.0---笔记2 tensor高阶操作_第2张图片

tf.concat([a, b], axis = )
注:
(1)不创建新的维度;
(2)在哪个维度合并,哪个维度数量增加;其他维度必须相同。
tensorflow2.0---笔记2 tensor高阶操作_第3张图片

a = tf.ones([4, 35, 8])
b = tf.ones([2, 35, 8])
c = tf.ones([4, 35, 8])

d = tf.concat([a, b], axis=0)
print(d.shape)  # (6, 35, 8)

e = tf.concat([a, c], axis=-1)
print(e.shape)  # (4, 35, 16)

tensorflow2.0---笔记2 tensor高阶操作_第4张图片

tf.stack([a, b], axis = )
注意,会创建新的维度!

a = tf.ones([4, 35, 8])
b = tf.ones([4, 35, 8])

c = tf.stack([a, b], axis=0)
print(c.shape)

d = tf.stack([a, b], axis=-1)
print(d.shape)  # (4, 35, 8, 2)

a、b的原始维度必须完全相同,否则报错:

a = tf.ones([4, 35, 8])
b = tf.ones([2, 35, 8])

c = tf.stack([a, b], axis=0)
print(c.shape)
#  ensorflow.python.framework.errors_impl.InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [4,35,8] != values[1].shape = [2,35,8] [Op:Pack] name: stack

分割

tf.unstack(a, axis = )
注意,返回一个list,list里面的内容是tensor

a = tf.ones([4, 35, 8])
b = tf.ones([4, 35, 8])
c = tf.stack([a, b], axis=0)
print(c.shape)  # (2, 4, 35, 8)

d = tf.unstack(c, axis=0)
print(type(d))  # 
print(d[0].shape)  # (4, 35, 8)

e = tf.unstack(c, axis=-1)
print(len(e)) # 8
print(e[0].shape)  # (2, 4, 35)   范围e[0]~e[7]

tf.split(a, axis = , num_or_size_splits = )

a = tf.ones([4, 35, 8])
b = tf.ones([4, 35, 8])
c = tf.stack([a, b], axis=0)
print(c.shape)  # (2, 4, 35, 8)

d = tf.split(c, axis=3, num_or_size_splits=2)  # 分成两份
print(type(d))  # 
print(len(d))  # 2
print(d[0].shape)  # (2, 4, 35, 4)

e = tf.split(c, axis=3, num_or_size_splits=[2, 2, 4])
print(e[0].shape)  # (2, 4, 35, 2)
print(e[2].shape)  # (2, 4, 35, 4)

数据统计

tensorflow2.0---笔记2 tensor高阶操作_第5张图片
向量的范数:
tensorflow2.0---笔记2 tensor高阶操作_第6张图片

tf.norm (范数)

a = tf.ones([2, 2])
print(tf.norm(a)) # tf.Tensor(2.0, shape=(), dtype=float32)  
# 不指定几范数和轴,默认二范数
print(tf.sqrt(tf.reduce_sum(tf.square(a))))  

你可能感兴趣的:(tensorflow2.0---笔记2 tensor高阶操作)