I want to build a network that, for a given input, predicts the hour of the day. The result should be in range 0 to 24.
I tried to solve it as a classification problem but that doesn't seem to be the right way. My problem is that I don't know how to build a cyclic loss function. For example, in my case, if the network gets an output of 1 and the true label is 23 I want the distance to be 2 and not 22. Is there a layer for that which I can use?
As far as I know there is no pre written cyclic loss function. For cyclic loss you should write your own loss function like this:
import keras.backend as K
def cyclic_loss(y_true, y_pred):
return K.min((y_pred +24 - y_true) % 24, (y_true + 24 - y_pred) % 24)
model.compile(optimizer='sgd', loss=cyclic_loss, metrics=['acc'])
However it is not a classification problem if you define your loss like that. If you want a classification problem you should encode your output with one-hot encoding and use cross-entropy as loss function. Then you have a probability for each hour of the day and you take the hour with the highest probability.
As a regression task you can use the cyclic loss function as described above.