1. 进阶操作:合并与分割,数据统计,张量比较,填充与复制,数据限幅,高级操作
  2. mnist测试实战

进阶操作:

####1.合并与分割####a = tf.random.normal([4,35,8]) # 模拟成绩册 A
b = tf.random.normal([6,35,8]) # 模拟成绩册 B
tf.concat([a,b],axis=0) # 拼接合并成绩册a = tf.random.normal([10,35,4])
b = tf.random.normal([10,35,4])
tf.concat([a,b],axis=2) # 在科目维度上拼接a = tf.random.normal([4,32,8])
b = tf.random.normal([6,35,8])
#tf.concat([a,b],axis=0) # 非法拼接,其他维度长度不相同a = tf.random.normal([35,8])
b = tf.random.normal([35,8])
tf.stack([a,b],axis=0) # 堆叠合并为 2 个班级,班级维度插入在最前a = tf.random.normal([35,8])
b = tf.random.normal([35,8])
tf.stack([a,b],axis=-1) # 在末尾插入班级维度a = tf.random.normal([35,8])
b = tf.random.normal([35,8])
tf.concat([a,b],axis=0) # 拼接方式合并,没有 2 个班级的概念a = tf.random.normal([35,4])
b = tf.random.normal([35,8])
#tf.stack([a,b],axis=-1) # 非法堆叠操作,张量 shape 不相同x = tf.random.normal([10,35,8])
# 等长切割为 10 份
result = tf.split(x, num_or_size_splits=10, axis=0)
len(result) # 返回的列表为 10 个张量的列表result[0] # 查看第一个班级的成绩册张量x = tf.random.normal([10,35,8])
# 自定义长度的切割,切割为 4 份,返回 4 个张量的列表 result
result = tf.split(x, num_or_size_splits=[4,2,2,2] ,axis=0)
len(result)result[0]x = tf.random.normal([10,35,8])
result = tf.unstack(x,axis=0) # Unstack 为长度为 1 的张量
len(result) # 返回 10 个张量的列表result[0] # 第一个班级#结果略####2.数据统计####x = tf.ones([2,2])
tf.norm(x,ord=1) # 计算 L1 范数tf.norm(x,ord=2) # 计算 L2 范数import numpy as np
tf.norm(x,ord=np.inf) # 计算∞范数x = tf.random.normal([4,10]) # 模型生成概率
tf.reduce_max(x,axis=1) # 统计概率维度上的最大值tf.reduce_min(x,axis=1) # 统计概率维度上的最小值tf.reduce_mean(x,axis=1) # 统计概率维度上的均值x = tf.random.normal([4,10])
# 统计全局的最大、最小、均值、和,返回的张量均为标量
tf.reduce_max(x),tf.reduce_min(x),tf.reduce_mean(x)out = tf.random.normal([4,10]) # 模拟网络预测输出
y = tf.constant([1,2,2,0]) # 模拟真实标签
y = tf.one_hot(y,depth=10) # one-hot 编码
loss = keras.losses.mse(y,out) # 计算每个样本的误差
loss = tf.reduce_mean(loss) # 平均误差,在样本数维度上取均值
loss # 误差标量out = tf.random.normal([4,10])
tf.reduce_sum(out,axis=-1) # 求最后一个维度的和out = tf.random.normal([2,10])
out = tf.nn.softmax(out, axis=1) # 通过 softmax 函数转换为概率值
outpred = tf.argmax(out, axis=1) # 选取概率最大的位置
pred#结果略####3.张量比较####out = tf.random.normal([100,10])
out = tf.nn.softmax(out, axis=1) # 输出转换为概率
pred = tf.argmax(out, axis=1) # 计算预测值# 模型生成真实标签
y = tf.random.uniform([100],dtype=tf.int64,maxval=10)out = tf.equal(pred,y) # 预测值与真实值比较,返回布尔类型的张量out = tf.cast(out, dtype=tf.float32) # 布尔型转 int 型
correct = tf.reduce_sum(out) # 统计 True 的个数####4.填充与复制####a = tf.constant([1,2,3,4,5,6]) # 第一个句子
b = tf.constant([7,8,1,6]) # 第二个句子
b = tf.pad(b, [[0,2]]) # 句子末尾填充 2 个 0
b # 填充后的结果tf.stack([a,b],axis=0) # 堆叠合并,创建句子数维度total_words = 10000 # 设定词汇量大小
max_review_len = 80 # 最大句子长度
embedding_len = 100 # 词向量长度
# 加载 IMDB 数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=total_words)
# 将句子填充或截断到相同长度,设置为末尾填充和末尾截断方式
x_train = keras.preprocessing.sequence.pad_sequences(x_train,maxlen=max_review_len,truncating='post',padding='post')
x_test = keras.preprocessing.sequence.pad_sequences(x_test,maxlen=max_review_len,truncating='post',padding='post')
print(x_train.shape, x_test.shape) # 打印等长的句子张量形状x = tf.random.normal([4,28,28,1])
# 图片上下、左右各填充 2 个单元
tf.pad(x,[[0,0],[2,2],[2,2],[0,0]])x = tf.random.normal([4,32,32,3])
tf.tile(x,[2,3,3,1]) # 数据复制#输出略####5.数据限幅####x = tf.range(9)
tf.maximum(x,2) # 下限幅到 2tf.minimum(x,7) # 上限幅到 7x = tf.range(9)
tf.minimum(tf.maximum(x,2),7) # 限幅为 2~7x = tf.range(9)
tf.clip_by_value(x,2,7) # 限幅为 2~7####6.高级操作####x = tf.random.uniform([4,35,8],maxval=100,dtype=tf.int32) # 成绩册张量tf.gather(x,[0,1],axis=0) # 在班级维度收集第 1~2 号班级成绩册# 收集第 1,4,9,12,13,27 号同学成绩
tf.gather(x,[0,3,8,11,12,26],axis=1)tf.gather(x,[2,4],axis=2) # 第 3,5 科目的成绩a=tf.range(8)
a=tf.reshape(a,[4,2]) # 生成张量 atf.gather(a,[3,1,0,2],axis=0) # 收集第 4,2,1,3 号元素students=tf.gather(x,[1,2],axis=0) # 收集第 2,3 号班级# 基于 students 张量继续收集
tf.gather(students,[2,3,5,26],axis=1) # 收集第 3,4,6,27 号同学x[1,1] # 收集第 2 个班级的第 2 个同学tf.stack([x[1,1],x[2,2],x[3,3]],axis=0)# 根据多维坐标收集数据
tf.gather_nd(x,[[1,1],[2,2],[3,3]])# 根据多维度坐标收集数据
tf.gather_nd(x,[[1,1,2],[2,2,3],[3,3,4]])# 根据掩码方式采样班级,给出掩码和维度索引
tf.boolean_mask(x,mask=[True, False,False,True],axis=0) #m ask=[True,False,False,True] 即采样第1和第4个班级的数据# 根据掩码方式采样科目
tf.boolean_mask(x,mask=[True,False,False,True,True,False,False,True],axis=2)x = tf.random.uniform([2,3,8],maxval=100,dtype=tf.int32)
tf.gather_nd(x,[[0,0],[0,1],[1,1],[1,2]]) # 多维坐标采集# 多维掩码采样
tf.boolean_mask(x,[[True,True,False],[False,True,True]])a = tf.ones([3,3]) # 构造 a 为全 1 矩阵
b = tf.zeros([3,3]) # 构造 b 为全 0 矩阵
# 构造采样条件
cond = tf.constant([[True,False,False],[False,True,False],[True,True,False]])
tf.where(cond,a,b) # 根据条件从 a,b 中采样cond # 构造的 cond 张量tf.where(cond) # 获取 cond 中为 True 的元素索引x = tf.random.normal([3,3]) # 构造 amask=x>0 # 比较操作,等同于 tf.math.greater()
maskindices=tf.where(mask) # 提取所有大于 0 的元素索引tf.gather_nd(x,indices) # 提取正数的元素值tf.boolean_mask(x,mask) # 通过掩码提取正数的元素值# 构造需要刷新数据的位置参数,即为 4、3、1 和 7 号位置
indices = tf.constant([[4], [3], [1], [7]])
# 构造需要写入的数据,4 号位写入 4.4,3 号位写入 3.3,以此类推
updates = tf.constant([4.4, 3.3, 1.1, 7.7])
# 在长度为 8 的全 0 向量上根据 indices 写入 updates 数据
tf.scatter_nd(indices, updates, [8])# 构造写入位置,即 2 个位置
indices = tf.constant([[1],[3]])
updates = tf.constant([# 构造写入数据,即 2 个矩阵[[5,5,5,5],[6,6,6,6],[7,7,7,7],[8,8,8,8]],[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
])
# 在 shape 为[4,4,4]白板上根据 indices 写入 updates
tf.scatter_nd(indices,updates,[4,4,4])x = tf.linspace(-8.,8,100) # 设置 x 轴的采样点
y = tf.linspace(-8.,8,100) # 设置 y 轴的采样点
x,y = tf.meshgrid(x,y) # 生成网格点,并内部拆分后返回
x.shape,y.shape # 打印拆分后的所有点的 x,y 坐标张量 shape#结果略

