我正在尝试根据此paper(第19页的公式3.8)实现自定义损失函数。我到达了此实现:
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
但是,当我尝试编译模型时:
model.compile(optimizer='rmsprop',loss=costume_loss(censored=c),metrics=['accuracy'])
我要
TypeError: 'NoneType' object cannot be interpreted as an integer
在计算时似乎未定义批次大小。 有人可以指出我正确的方向吗?也许我需要使用张量操作来实现它?如果可以,怎么办?
谢谢