【TensorFlow】笔记:基本操作-张量操作(一)

深度学习入门笔记

共 2186字,需浏览 5分钟

 · 2021-01-26


TensorFlow 使用 张量 (Tensor)作为数据的基本单位。TensorFlow 的张量在概念上等同于多维数组,我们可以使用它来描述数学中的标量(0 维数组)、向量(1 维数组)、矩阵(2 维数组)等各种量。




基础知识


首先,我们导入tensorflow,

import tensorflow as tf


我们来创建一些基本张量,

tensor1 = tf.constant(4)print(tensor1)
# outputtf.Tensor(4, shape=(), dtype=int32)

这是一个“标量”(或称“0 秩”张量)。标量包含单个值,但没有“轴”。


tensor2 = tf.constant([2.0, 3.0, 4.0])print(tensor2)
# outputtf.Tensor([2. 3. 4.], shape=(3,), dtype=float32)

这是一个“向量”(或称“1 秩”张量)就像一个值的列表。向量有 1 个轴。


tensor3 = tf.constant([[1, 2],                             [3, 4],                             [5, 6]], dtype=tf.float16)print(tensor3)
# outputtf.Tensor([[1. 2.] [3. 4.] [5. 6.]], shape=(3, 2), dtype=float16)

这是一个“矩阵”(或称“2 秩”张量)有 2 个轴。


总结


张量的轴可能更多,下面是一个包含 3 个轴的张量:

tensor4 = 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]],])
print(tensor4)
# outputtf.Tensor([[[ 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]]], shape=(3, 2, 5), dtype=int32)




张量通常包含浮点型和整型数据,但是还有许多其他数据类型,包括:

  • 复杂的数值

  • 字符串


tf.Tensor 基类要求张量是“矩形”——也就是说,每个轴上的每一个元素大小相同。但是,张量有可以处理不同形状的特殊类型。

我们可以对张量执行基本数学运算,包括加法、逐元素乘法和矩阵乘法运算。


a = tf.constant([[1, 2],                 [3, 4]])b = tf.constant([[1, 1],                 [1, 1]])
print(tf.add(a, b), "\n"# 对应元素相加print(tf.multiply(a, b), "\n"# 对应元素相乘print(tf.matmul(a, b), "\n"# 做矩阵乘法
# outputtf.Tensor([[2 3] [4 5]], shape=(2, 2), dtype=int32)
tf.Tensor([[1 2] [3 4]], shape=(2, 2), dtype=int32)
tf.Tensor([[3 3] [7 7]], shape=(2, 2), dtype=int32)


print(a + b, "\n") # element-wise additionprint(a * b, "\n") # element-wise multiplicationprint(a @ b, "\n") # matrix multiplication
# outputtf.Tensor([[2 3] [4 5]], shape=(2, 2), dtype=int32)
tf.Tensor([[1 2] [3 4]], shape=(2, 2), dtype=int32)
tf.Tensor([[3 3] [7 7]], shape=(2, 2), dtype=int32)


各种运算 (op) 都可以使用张量。

a = tf.constant([[4.0, 5.0], [10.0, 1.0]])
# 找最大值print(tf.reduce_max(a))# 找最大值的索引print(tf.argmax(a)) # outputtf.Tensor(10.0, shape=(), dtype=float32)tf.Tensor([1 0], shape=(2,), dtype=int64)



点击上方“蓝字”关注本公众号

点击上方“蓝字”关注本公众号

浏览 25
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报