tf.add()和tf.matmul()的简单实现
import tensorflow as tf
# tf2默认为即时执行模式
# TensorFlow 使用张量(tensor)作为数据的基本单位。TensorFlow 的张量在概念上等同于多维数组,
# 我们可以使用它来描述数学中的标量(零维数组)、向量(一维数组)、矩阵(二维数组)等
# 定义一个随机数(标量)
random_float = tf.random.uniform(shape=())
print(random_float)
random_int = tf.random.uniform(maxval=10, dtype=tf.int32, shape=())
print(random_int)
# 定义一个有2个元素的零向量
zero_vector = tf.zeros(shape=(2))
# 定义两个2×2的常量矩阵
A = tf.constant([[1., 2.], [3., 4.]])
B = tf.constant([[5., 6.], [7., 8.]])
# 张量的重要属性是形状、类型和值,它们分别可以通过张量的 shape、dtype 属性和numpy()方法获得。
# 查看矩阵A的形状、类型和值
print(A.shape) # 输出(2, 2),即矩阵的长和宽均为2
print(A.dtype) # 输出<dtype: 'float32'>
# 张量的numpy()方法是将张量的值转换为一个 NumPy数组。
print(A.numpy()) # 输出[[1. 2.]
# [3. 4.]]
C = tf.add(A, B) # 计算矩阵A和B的和
D = tf.matmul(A, B) # 计算矩阵A和B的乘积
print(C)
print(D)