Carsten
Carsten

Reputation: 4334

How do I assign names to Ouputs in a subclassed Keras Model?

I want to name the outputs of a subclassed TensorFlow Keras Model, so I can pass targets to them in fit(), e.g. self.model.fit(np_inputs, {'q_values': np_targets}, verbose=0)

The model looks like this:

class MyModel(tf.keras.models.Model):
    def __init__(self, name):
        super(MyModel, self).__init__()
        self.input_layer = tf.keras.Input(shape=(BOARD_SIZE * 3,))
        self.d1 = tf.keras.layers.Dense(BOARD_SIZE * 3 * 9, activation='relu')
        self.d2 = tf.keras.layers.Dense(BOARD_SIZE * 3 * 100, activation='relu')
        self.d3 = tf.keras.layers.Dense(BOARD_SIZE * 3 * 9, activation='relu')
        self.q_values_l = tf.keras.layers.Dense(BOARD_SIZE, activation=None, name='q_values')
        self.probabilities_l = tf.keras.layers.Softmax(name='probabilities')

    @tf.function
    def call(self, input_data):
        x = self.d1(input_data)
        x = self.d2(x)
        x = self.d3(x)
        q = self.q_values_l(x)
        p = self.probabilities_l(q)
        return p, q

I naively assumed the name of the corresponding layers would also be assigned to the outputs, but this does not seem to be the case.

I only have targets to 1 of the outputs, thus the need to exactly specify what output the targets are for when calling fit().

In the functional way of using Keras this works well, but I can't replicate it in the subclass approach. I can't use the functional Keras way in my case for unrelated reasons.

Upvotes: 0

Views: 174

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Why not just pass a dummy target?

model.fit(np_inputs, [np.zeros((len(np_inputs),)), np_targets], ...)

Maybe even None can be passed instead of np.zeros.

You can compile the model exactly the same way:

model.compile(loss=[p_loss, q_loss], ...)

Upvotes: 1

Related Questions