mnist测试实战:

#%%
import  matplotlib
from    matplotlib import pyplot as plt
# Default parameters for plots
matplotlib.rcParams['font.size'] = 20
matplotlib.rcParams['figure.titlesize'] = 20
matplotlib.rcParams['figure.figsize'] = [9, 7]
matplotlib.rcParams['font.family'] = ['STKaiTi']
matplotlib.rcParams['axes.unicode_minus']=False
import  tensorflow as tf
from    tensorflow import keras
from    tensorflow.keras import datasets, layers, optimizers
import  osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'
print(tf.__version__)def preprocess(x, y): # [b, 28, 28], [b]print(x.shape,y.shape)x = tf.cast(x, dtype=tf.float32) / 255.x = tf.reshape(x, [-1, 28*28])y = tf.cast(y, dtype=tf.int32)y = tf.one_hot(y, depth=10)return x,y#%%
(x, y), (x_test, y_test) = datasets.mnist.load_data()
print('x:', x.shape, 'y:', y.shape, 'x test:', x_test.shape, 'y test:', y_test)
#%%
batchsz = 512
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(1000)
train_db = train_db.batch(batchsz)
train_db = train_db.map(preprocess)
train_db = train_db.repeat(20)#%%test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.shuffle(1000).batch(batchsz).map(preprocess)
x,y = next(iter(train_db))
print('train sample:', x.shape, y.shape)
# print(x[0], y[0])#%%
def main():# learning ratelr = 1e-2accs,losses = [], []# 784 => 512w1, b1 = tf.Variable(tf.random.normal([784, 256], stddev=0.1)), tf.Variable(tf.zeros([256]))# 512 => 256w2, b2 = tf.Variable(tf.random.normal([256, 128], stddev=0.1)), tf.Variable(tf.zeros([128]))# 256 => 10w3, b3 = tf.Variable(tf.random.normal([128, 10], stddev=0.1)), tf.Variable(tf.zeros([10]))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] => scalarloss = tf.reduce_mean(loss)grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3]) for p, g in zip([w1, b1, w2, b2, w3, b3], grads):p.assign_sub(lr * g)# printif step % 80 == 0:print(step, 'loss:', float(loss))losses.append(float(loss))if step %80 == 0:# evaluate/testtotal, total_correct = 0., 0for x, y in test_db:# layer1.h1 = x @ w1 + b1h1 = tf.nn.relu(h1)# layer2h2 = h1 @ w2 + b2h2 = tf.nn.relu(h2)# outputout = h2 @ w3 + b3# [b, 10] => [b]pred = tf.argmax(out, axis=1)# convert one_hot y to number yy = tf.argmax(y, axis=1)# bool typecorrect = tf.equal(pred, y)# bool tensor => int tensor => numpytotal_correct += tf.reduce_sum(tf.cast(correct, dtype=tf.int32)).numpy()total += x.shape[0]print(step, 'Evaluate Acc:', total_correct/total)accs.append(total_correct/total)plt.figure()x = [i*80 for i in range(len(losses))]plt.plot(x, losses, color='C0', marker='s', label='训练')plt.ylabel('MSE')plt.xlabel('Step')plt.legend()plt.savefig('train.svg')plt.figure()plt.plot(x, accs, color='C1', marker='s', label='测试')plt.ylabel('准确率')plt.xlabel('Step')plt.legend()plt.savefig('test.svg')if __name__ == '__main__':main()


