- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对计算梯度很感兴趣。 Tensorflow 中 keras 模型的输入。我知道以前可以通过构建图形并使用 tf.gradients
来完成此操作。 .例如 here .但是,我想在 Eager 模式(可能使用 GradientTape
)下进行实验时实现这一点。具体来说,如果我的网络有两个输入 (x, y)
,并预测 (u, v, p)
计算例如,du/dx
用于损失。
下面的片段,完整代码 at this gist .
model = tf.keras.Sequential([
tf.keras.layers.Dense(20, activation=tf.nn.relu, input_shape=(2,)), # input shape required
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(3)
])
def loss(model: tf.keras.Model, inputs, outputs):
u_true, v_true = outputs[:, 0], outputs[:, 1]
prediction = model(inputs)
u_pred, v_pred = prediction[:, 0], prediction[:, 1]
loss_value = tf.reduce_mean(tf.square(u_true - u_pred)) + \
tf.reduce_mean(tf.square(v_true - v_pred))
return loss_value, u_pred, v_pred
def grad(model: tf.keras.Model, inputs, outputs):
"""
:param inputs: (batch_size, 2) -> x, y
:param outputs: (batch_size, 3) -> vx, vy, p
:return:
"""
with tf.GradientTape() as tape:
loss_value, u_pred, v_pred = loss(model, inputs, outputs)
# AttributeError: 'DeferredTensor' object has no attribute '_id'
print(tape.gradient(u_pred, model.input))
grads = tape.gradient(loss_value, model.trainable_variables)
return loss_value, grads
tape.gradient(u_pred, model.input)
或
tape.gradient(model.output, model.input)
但这些抛出:
AttributeError: 'DeferredTensor' object has no attribute '_id'
最佳答案
以下是使用 Eager Execution 检索相对于输入的预测梯度的示例
基本上,您需要使用 Tape.watch(inputs) [我在我的示例中使用功能 - 无论您想调用 x ... ] 为 Tensorflow 记录模型输出中的更改(您可以使用 loss ) 关于输入...(并确保在 with tf.GradientTape() 上下文之外调用您的 tape.gradient)
看看下面的 get_gradients 函数...
希望这可以帮助!
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(len(numeric_headers),)), # input shape required
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)
])
# model = MyModel()
loss_object = tf.keras.losses.BinaryCrossentropy()
optimizer = tf.keras.optimizers.Adam()
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
def get_gradients(model, features):
with tf.GradientTape() as tape:
tape.watch(features)
predictions = model(features)
gradients = tape.gradient(predictions, features)
return gradients
def train_step(features, label):
with tf.GradientTape() as tape:
predictions = model(features)
loss = loss_object(label, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accuracy(label, predictions)
def test_step(features, label):
predictions = model(features)
t_loss = loss_object(label, predictions)
test_loss(t_loss)
test_accuracy(label, predictions)
EPOCHS = 5
for epoch in range(EPOCHS):
for features, labels in train_ds:
train_step(features, labels)
for features, labels in train_ds:
test_step(features, labels)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print (template.format(epoch+1,
train_loss.result(),
train_accuracy.result()*100,
test_loss.result(),
test_accuracy.result()*100))
if epoch == EPOCHS - 1:
for features, labels in train_ds:
print ('-')
print (get_gradients(model, features))
关于python - 在 Tensorflow 急切模式下计算梯度与模型输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55066710/
我有一个案例,在大多数情况下,对象之间的关系是这样的,因此在关系上预先配置一个渴望(加入)的负载是有意义的。但是现在我遇到了一种情况,我真的不想完成急切的加载。 我是否应该从关系中删除连接负载并将所有
在我的 Grails 项目中,我有以下类: class A { static hasMany = [cs:C] } class B { static hasMany = [cs:C]
想象一下以下简化的 DI 模型: @ApplicationScoped public class A { private B b; @Inject public A(B b)
我使用 MapLoader 将数据从数据存储初始加载到 Hazelcast (InitialLoadMode = EAGER)。我需要从一个物化 View 中加载这些数据,该 View 是为了在加载过
我使用 Hibernate Envers 4.3.10.Final。我有以下两个 JPA 类: public class Factory { private int factoryID;
EJB 似乎被延迟加载 - 每当访问时。 但是,我想急切地初始化它们 - 即每当容器启动时。这是如何实现的(尤其是在 JBoss 中) This topic给出了一些提示,但不是很令人满意。 最佳答案
我是一名优秀的程序员,十分优秀!