tensorflow v2.0入门教程——02基本操作

╰+攻爆jí腚メ 2023-08-17 17:31 180阅读 0赞

个人博客

tensor

tensor即张量,张量的数学含义是多维数组,标量(数字)可以看作是0维的张量。一维数组称为1维向量,二维数组称为矩阵。在神经网络学习中,几乎所有的数据都可以看作张量,如神经网络的权重,偏置等。

输出hello world

  1. import tensorflow as tf
  2. hello = tf.constant('hello world') # 创建一个常量
  3. print(hello) # 输出
  4. print(hello.numpy()) # 输出张量的值
  5. print(hello.shape) # 输出维度
  6. print(hello.dtype) # 输出张量类型

输出结果

  1. tf.Tensor(b'hello world', shape=(), dtype=string)
  2. b'hello world'

shape是维度,标量是0维,[1,2,3]是1维。[[1,2],[3,4]]是2维,shape=(2,2)。
dtype是张量类型。

基本张量操作

  1. import tensorflow as tf
  2. # 定义常量
  3. a = tf.constant(3)
  4. b = tf.constant(4)
  5. c = tf.constant(5)
  6. matrix1 = tf.constant([[1., 2.], [3., 4.]])
  7. matrix2 = tf.constant([[5., 6.], [7., 8.]])
  8. add = tf.add(a, b) # 求和
  9. sub = tf.subtract(a, b) # 求差
  10. mul = tf.multiply(a, b) # 求积
  11. div = tf.divide(a, b) # 相除
  12. mean = tf.reduce_mean([a, b, c]) # 求平均数
  13. sum = tf.reduce_sum([a, b, c]) # 求和
  14. product = tf.matmul(matrix1, matrix2) # 矩阵相乘
  15. # 输出张量的值
  16. print("add =", add.numpy())
  17. print("sub =", sub.numpy())
  18. print("mul =", mul.numpy())
  19. print("div =", div.numpy())
  20. print("mean =", mean.numpy())
  21. print("sum =", sum.numpy())
  22. print("product=", product.numpy())

输出结果

  1. add = 7
  2. sub = -1
  3. mul = 12
  4. div = 0.75
  5. mean = 4
  6. sum = 12
  7. product= [[19. 22.]
  8. [43. 50.]]

个人博客
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,180人围观)

还没有评论,来说两句吧...

相关阅读