2022.4.13_tf-tf进阶相关推荐

  1. 2022/9/11 Python进阶--Linux版 持续更新

    常见操作系统 windows macos 乌班图Linux  对上控制软件 对下控制硬件 1.windows中 C D···等 被称为根目录 c:. 有多个根目录 2. Linux中 没有盘符的概念, ...

  2. B站2022保姆级Java进阶教程(一)Javaweb阶段

    No.1:Javaweb 学完web第一站就到了Javaweb这儿,web和Javaweb之间可是有很多相通的地方,想要做出一个合格的网页,web和Javaweb一个都不能少,但你真的做好准备学习Ja ...

  3. 50 条有趣的 Python 一行代码

    在学习Python的过程中,总会发现Python能够轻易的解决许多问题. 一些复杂的任务,甚至可以使用一行Python代码就能搞定. 下面给大家介绍50个有趣的Python一行代码,都很实用. 希望大 ...

  4. 今日行业报告更新10月25日

    今日报告分享 2022人力资源数字化转型白皮书:数字化人才管理,成就高绩效企业 2022服装零售企业人才选育趋势报告:数字驱动,成就风尚人才 2022中国智能人居产业研究报告:从端到云到用,揭秘人类居 ...

  5. Python开发一个炸金花小游戏,注意别玩上瘾了

    众所周知扑克牌可谓是居家旅行.桌面交友的必备道具,今天我们用 Python 来实现一个类似炸金花的扑克牌小游戏,先来看一下基本的游戏规则. 炸(诈)金花又叫三张牌,是在全国广泛流传的一种民间多人纸牌 ...

  6. 接口测试面试题及参考答案,就等你来看~

    你们公司的接口测试流程是? 接口测试我们是在XX项目做的,主要有XX接口,XX接口,XX接口等. 1.首先是从开发那里拿到API接口文档,了解接口业务.包括接口地址.请求方式,入参.出参,token鉴 ...

  7. 嵌入式软件测试的小结

    前言 文章内容为本人这三年来在嵌入式软件测试(黑盒)上的一些积累吧,说起来也挺快的,毕业三年的时间就这样过去了,在两家公司工作过(现在这家是第二家),这几年的测试项目基本都是围绕着嵌入式软件,同时需要 ...

  8. 100行Python代码,做一个打地鼠小游戏

    游戏画面 首先先进行游戏画面排版, class TopWindow(QWidget):def __init__(self, parent=None):super().__init__(parent)s ...

  9. 用 Python 写了一个天天酷跑(附源码)

    写出来的效果图就是这样了: 下面就更新一下全部的代码吧 还是老样子先定义 import pygame,sys import random 写一下游戏配置 width = 1200 #窗口宽度 heig ...

  10. Python写个益智小游戏来锻炼大脑

    游戏规则 珠玑棋的规则非常简单.它分为两方:攻击方和防守方.具体流程如下: 防守方写一个4位数字,每位数字不能重复 攻击方有10次猜测的机会,在每次机会里面,攻击方可以说出一个4位数,让防守方检查. ...

