How to get the loss for each epoch in custom batch training in Keras?

Viewed 982

I am experimenting a little bit with AI and I have a model where I want to train it in batches which are chosen previously and have irregular shapes.

Heres what I have:

model = create_model(units_vector, (inp_shape,), lr)
for i in range(epochs):
    for batch in batches:
        model.fit(batch[0], batch[1], epochs=1, verbose=0)

The function create_model defines a simple model (only dense layers) and compiles it with mse and Adam.

batches is a list of tuples where the inputs and outputs are stored (in numpy arrays).

I would want a way to print at the end of each epoch the loss experimented by the model. Or some way to check if the model is learning something or not (without having to print a message at each batch which is too much spam).

1 Answers

here a simple way to print the loss at the end of each epoch. you can access the loss through model.history.history. you can also modify the message according to your needs

epochs = 5
n_batches = 20
n_features = 10
batches = [[np.random.uniform(0,1, (1,n_features)), np.random.uniform(0,1, (1,1))] for _ in range(n_batches)]

inp = Input((n_features,))
x = Dense(32)(inp)
out = Dense(1)(x)
model = Model(inp, out)
model.compile('adam', 'mse')

for i in range(epochs):
    for batch in batches:
        model.fit(batch[0], batch[1], epochs=1, verbose=0)
    print(f"EPOCH {i}", model.history.history)

example of the output:

EPOCH 0 {'loss': [0.9013449549674988]}
EPOCH 1 {'loss': [0.7315107583999634]}
EPOCH 2 {'loss': [0.5937882661819458]}
EPOCH 3 {'loss': [0.5331881046295166]}
EPOCH 4 {'loss': [0.47262871265411377]}
Related