tensorflow张量限幅
本篇内容有clip_by_value、clip_by_norm、gradient clipping
1.tf.clip_by_value
a = tf.range(10)
print(a)
# if x<a res=a,else x=x
print(tf.maximum(a,2))
# if x>a,res=a,else x=x
print(tf.minimum(a,8))
# 综合maximum和minimum两个函数的功能,指定上下限
print(tf.clip_by_value(a,2,8))

2.tf.clip_by_norm
# 随机生成一个2行2列的tensor
a = tf.random.normal([2,2],mean=10)
# 打印二范数
print(tf.norm(a))
# 根据新的norm进行放缩
print(tf.clip_by_norm(a,15))
print(tf.norm(tf.clip_by_norm(a,15)))

3.tf.clip_by_global_norm
# gradient clipping为解决梯度下降和梯度消失问题
# 可保证整体向量同时缩放(等倍数)
for g in grads:
grads,_ = tf.clip_by_global_norm(grads,15)
实测:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers
import os os.environ['TF_CPP_MIN_LOG_LEVEL']=''
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 => 512
w1, b1 = tf.Variable(tf.random.truncated_normal([784, 512], stddev=0.1)), tf.Variable(tf.zeros([512]))
# 512 => 256
w2, b2 = tf.Variable(tf.random.truncated_normal([512, 256], stddev=0.1)), tf.Variable(tf.zeros([256]))
# 256 => 10
w3, 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 + b1
h1 = tf.nn.relu(h1)
# layer2
h2 = h1 @ w2 + b2
h2 = tf.nn.relu(h2)
# output
out = 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] => scalar
loss = tf.reduce_mean(loss) # compute gradient
grads = 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*grad
optimizer.apply_gradients(zip(grads, [w1, b1, w2, b2, w3, b3])) if step % 100 == 0:
print(step, 'loss:', float(loss)) if __name__ == '__main__':
main()


tensorflow张量限幅的更多相关文章
- AI - TensorFlow - 张量(Tensor)
张量(Tensor) 在Tensorflow中,变量统一称作张量(Tensor). 张量(Tensor)是任意维度的数组. 0阶张量:纯量或标量 (scalar), 也就是一个数值,例如,\'Howd ...
- Tensorflow张量
张量常规解释 张量(tensor)理论是数学的一个分支学科,在力学中有重要应用.张量这一术语起源于力学,它最初是用来表示弹性介质中各点应力状态的,后来张量理论发展成为力学和物理学的一个有力的数学工具. ...
- tensorflow 张量的阶、形状、数据类型及None在tensor中表示的意思。
x = tf.placeholder(tf.float32, [None, 784]) x isn't a specific value. It's a placeholder, a value th ...
- TensorFlow2.0(五):张量限幅
.caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...
- tensorflow张量排序
本篇记录一下TensorFlow中张量的排序方法 tf.sort和tf.argsort # 声明tensor a是由1到5打乱顺序组成的 a = tf.random.shuffle(tf.range( ...
- TensorFlow—张量运算仿真神经网络的运行
import tensorflow as tf import numpy as np ts_norm=tf.random_normal([]) with tf.Session() as sess: n ...
- Tensorflow张量的形状表示方法
对输入或输出而言: 一个张量的形状为a x b x c x d,实际写出这个张量时: 最外层括号[…]表示这个是一个张量,无别的意义! 次外层括号有a个,表示这个张量里有a个样本 再往内的括号有b个, ...
- 121、TensorFlow张量命名
# tf.Graph对象定义了一个命名空间对于它自身包含的tf.Operation对象 # TensorFlow自动选择一个独一无二的名字,对于数据流图中的每一个操作 # 但是给操作添加一个描述性的名 ...
- 吴裕雄--天生自然TensorFlow2教程:张量限幅
import tensorflow as tf a = tf.range(10) a # a中小于2的元素值为2 tf.maximum(a, 2) # a中大于8的元素值为8 tf.minimum(a ...
随机推荐
- 【OpenGL】变换矩阵计算公式
摘自: http://ogldev.atspace.co.uk/www/tutorial06/tutorial06.html, http://ogldev.atspace.co.uk/www/tuto ...
- JAVA System.exit(0) 和 System.exit(1) 的区别
System.exit(int state) 方法都是来结束当前运行的java虚拟机.所有System.exit(1).System.exit(0) 执行后都会退出程序. state为0时时正常退出, ...
- java 子线程定时去更改主线程的变量
在一次代码编写场景,需要post一些数据,同时携带获得的token,(但是token的有效时间是7200s),但是post需要很多次,很长时间,不可能2小时候中断程序,手动去获取token,这样效率太 ...
- ELK logstash 各种报错
1.logstash 启动后数据传输了,但是 ElasticSearch 中没有生成索引,查看logstash日志,报错如下 [2018-06-08T14:46:25,387][WARN ] [log ...
- curl 和 tcpdump
curl: 1.通常使用curl 来监控网址状态, #curl -m 5 -s -o /dev/null -w %{http_code} www.baidu.com #200 -m 设置访问超时时间, ...
- linux系统的启动流程梳理
1. 不同版本的linux系统的启动流程 1.1 centos6.x系统的启动流程 其详细启动步骤如下: 1)开机,BIOS自检,检查各个硬件是否正常 2)读取硬盘MBR信息,引导系统启动 3)加载g ...
- [MSSQL]xp_cmdshell 查看磁盘空间
EXEC xp_cmdshell 'wmic logicaldisk get freespace,caption | findstr C'; <class 'pyodbc.Row'> (' ...
- ISO14229系列之二:诊断指令格式和相关概念
作者:autogeek 原文链接:http://www.cnblogs.com/autogeek/p/4458658.html 1. 简单的通信机制 其实诊断通信的机制很简单,可以类比client-s ...
- vue h5移动端禁止缩放
在index.html里面写 <meta name="viewport" content="width=device-width, initial-scale=1. ...
- c语言心形告白代码实现
c语言心形告白代码实现 1.彩色告白 include<stdio.h> include<math.h> include<windows.h> include< ...