tensorflow 初学前须知: 张量和tensorflow的操作函数

一、张量 == 数组

1、对应关系

TensorFlow使用 张量 (Tensor)作为数据的基本单位。
标量(0维数组)、向量(1维数组)、矩阵(2维数组)

# 定义一个随机数(标量)
random_float = tf.random.uniform(shape=())

# 定义一个有2个元素的零向量
zero_vector = tf.zeros(shape=(2))

# 定义两个2×2的常量矩阵
A = tf.constant([[1., 2.], [3., 4.]])	#Python中可以使用整数后加小数点表示将该整数定义为浮点数类型。例如 3. 代表浮点数 3.0。
B = tf.constant([[5., 6.], [7., 8.]])

2、张量的属性

shape()输出矩阵的长宽,即A*B
dtype()输出矩阵的类型,默认为float32,也可以定义时特别指定zero_vector = tf.zeros(shape=(2), dtype=tf.int32)

# 查看矩阵A的形状、类型和值
print(A.shape)      # 输出(2, 2),即矩阵的长和宽均为2
print(A.dtype)      # 输出<dtype: 'float32'>
print(A.numpy())    # 输出[[1. 2.]   			#这里似乎是因为版本的问题,一直提示'Tensor' object has no attribute 'numpy'
                    #      [3. 4.]]

数据转换
在这里插入图片描述
形状操作
在这里插入图片描述

3、一顿操作猛如虎

TensorFlow中有大量的张量操作API,包括数学运算、张量形状操作、切片和连接(等多种类型,可以通过查阅TensorFlow的官方API文档 来进一步了解。

tf.add(),求和
tf.matmul(),矩阵乘
tf.GradientTape(),自动求导

在这里插入图片描述
在这里插入图片描述

A = tf.constant([[1.,2.],[3.,4.]])
B = tf.constant([[5.,6.],[7.,8.]])
C = tf.add(A,B)
D = tf.matmul(A,B)
print(A.shape)      # 输出(2, 2),即矩阵的长和宽均为2
print(A.dtype)      # 输出<dtype: 'float32'>
with tf.Session() as sess:
    print(sess.run(C))
    print(sess.run(D))

运行:
(2, 2)
<dtype: 'float32'>
[[ 6.  8.]
 [10. 12.]]
[[19. 22.]
 [43. 50.]]
发布了70 篇原创文章 · 获赞 5 · 访问量 3534

猜你喜欢

转载自blog.csdn.net/qq_42647903/article/details/99867012