1

I'm trying to implement a custom loss function as per this paper, equation 3.8 page 19. I arrived at this implementation:

import numpy as np
import keras.backend as T
from keras import models

def costume_loss(censored):
    '''costume loss function'''

    def loglikelihood_function(y_true,y_pred,censored):
        '''implements likelihood function as per equation 3.8 in using survival prediction techniques to learn consumer'''
        results=[]
        n=T.int_shape(y_pred)[0]  #number of instances
        K=T.int_shape(y_pred)[1]    #number of subintervals

        print(T.int_shape(y_pred)[0],T.int_shape(y_pred)[1])


        for i in range(n):
            if censored[i]==0:
                sum1=np.sum([y_pred[i][j]*y_true[i][j] for j in range(K)])
                sum2=np.sum([math.exp(np.sum([ y_pred[i][k]  for k in range(j,K)])) for j in range(K)])
                results.append(-(sum1-math.log(sum2)))      
            else:
                sum1=np.sum([y_true[i][j]*math.exp(np.sum([y_pred[i][k] for k in range(j,K)]))   for j in range(K)])
                sum2=np.sum([math.exp(np.sum([ y_pred[i][k]  for k in range(j,K)])) for j in range(K)])
            results.append(-(math.log(sum1)-math.log(sum2))) 

        x=tf.constant(np.array(results,dtype='float64'))   #convert into tensor
        return T.mean(x)

    def loss_function(y_true,y_pred):
        return loglikelihood_function(y_true,y_pred,censored)

    return loss_function

However when I try to compile the model:

model.compile(optimizer='rmsprop',loss=costume_loss(censored=c),metrics=['accuracy'])

I'm getting

TypeError: 'NoneType' object cannot be interpreted as an integer

Which seems as if the batch size is undefined at time of calculation. Can someone point me in the right direction? Maybe I would need to implement it using tensor operations? If so, how?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Juan Castaño
  • 67
  • 3
  • 11
  • are `n` and `K` integers? what is `c` set at? what is the shape of `y_pred`? – Dirk N Mar 19 '19 at 21:49
  • Hi! Yeah, both n and K are integers. C is an array of 0 or 1s indicating wheher each sample was either censored or not; y_pred should be the output of the output layer in the nn. – Juan Castaño Mar 21 '19 at 11:43

0 Answers0