最新文章

  1. OpenCV图像序列生成视频,MATLAB图像生成avi视频,image2video。
  2. B2B2C多用户商城就等于零售吗?什么是新零售?新零售有哪些特点?
  3. PIE SDK波段合成
  4. [异常笔记] zookeeper集群启动异常: Cannot open channel to 2 at election address ……
  5. 寄存器在哪里_二、汇编之寄存器
  6. redis异步写入mysql_异步操作redis,mysql
  7. 查看grafana版本_使用 Prometheus 与 Grafana 为 Kubernetes 集群建立监控与警报机制
  8. 获取表单对象,得三种方法getElementById(), getElementsByName(), and getElementsByTagName() 和用法...
  9. 转:VCSA 6.7 升级到VCSA7.0
  10. 《快活帮》第三次作业:团队项目的原型设计
  11. Photoshop操作秘籍
  12. 权威cpu测试软件,权威CPU测试软件更新 CPU-Z v1.40.5
  13. Linux命令-关机命令详解
  14. 最详细的Android SDK下载安装及配置教程
  15. Xcode 使用手册之01 欢迎使用Xcode(Xcode中文文档手册)
  16. 叶俊|知行合一创纪录|杭州创纪录企业管理咨询有限公司董事长简介
  17. 集群通信组件Tribes之整体介绍
  18. jsp是java的一种吗_jsp是什么
  19. vba获取html代码数据,VBA获取网页表格数据
  20. 利用DirectShow开发C#版的MP3播放器(二)

热门文章

  1. 如何用js实现日期天数、时分秒的倒计时
  2. Linux用rm -rf 无法删除文件或者目录 出现不允许的操作
  3. 【codevs 1391】伊吹萃香
  4. [COGS1000]伊吹萃香 最短路
  5. 《大学语文》练习题库及答案
  6. Apache 配置Http重定向到Https(两种方案任君选择)
  7. 软件测试需要学什么?年薪30W+的测试工程师需要掌握哪些技能?
  8. Javascript(es2016) import和require用法和区别
  9. 【解决nvidia-smi】不是内部或外部命令,也不是可运行的程序 或批处理文件
  10. 消息称 Apple TV 国行已确定正式过审是真的吗?