Tensorflow2.0 笔记-1

    科技2025-07-23  9

    一、张量生成

    创建一个张量

    List item # tf.constant(张量内容,dtype=数据类型(可选)) import tensorflow as tf a = tf.constant([1,5],dtype=tf.int64) print(a) 根据逗号隔开的数字,代表是几维的张量

    将numpy的数据类型转换为Tensor数据类型

    tf.convert_to_tensor(数据名,dtype=数据类型(可选))

    创建全为0的张量

    tf.zeros(维度) a=tf.zeros([2,3])

    创建全为1的张量

    tf.ones(维度) b=tf.ones([4])

    创建全为指定数值的张量

    tf.fill([2,2],9)

    维度:一维 直接写一个数字; 二维: 【行,列】; 三维:【a,b,c,d】

    生成正态分布的随机数,默认均值为0,标准差为1 # tf.ranodm.normal(维数,mean=均值,stddev=标准差) # 生成的这些随机数都负荷以0.5为均值,1为标准差 d = tf.random.normal([2,2],mean=0.5,stddev=1) print(d) 生成阶段式正态分布的随机数 tf.ranodm.truncated_normal(维数,mean=均值,stddev=标准差) 生成均匀分布的随机数 tf.ranodm.uniform(维数,minval最小值,maxval=最大值)

    二、常用函数

    四则运算

    a = tf.ones([1, 3]) b = tf.fill([1, 3], 3.) print("a:", a) print("b:", b) print("a+b:", tf.add(a, b)) print("a-b:", tf.subtract(a, b)) print("a*b:", tf.multiply(a, b)) print("b/a:", tf.divide(b, a)) # 输出 a: tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32) b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32) a+b: tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32) a-b: tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32) a*b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32) b/a: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)

    平方、次方、开方

    a = tf.fill([1, 2], 3.) print("a:", a) print("a的平方:", tf.pow(a, 3)) print("a的平方:", tf.square(a)) print("a的开方:", tf.sqrt(a)) """ a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32) a的平方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32) a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32) a的开方: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32) """

    矩阵相乘

    a = tf.ones([3, 2]) b = tf.fill([2, 3], 3.) print("a:", a) print("b:", b) print("a*b:", tf.matmul(a, b)) """ a*b: tf.Tensor( [[6. 6. 6.] [6. 6. 6.] [6. 6. 6.]], shape=(3, 3), dtype=float32) """

    切分

    切分传入张量的第一维度,生成输入特征-标签对。构建数据集 numpy和tensor格式都可用该语句读入数据 dataset = tf.data.Dataset.from_tensor_slices((输入特征, 标签))

    features = tf.constant([12, 23, 10, 17]) labels = tf.constant([0, 1, 1, 0]) dataset = tf.data.Dataset.from_tensor_slices((features, labels)) for element in dataset: print(element)

    运行结果:

    (<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>) (<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>) (<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>) (<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)

    tf.GradientTape

    with结构记录计算过程,gradient求出张量的梯度

    with.tf.GradientTape() as tape: 若干计算过程 grad = tape.gradient(函数,对谁求导)

    例子:

    with tf.GradientTape() as tape: # w 初始值为3 w = tf.Variable(tf.constant(3.0)) # 损失函数是w的平方 loss = tf.pow(w, 2) grad = tape.gradient(loss, w) # loss函数对w求导 print(grad) # tf.Tensor(6.0, shape=(), dtype=float32)

    enumerate

    enumerate是python的内建函数,它可以遍历每个元素(如列表、字符串或元组),组合为:索引 元素,常用在for循环中使用。

    enumerate(列表名)

    seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print(i, element) 运行结果: 0 one 1 two 2 three

    tf.one_hot

    在分类问题时,常用tf.one_hot做标签。 tf.one_hot() 函数将带转换数据,转换为ont-hot形式的数据输出。 tf.one_hot(带转换数据,depth=几分类)

    classes = 3 labels = tf.constant([1, 0, 2]) # 输入的元素值最小为0,最大为2 output = tf.one_hot(labels, depth=classes) print("result of labels1:", output) 运行结果: result of labels1: tf.Tensor( [[0. 1. 0.] [1. 0. 0.] [0. 0. 1.]], shape=(3, 3), dtype=float32)

    tf.nn.sotfmax

    assign_sub

    常用于参数的自更新。

    赋值操作,更新参数的值并返回。调用assign_sub前,先用 tf.Variable 定义变量w为 可训练(可自更新)。

    w.assign_sub(w要自减的内容)

    x = tf.Variable(4) x.assign_sub(1) print("x:", x) # 4-1=3 # x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

    tf.argmax

    返回张量沿指定维度最大值的索引

    test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]]) print("test:\n", test) print("每一列的最大值的索引:", tf.argmax(test, axis=0)) # 返回每一列最大值的索引 print("每一行的最大值的索引", tf.argmax(test, axis=1)) # 返回每一行最大值的索引 输出: test: [[1 2 3] [2 3 4] [5 4 3] [8 7 2]] 每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64) 每一行的最大值的索引 tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
    Processed: 0.062, SQL: 8