- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请对您的想法添加最少的评论,以便我可以改进我的查询。谢谢。 :)
我正在尝试训练 tf.keras
带 的模型梯度累积 (GA)。但我不想在自定义训练循环( like )中使用它,而是自定义 .fit()
方法通过覆盖 train_step
。是否可以?如何做到这一点?原因是如果我们想得到keras
的好处内置功能,如 fit
, callbacks
,我们不想使用自定义训练循环,但同时如果我们想覆盖 train_step
出于某种原因(例如 GA 或其他),我们可以自定义 fit
方法,并且仍然可以利用这些内置函数。
而且,我知道使用 的优点GA 但是使用它的主要缺点是什么?为什么它不是默认功能,而是框架的可选功能?
# overriding train step
# my attempt
# it's not appropriately implemented
# and need to fix
class CustomTrainStep(tf.keras.Model):
def __init__(self, n_gradients, *args, **kwargs):
super().__init__(*args, **kwargs)
self.n_gradients = n_gradients
self.gradient_accumulation = [tf.zeros_like(this_var) for this_var in \
self.trainable_variables]
def train_step(self, data):
x, y = data
batch_size = tf.cast(tf.shape(x)[0], tf.float32)
# Gradient Tape
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)
# Calculate batch gradients
gradients = tape.gradient(loss, self.trainable_variables)
# Accumulate batch gradients
accum_gradient = [(acum_grad+grad) for acum_grad, grad in \
zip(self.gradient_accumulation, gradients)]
accum_gradient = [this_grad/batch_size for this_grad in accum_gradient]
# apply accumulated gradients
self.optimizer.apply_gradients(zip(accum_gradient, self.trainable_variables))
# TODO: reset self.gradient_accumulation
# update metrics
self.compiled_metrics.update_state(y, y_pred)
return {m.name: m.result() for m in self.metrics}
请运行并检查以下玩具设置。
# Model
size = 32
input = tf.keras.Input(shape=(size,size,3))
efnet = tf.keras.applications.DenseNet121(weights=None,
include_top = False,
input_tensor = input)
base_maps = tf.keras.layers.GlobalAveragePooling2D()(efnet.output)
base_maps = tf.keras.layers.Dense(units=10, activation='softmax',
name='primary')(base_maps)
custom_model = CustomTrainStep(n_gradients=10, inputs=[input], outputs=[base_maps])
# bind all
custom_model.compile(
loss = tf.keras.losses.CategoricalCrossentropy(),
metrics = ['accuracy'],
optimizer = tf.keras.optimizers.Adam() )
# data
(x_train, y_train), (_, _) = tf.keras.datasets.mnist.load_data()
x_train = tf.expand_dims(x_train, -1)
x_train = tf.repeat(x_train, 3, axis=-1)
x_train = tf.divide(x_train, 255)
x_train = tf.image.resize(x_train, [size,size]) # if we want to resize
y_train = tf.one_hot(y_train , depth=10)
# customized fit
custom_model.fit(x_train, y_train, batch_size=64, epochs=3, verbose = 1)
最佳答案
是的,可以自定义 .fit()
方法通过覆盖 train_step
在没有自定义训练循环的情况下,下面的简单示例将向您展示如何使用 训练一个简单的 mnist 分类器。梯度累积 :
import tensorflow as tf
# overriding train step
# my attempt
# it's not appropriately implemented
# and need to fix
class CustomTrainStep(tf.keras.Model):
def __init__(self, n_gradients, *args, **kwargs):
super().__init__(*args, **kwargs)
self.n_gradients = tf.constant(n_gradients, dtype=tf.int32)
self.n_acum_step = tf.Variable(0, dtype=tf.int32, trainable=False)
self.gradient_accumulation = [tf.Variable(tf.zeros_like(v, dtype=tf.float32), trainable=False) for v in self.trainable_variables]
def train_step(self, data):
self.n_acum_step.assign_add(1)
x, y = data
# Gradient Tape
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)
# Calculate batch gradients
gradients = tape.gradient(loss, self.trainable_variables)
# Accumulate batch gradients
for i in range(len(self.gradient_accumulation)):
self.gradient_accumulation[i].assign_add(gradients[i])
# If n_acum_step reach the n_gradients then we apply accumulated gradients to update the variables otherwise do nothing
tf.cond(tf.equal(self.n_acum_step, self.n_gradients), self.apply_accu_gradients, lambda: None)
# update metrics
self.compiled_metrics.update_state(y, y_pred)
return {m.name: m.result() for m in self.metrics}
def apply_accu_gradients(self):
# apply accumulated gradients
self.optimizer.apply_gradients(zip(self.gradient_accumulation, self.trainable_variables))
# reset
self.n_acum_step.assign(0)
for i in range(len(self.gradient_accumulation)):
self.gradient_accumulation[i].assign(tf.zeros_like(self.trainable_variables[i], dtype=tf.float32))
# Model
input = tf.keras.Input(shape=(28, 28))
base_maps = tf.keras.layers.Flatten(input_shape=(28, 28))(input)
base_maps = tf.keras.layers.Dense(128, activation='relu')(base_maps)
base_maps = tf.keras.layers.Dense(units=10, activation='softmax', name='primary')(base_maps)
custom_model = CustomTrainStep(n_gradients=10, inputs=[input], outputs=[base_maps])
# bind all
custom_model.compile(
loss = tf.keras.losses.CategoricalCrossentropy(),
metrics = ['accuracy'],
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) )
# data
(x_train, y_train), (_, _) = tf.keras.datasets.mnist.load_data()
x_train = tf.divide(x_train, 255)
y_train = tf.one_hot(y_train , depth=10)
# customized fit
custom_model.fit(x_train, y_train, batch_size=6, epochs=3, verbose = 1)
输出:
Epoch 1/3
10000/10000 [==============================] - 13s 1ms/step - loss: 0.5053 - accuracy: 0.8584
Epoch 2/3
10000/10000 [==============================] - 13s 1ms/step - loss: 0.1389 - accuracy: 0.9600
Epoch 3/3
10000/10000 [==============================] - 13s 1ms/step - loss: 0.0898 - accuracy: 0.9748
优点:
Gradient accumulation is a mechanism to split the batch of samples —used for training a neural network — into several mini-batches ofsamples that will be run sequentially
Example: If you run a gradient accumulation with steps of 5 and batchsize of 4 images, it serves almost the same purpose of running with abatch size of 20 images.
4 + 4
至
2 + 2 + 2 + 2
.
关于python - 在 TF.Keras 中使用自定义模型进行梯度累积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66472201/
美好的一天! 我正在制作一个出勤检查程序,单击一次时显示橙色按钮,单击两次时显示红色按钮,单击 3 次时显示黑色按钮。我在如何累积 getClickCount() 值方面遇到问题,因为对于按钮要注册
我似乎无法在 Adobe 网站上找到明确的答案。使用 ColdFusion 10,11 甚至 2016,更新(修补程序)是否累积? 例如,ColdFusion 的修补程序高达 hotfix_023
我是随机森林新手,我有一个关于回归的问题。我正在使用 R 包 randomForests 来计算 RF 模型。 我的最终目标是选择对预测连续性状很重要的变量集,因此我正在计算一个模型,然后删除准确度平
目前我们有一个发布/消费者服务,消费者将收到的消息写入 AWS S3。我们目前每月编写超过 100.000.000 个对象。但是,我们可以根据一些规则对这些消息进行分组,以节省一些钱。这些规则可以是这
假设我有一个二叉树: data BinTree a = Nil | Branch a (BinTree a) (BinTree a) 我想在这样的结构上做一个累积映射: mapAccum ::
我正在使用内核估计,我应用了 density函数从 R 到我的数据文件(双变量),经过几次统计处理后,我需要转换这些数据,这就是我的问题: 是否有非参数方法的逆累积分布函数? 我尝试过 Google、
不确定以前是否有人问过这个问题,尝试搜索它但找不到任何相关内容。 我试图获得一个累积的字符串聚合,即仅运行不同值的聚合。这是我正在寻找的结果的示例。 我尝试使用 string_agg 函数,但它仅在用
我想找到累积的 bind.rows。这是我想要实现的小例子。我将使用 dslabs 包中的 gapminder 数据集进行演示。 library(tidyverse) library(dslabs)
在 Linux 中使用 tomcat 进程时,我们观察到时间字段显示5506:34(累积 CPU 时间)。在探索时,这是在进程的整个生命周期中运行所花费的 CPU 时间的百分比。 由于这是一个 Jav
我有一些数据可以使用 pyparsing 中的 OneorMore 函数进行解析。比如, fun = OneorMore( foo.setResultsName("foo") + bar.setRe
我试图弄清楚是否有一种简单的方法可以解决 pandas 的以下问题。假设我有四个容器,A、B、C、D,每个容器都有特定的体积。假设我现在得到了一定量的液体,我想用它来填充这些容器。我怎样才能想出一个“
我正在尝试编写一个函数来检测所有上升沿 - 向量中值超过特定阈值的索引。这里描述了类似的东西:Python rising/falling edge oscilloscope-like trigger
这个问题在这里已经有了答案: Multiplying elements of a column in skipping an element after each iteration (3 个答案)
有没有办法获取数据框中每一行的值计数? |f1|f2| ------- v1 | a value_counts -> {a:1} v2 | a value_counts -> {a:2} v3 |
我目前正在尝试对我正在构建的计算器(使用复合模式)进行测试。第一种方法应该添加 75 美元,效果很好,但是当第二种方法运行时,“服务”被重置并且有0 美元作为工作成本。如果我将这两种方法合二为一,那么
我有一个如下所示的文档: 数据.txt 100, "some text" 101, "more text" 102, "even more text" 我使用正则表达式处理它并返回一个新的处理文档,如
假设我有这个: function getAllPromises(key: string, val: any): Promise { const subDeps = someHash[key]; c
我在 mysql 中有表“cumul_sum”,我想根据条件划分“cumulative”列,即如果此列中的值 >= 70,则这些值应存储在名为“others”的新列中"并且前面应该存放对应的sku_i
我正在做一个用 C++ 刺激 ATM 的项目,但在使用累加器时遇到了一些问题,我的问题是:我正在使用开关(这里是情况 1)来更改在包含的函数中声明的 2 个变量的值switch(),但是值只在情况 1
我希望能够使用 accumulate 对 vector 中的每隔一对元素进行累加。我尝试了以下但没有成功,为非空、非零 vector 返回错误 return std::accumulate(vec.b
我是一名优秀的程序员,十分优秀!