文章目录

  • 一、合并与分割
    • 1. tf.concat-合并-原有的维度上进行累加
    • 2.tf.stack-合并-创造一个新的维度
    • 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.案例
  • 四、填充与复制
    • 1.tf.pad-数据的填充
    • 2.tf.tile-数据的复制
  • 五、张量的限幅
    • 1.tf.clip_by_value—根据值来裁剪
    • 2.tf.clip_by_norm-根据范数裁剪
    • 3.tf.nn.relu—将矩阵中每行小于0的值置0
    • 4.tf.clip_by_global_norm-等比例裁剪
    • 5.案例
  • 六、高阶op
    • 1.tf.where—配合tf.gather_nd使用
    • 2.tf.scatter_nd-根据坐标有目的的更新
    • 3.tf.meshgrid-生成一个坐标轴
    • 4.案例

一、合并与分割

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 resif __name__ == '__main__':# 正态分布output = tf.random.normal([10,6])# 使6类概率总和为1output = 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)print('pred:',pred.numpy())print('label:',target.numpy())acc = accuracy(output,target,topk=(1,2,3,4,5,6))print('top-1-6 acc:',acc)
prob: [[0.25310278 0.21715644 0.16043882 0.13088997 0.04334083 0.19507109][0.05892418 0.04548917 0.00926314 0.14529602 0.66777605 0.07325139][0.09742808 0.08304427 0.07460099 0.04067177 0.626185   0.07806987][0.20478569 0.12294924 0.12010485 0.13751231 0.36418733 0.05046057][0.11872064 0.31072393 0.12530336 0.1552888  0.2132587  0.07670452][0.01519807 0.09672114 0.1460476  0.00934331 0.5649092  0.16778067][0.04199061 0.18141054 0.06647632 0.6006175  0.03198383 0.07752118][0.09226219 0.2346089  0.13022321 0.16295874 0.05362028 0.3263266 ][0.07019574 0.0861177  0.10912605 0.10521299 0.2152082  0.4141393 ][0.01882887 0.26597694 0.19122466 0.24109262 0.14920162 0.13367532]]
pred: [0 4 4 4 1 4 3 5 5 1]
label: [0 2 3 4 2 4 2 3 5 5]
top-1-6 acc: [0.4000000059604645, 0.4000000059604645, 0.5, 0.699999988079071, 0.800000011920929, 1.0]

四、填充与复制

1.tf.pad-数据的填充




2.tf.tile-数据的复制


五、张量的限幅

1.tf.clip_by_value—根据值来裁剪

2.tf.clip_by_norm-根据范数裁剪

3.tf.nn.relu—将矩阵中每行小于0的值置0

4.tf.clip_by_global_norm-等比例裁剪

Gradient clipping梯度裁剪

5.案例

# 将无关信息屏蔽掉
import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers# 列出你所有的物理GPU,设置内存自动增长
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:tf.config.experimental.set_memory_growth(gpu, True)print(tf.__version__)(x, y), _ = datasets.mnist.load_data()
x = tf.convert_to_tensor(x, dtype=tf.float32) / 50.
y = tf.convert_to_tensor(y)
y = tf.one_hot(y, depth=10)
print('x:', x.shape, 'y:', y.shape)
train_db = tf.data.Dataset.from_tensor_slices((x, y)).batch(128).repeat(30)
x, y = next(iter(train_db))
print('sample:', x.shape, y.shape)# print(x[0], y[0])def main():# 784 => 512w1, b1 = tf.Variable(tf.random.truncated_normal([784, 512], stddev=0.1)), tf.Variable(tf.zeros([512]))# 512 => 256w2, b2 = tf.Variable(tf.random.truncated_normal([512, 256], stddev=0.1)), tf.Variable(tf.zeros([256]))# 256 => 10w3, b3 = tf.Variable(tf.random.truncated_normal([256, 10], stddev=0.1)), tf.Variable(tf.zeros([10]))# 优化器optimizer = optimizers.SGD(lr=0.01)for step, (x, y) in enumerate(train_db):# [b, 28, 28] => [b, 784]x = tf.reshape(x, (-1, 784))with tf.GradientTape() as tape:# layer1.h1 = x @ w1 + b1h1 = tf.nn.relu(h1)# layer2h2 = h1 @ w2 + b2h2 = tf.nn.relu(h2)# outputout = h2 @ w3 + b3# out = tf.nn.relu(out)# compute loss# [b, 10] - [b, 10]loss = tf.square(y - out)# [b, 10] => [b]loss = tf.reduce_mean(loss, axis=1)# [b] => scalarloss = tf.reduce_mean(loss)# compute gradientgrads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])print('==before==')for g in grads:print(tf.norm(g))# 对所有可训练参数进行等比例裁剪grads, _ = tf.clip_by_global_norm(grads, 15)print('==after==')for g in grads:print(tf.norm(g))# update w' = w - lr*gradoptimizer.apply_gradients(zip(grads, [w1, b1, w2, b2, w3, b3]))if step % 100 == 0:print(step, 'loss:', float(loss))if __name__ == '__main__':main()

六、高阶op

1.tf.where—配合tf.gather_nd使用

tf.where(cond)—返回元素为True的坐标

tf.where(cond,A,B)—表示根据cond将A中的元素筛选后替换到B中相同位置

import tensorflow as tfa = tf.ones([3, 3])
b = tf.zeros([3, 3])
mask = [[1, 0, 0], [0, 0, 1], [0, 1, 1]]
c = tf.convert_to_tensor(mask)
cc = tf.cast(c, dtype=tf.bool)
print(tf.where(cc, b, a))
tf.Tensor(
[[0. 1. 1.][1. 1. 0.][1. 0. 0.]], shape=(3, 3), dtype=float32)

