tf更新tensor/自定义层

作者:@houkai
本文为作者原创,转载请注明出处:https://www.cnblogs.com/houkai/p/10333164.html


修改Tensor特定位置的值

stack overflow 中提到的方案。
TensorFlow不让你直接单独改指定位置的值,但是留了个歪门儿,就是tf.scatter_update这个方法,它可以批量替换张量某一维上的所有数据。

def set_value(matrix, x, y, val):
    # 提取出要更新的行
    row = tf.gather(matrix, x)
    # 构造这行的新数据
    new_row = tf.concat([row[:y], [val], row[y+1:]], axis=0)
    # 使用 tf.scatter_update 方法进正行替换
    matrix.assign(tf.scatter_update(matrix, x, new_row)) 

但是这么做有没什么缺点呢?有,那就是慢,特别是矩阵很大的时候,那是真心的慢。
TensorFlow是对张量运算(其实二维的就是矩阵运算)有速度优化的,能不能将张量修改的操作变成一个普通的张量运算呢?能,再构建一个差值张量然后做个加法,哎,又是一条旁门邪道。

def set_value(matrix, x, y, val):
    # 得到张量的宽和高,即第一维和第二维的Size
    w = int(matrix.get_shape()[0])
    h = int(matrix.get_shape()[1])
    # 构造一个只有目标位置有值的稀疏矩阵,其值为目标值于原始值的差
    val_diff = val - matrix[x][y]
    diff_matrix = tf.sparse_tensor_to_dense(tf.SparseTensor(indices=[x, y], values=[val_diff], dense_shape=[w, h]))
    # 用 Variable.assign_add 将两个矩阵相加
    matrix.assign_add(diff_matrix)

cs20si课程作业1的第3题 后一种方法的效率大概提升了4倍。

Shuffling input files with tensorflow Datasets

问题

按文件列表顺序读取

BUFFER_SIZE = 1000 # arbitrary number
# define filenames somewhere, e.g. via glob
dataset = tf.data.TFRecordDataset(filenames).shuffle(BUFFER_SIZE)

shuffle文件,然后读取

dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.shuffle(BUFFER_SIZE) # doesn't need to be big
dataset = dataset.flat_map(tf.data.TFRecordDataset)
dataset = dataset.map(decode_example, num_parallel_calls=5) # add your decoding logic here
# further processing of the dataset

同时从多个文件读取

dataset = dataset.interleave(tf.data.TFRecordDataset, cycle_length=4)

TF自定义梯度

自定义梯度

多个op
See also tf.RegisterGradient which registers a gradient function for a primitive TensorFlow operation. tf.custom_gradient on the other hand allows for fine grained control over the gradient computation of a sequence of operations.

keras 不支持 去用pytorch吧

posted @   侯凯  阅读(744)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示