tensorflow可学习的重量系数与keras API

时间:2019-09-26 18:18:45

标签: tensorflow keras

我想使损失函数具有以下形式:

L = l1(x)+(1 / w1)* l2(x)+(1 / w2)* l3(x)+ ln(1+(w1 * w1 + w2 * w2)

其中w1和w2是可学习的。通常,这些重量系数是固定的。我可以创建一个tf模型,其中这些变量是可训练的,但是我不确定如何使用keras API做到这一点。

如何使用tf.keras api对此进行指定?在训练时如何检查其值?

1 个答案:

答案 0 :(得分:1)

您可以定义一个包含权重w1和w2的自定义图层。

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from keras import backend as K

class CustomLayer(layers.Layer):

  def __init__(self):
    super(CustomLayer, self).__init__()

  def build(self, input_shape):
    self.w1 = self.add_weight(shape=(1,),
                             initializer='ones',
                             trainable=True)

    self.w2 = self.add_weight(shape=(1,),
                             initializer='ones',
                             trainable=True)

  def call(self, inputs):
    y_true = inputs[:,:1]
    y_pred = inputs[:,1:]
    loss = K.sum((y_pred - y_true) ** 2. + self.w1 + self.w2, -1) #loss calculation
    self.add_loss(loss, inputs=inputs) # add the loss
    return  K.square(inputs) # not used


model = Sequential()
model.add(layers.Input(shape=(2,)))
model.add(CustomLayer())
model.compile(optimizer='adam', loss=None) #no loss updation here
X = np.random.randn(10, 2)
model.fit(X, epochs=2)

输出:

10/10 [==============================] - 0s 6ms/sample - loss: 3.6391
Epoch 2/2
10/10 [==============================] - 0s 103us/sample - loss: 3.6371

此处提供完整示例:https://github.com/yaringal/multi-task-learning-example

https://www.tensorflow.org/beta/guide/keras/custom_layers_and_models#layers_encapsulate_a_state_weights_and_some_computation