我想要一些损失函数,例如:
def loss_equation(x, a, b):
"""L2 loss for matrix equation `a=bx`."""
a_test = tf.matmul(x, b)
return tf.reduce_sum(tf.square(a-a_test))
def loss_regular(x):
"""L2 loss regularizing entries of `x`."""
return tf.reduce_sum(tf.square(x))
并且能够找到最佳x
,将损失馈送到自定义优化函数,如下所示:
x_optimal = some_optimizer(
{ "loss": loss_equation,
"args": [param_a, param_b]
},
{ "loss": loss_equation,
"args": []
})
优化器应该找到最佳的x
,以最大程度地减少指定损失的总和(例如,在一个实验中,我有两个损失,每个损失都有自己的参数,在另一个实验中,我有五个损失)。
如何在TensorFlow中对这种模块化行为进行编程?
答案 0 :(得分:1)
x = ...
def loss_overall(x):
return loss_equation(x, param_a, param_b) + loss_regular(x)
loss = loss_overall(x)
opt = tf.train.AdamOptimizer(1e-3)
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
train_op = opt.minimize(loss)
with tf.Session() as sess:
while True:
sess.run(train_op)
...
首先,您应该创建损耗张量
其次,您应该定义优化器
第三,调用最小化方法来获得列车运行