本篇内容有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张量限幅的更多相关文章

  1. AI - TensorFlow - 张量(Tensor)

    张量(Tensor) 在Tensorflow中,变量统一称作张量(Tensor). 张量(Tensor)是任意维度的数组. 0阶张量:纯量或标量 (scalar), 也就是一个数值,例如,\'Howd ...

  2. Tensorflow张量

    张量常规解释 张量(tensor)理论是数学的一个分支学科,在力学中有重要应用.张量这一术语起源于力学,它最初是用来表示弹性介质中各点应力状态的,后来张量理论发展成为力学和物理学的一个有力的数学工具. ...

  3. tensorflow 张量的阶、形状、数据类型及None在tensor中表示的意思。

    x = tf.placeholder(tf.float32, [None, 784]) x isn't a specific value. It's a placeholder, a value th ...

  4. TensorFlow2.0(五):张量限幅

    .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...

  5. tensorflow张量排序

    本篇记录一下TensorFlow中张量的排序方法 tf.sort和tf.argsort # 声明tensor a是由1到5打乱顺序组成的 a = tf.random.shuffle(tf.range( ...

  6. TensorFlow—张量运算仿真神经网络的运行

    import tensorflow as tf import numpy as np ts_norm=tf.random_normal([]) with tf.Session() as sess: n ...

  7. Tensorflow张量的形状表示方法

    对输入或输出而言: 一个张量的形状为a x b x c x d,实际写出这个张量时: 最外层括号[…]表示这个是一个张量,无别的意义! 次外层括号有a个,表示这个张量里有a个样本 再往内的括号有b个, ...

  8. 121、TensorFlow张量命名

    # tf.Graph对象定义了一个命名空间对于它自身包含的tf.Operation对象 # TensorFlow自动选择一个独一无二的名字,对于数据流图中的每一个操作 # 但是给操作添加一个描述性的名 ...

  9. 吴裕雄--天生自然TensorFlow2教程:张量限幅

    import tensorflow as tf a = tf.range(10) a # a中小于2的元素值为2 tf.maximum(a, 2) # a中大于8的元素值为8 tf.minimum(a ...

随机推荐

  1. 开发中常见的common.js--1

    common.js 1.基于代码重用的目的,方便在页面中调用: 2.跟普通的js包含文件并没有其他不一样,主要是一些js经常用到的函数,或者字符串.数组方法的简单扩展: 3.封装的兼容性的方法.[po ...

  2. 用反射、泛型 改造SqlHelper

    1.  数据准备 public class BaseModel { public int Id { set; get; } } public class Company : BaseModel { p ...

  3. 基于 Serverless Component 全栈解决方案

    什么是 Serverless Component Serverless Component 是 Serverless Framework 的,支持多个云资源编排和组织的场景化解决方案. Serverl ...

  4. 万字分享,我是如何一步一步监控公司MySQL的?

    整理了一些Java方面的架构.面试资料(微服务.集群.分布式.中间件等),有需要的小伙伴可以关注公众号[程序员内点事],无套路自行领取 更多优选 一口气说出 9种 分布式ID生成方式,面试官有点懵了 ...

  5. Python3(八) 枚举详解

    一.枚举其实是一个类 建议标识名字用大写 1.枚举类: from enum import Enum class VIP(Enum):     YELLOW = 1     GREEN = 2      ...

  6. php gettype()函数

      gettype() 会根据 参数类型返回值: boolean:表示变量为布尔类型 integer:表示变量为整数类型 double :表示变量为float类型(历史原因) string:表示变量为 ...

  7. Ant Design Vue Pro 项目实战-项目初始化(一)

    写在前面 时间真快,转眼又是新的一年.随着前后端技术的不断更新迭代,尤其是前端,在目前前后端分离开发模式这样的一个大环境下,交互性.兼容性等传统的开发模式已经显得有些吃力.之前一直用的是react,随 ...

  8. pytorch之 batch_train

    import torch import torch.utils.data as Data torch.manual_seed(1) # reproducible BATCH_SIZE = 5 # BA ...

  9. Unity5.5.6 升级到 2018.4.1 打包出现的问题 : Gradle version 2.10 is required. Current version is 5.1.1

    起因:最近要在googleplay上架新游戏,而谷歌要求新上架的应用要支持64位,鉴于老版本的unity不支持打包64位apk,所以决定升级unity版本到2018.4.1, 但打包过程中出现了几个问 ...

  10. VMware vCenter Server6.0安装及群集配置介绍

    在本项目中,将在VMware Workstation 模拟的Windows Server 2008 R2虚拟机中安装VMware vCenter Server ,并且使用vCenter Server捆 ...