深度学习TF—2.TensorFlow2高阶操作

本文详细介绍了TensorFlow2中的高阶操作,包括张量的合并与分割、数据统计、排序、填充与复制、限幅以及高阶操作。讲解了如tf.concat、tf.stack、tf.norm、tf.reduce_max/min/mean/sum、tf.argsort、tf.sort、tf.pad、tf.tile、tf.clip_by_value等关键函数的用法,是理解TensorFlow2高级特性的宝贵资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、合并与分割

1. tf.concat-合并-原有的维度上进行累加

concat操作需要满足除拼接维度外,其余维度均相等
在这里插入图片描述

2.tf.stack-合并-创造一个新的维度

stack操作需要Tensor维度均相等
在这里插入图片描述

3.tf.unstack-分割

不能指定打散的数量,只能按维度进行分割
在这里插入图片描述

4.tf.split-分割

可以指定打散的数量
在这里插入图片描述

二、数据统计操作

1.tf.norm—张量的范数

二范数
在这里插入图片描述
一范数
在这里插入图片描述

2.tf.reduce_max/min/mean/sum—张量的最大值、最小值、平均值、和

在这里插入图片描述

3.tf.argmax/argmin—张量最大值的位置与最小值的位置

在这里插入图片描述

4.tf.equal—张量的比较

在这里插入图片描述

5.tf.unique—张量的独特值

在这里插入图片描述

三、张量排序

1.tf.sort-排序/tf.argsort-排序并返回索引

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

2.tf.math.top_k-最大值的前几个

在这里插入图片描述

3.案例
# 将无关信息屏蔽掉
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
tf.random.set_seed(2467)

# output->[b,n] target->[b,]
def accuracy(output,target,topk=(1,)):
    maxk = max(topk)
    batch_size = target.shape[0]

    # 返回最大值前maxk个的索引
    pred = tf.math.top_k(output,maxk).indices
    # 转置
    pred = tf.transpose(pred,perm=[1,0])
    # 将target广播成pred形状
    target_ = tf.broadcast_to(target,pred.shape)
    # 比较
    correct = tf.equal(pred,target_)

    res = []
    for k in topk:
        correct_k = tf.cast(tf.reshape(correct[:k],[-1]),dtype=tf.float32)
        # print('123=',correct_k)
        correct_k = tf.reduce_sum(correct_k)
        acc = float(correct_k / batch_size)
        res.append(acc)

    return res

if __name__ == '__main__':
    # 正态分布
    output = tf.random.normal([10,6])
    # 使6类概率总和为1
    output = tf.math.softmax(output,axis=1)
    # 均匀分布
    target = tf.random.uniform([10],maxval=6,dtype=tf.int32)
    print('prob:',output.numpy())
    pred = tf.argmax(output,axis=1)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值