2.tf.scatter_nd-根据坐标有目的的更新




3.tf.meshgrid-生成一个坐标轴


4.案例

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'import tensorflow as tf
import matplotlib.pyplot as pltdef fun(x):""":param x: [b,2]:return:"""z = tf.math.sin(x[...,0]) + tf.math.sin(x[...,1])return zif __name__ == '__main__':x = tf.linspace(0.,2*3.14,500)y = tf.linspace(0.,2*3.14,500)# [500,500]point_x, point_y = tf.meshgrid(x,y)# [500,500,2]points = tf.stack([point_x,point_y],axis=2)print('points:',points.shape)z = fun(points)print('z:',z.shape)plt.figure('plot 2d func value')plt.imshow(z,origin='lower',interpolation='none')plt.colorbar()plt.figure('plot 2d func contour')# 画出等高线plt.contour(point_x,point_y,z)plt.colorbar()plt.show()


深度学习TF—2.TensorFlow2高阶操作相关推荐

  1. TensorFlow2 入门指南 | 06 TensorFLow2 高阶操作汇总

    前言: 本专栏在保证内容完整性的基础上,力求简洁,旨在让初学者能够更快地.高效地入门TensorFlow2 深度学习框架.如果觉得本专栏对您有帮助的话,可以给一个小小的三连,各位的支持将是我创作的最大 ...

  2. 深度学习(17)TensorFlow高阶操作六: 高阶OP

    深度学习(17)TensorFlow高阶操作六: 高阶OP 1. Where(tensor) 2. where(cond, A, B) 3. 1-D scatter_nd 4. 2-D scatter ...

  3. 深度学习(16)TensorFlow高阶操作五: 张量限幅

    深度学习(16)TensorFlow高阶操作五: 张量限幅 1. clip_by_value 2. relu 3. clip_by_norm 4. Gradient clipping 5. 梯度爆炸实 ...

  4. 深度学习(15)TensorFlow高阶操作四: 填充与复制

    深度学习(15)TensorFlow高阶操作四: 填充与复制 1. Pad 2. 常用于Image Padding 3. tile 4. tile VS broadcast_to Outline pa ...

  5. 深度学习(14)TensorFlow高阶操作三: 张量排序

    深度学习(14)TensorFlow高阶操作三: 张量排序 一. Sort, argsort 1. 一维Tensor 2. 多维Tensor 二. Top_k 三. Top-k accuracy(To ...

  6. 深度学习(12)TensorFlow高阶操作一: 合并与分割

    深度学习(12)TensorFlow高阶操作一: 合并与分割 1. concat 2. stack: create new dim 3. Dim mismatch 4. unstuck 5. spli ...

  7. Tensorflow学习四---高阶操作

    Tensorflow学习四-高阶操作 Merge and split 1.tf.concat 拼接 a = tf.ones([4,32,8]) b = tf.ones([2,32,8]) print( ...

  8. 深度学习(6)TensorFlow基础操作二: 创建Tensor

    深度学习(6)TensorFlow基础操作二: 创建Tensor 一. 创建方式 1. From Numpy,List 2. zeros,ones (1) tf.zeros() (2) tf.zero ...

  9. 深度学习(11)TensorFlow基础操作七: 向前传播(张量)实战

    深度学习(11)TensorFlow基础操作七: 向前传播(张量)实战 1. 导包 2. 加载数据集 3. 转换数据类型 4. 查看x.shape, y.shape, x.dtype, y.dtype ...

  10. 深度学习(10)TensorFlow基础操作六: 数学运算

    深度学习(10)TensorFlow基础操作六: 数学运算 1. Operation type 2. + - * / % // 3. tf.math.log & tf.exp 4. log2, ...

最新文章

  1. html4与html5效果,浅谈HTML5与HTML4的10个关键区别
  2. 关于JS 事件冒泡和onclick,click,on()事件触发顺序
  3. 客户端手册_山东省税务局社保费管理客户端企业缴费操作手册
  4. DCMTK:类DSRBasicCodedEntry和DSRCodedEntryValue的测试程序
  5. 【PAG组件】-从解码渲染层面对比 PAG 与 lottie
  6. 【转载】实用的人际关系经验
  7. 51单片机HS0038红外遥控程序
  8. C# 阿拉伯数字转换为中文数字/中文数字转换为阿拉伯数字
  9. 运营支持是干什么_运营|你们运营到底是干什么的?
  10. MySQL常用的关键字查询用法
  11. 用聊天记录当证据 对方改了微信号怎么证明他是他
  12. TCP状态转换图文解说
  13. 零售行业新渠道,效率居然这么高?
  14. Fabric Block区块结构解析
  15. 69、Android获取每日运动步数
  16. win10计算机怎么新增用户,win10 如何添加管理员账户_win10 添加管理员账户方法-win7之家...
  17. adb shell input(系统服务:input)
  18. php-fpm 启动失败,php-fpm自启动失败问题排查
  19. 全国大学生信息安全大赛线下赛crypto3题解
  20. AutoJs学习-投币小游戏

热门文章

  1. 树组件:主要配置项、属性、方法
  2. Cookie使用基础
  3. shell脚本基础练习题
  4. 常用正则表达式(regular expression)
  5. HTML的form表单标签
  6. 解决datalist中单选按钮可以多选的问题(Asp.Net)
  7. win10下安装Cygwin配置gcc编译环境
  8. 2019icpc南京网络赛 A The beautiful values of the palace(离线+树状数组)
  9. ubuntu下mysql数据库存储路径修改
  10. BZOJ4241历史研究题解