Tensorflow2.0入门教程2:认识张量Tensor

知识点

1.认识张量Tensor:标量、向量、矩阵,张量的属性(形状、类型和值);

2.Tensorflow运算操作:加、减乘除、矩阵运算等;

认识张量Tensor

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

导入 TensorFlow:

import tensorflow as tf

1.定义张量、向量、矩阵

# 定义一个随机数(标量)

random_float = tf.random.uniform(shape=())
print(random_float)

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

# 定义两个2×2的常量矩阵
A = tf.constant([[1., 2.], [3., 4.]])
B = tf.constant([[5., 6.], [7., 8.]])
print(A)
print(B)

tf.Tensor(0.6339736, shape=(), dtype=float32)
tf.Tensor([0. 0.], shape=(2,), dtype=float32)
tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[5. 6.]
 [7. 8.]], shape=(2, 2), dtype=float32)

张量的重要属性是其形状、类型和值。可以通过张量的 shape 、 dtype 属性和 numpy() 方法获得。例如:

# 查看矩阵A的形状、类型和值
print(A.shape)      # 输出(2, 2),即矩阵的长和宽均为2
print(A.dtype)      # 输出<dtype: 'float32'>
print(A.numpy())    # 输出[[1. 2.]
                    #      [3. 4.]],numpy() 方法是将张量的值转换为一个 NumPy 数组

(2, 2)
<dtype: 'float32'>
[[1. 2.]
 [3. 4.]]

2.Tensorflow运算操作

d = tf.add(A,B)  # 计算矩阵A和B的和
print(d)

tf.Tensor(
[[ 6.  8.]
 [10. 12.]], shape=(2, 2), dtype=float32)

e = tf.matmul(A,B)  # 计算矩阵A和B的乘积
print(e)

tf.Tensor(
[[19. 22.]
 [43. 50.]], shape=(2, 2), dtype=float32)

猜你喜欢

转载自blog.csdn.net/zhaomengsen/article/details/130873930