我在尝试构建一个Keras的损失函数,其中我对预测值与一组给定值之间的最小距离进行惩罚。问题是我需要计算预测值与给定值之间的距离。
示例代码
def custom_loss(y_pred,y_test): #给定值 centers=K.constant([[-2.5,-1],[-1.25,-2],[.5,-1],[1.5,.25]]) num_centers=K.int_shape(centers)[0] #开始构建距离矩阵 height=K.int_shape(y_pred)[0] i=0 current_center=K.reshape(K.repeat(K.reshape(centers[i,:],[1,-1]),height),[height,2]) current_dist=K.sqrt(K.sum(K.square(y_pred-current_center),axis=1)) #第一个中心的距离矩阵值 Distance=K.reshape(current_dist,[height,1]) for i in range(1,num_centers): current_center=K.reshape(K.repeat(K.reshape(centers[i,:],[1,-1]),height),[height,2]) current_dist=K.sqrt(K.sum(K.square(y_pred-current_center),axis=-1)) current_dist=K.reshape(current_dist,[height,1]) #迭代地连接y_pred与剩余中心的距离 Distance=K.concatenate([Distance,current_dist],axis=-1) #确定每个预测值到最近中心的最小距离 A=K.min(A,axis=1) #返回平均最小距离作为损失 return K.sum(A)/float(height)
然而,我无法移除函数对y_pred第一维度的依赖,而这一维度是可变的。我使用数组广播来计算y_pred与每个给定值之间的差异,但我是明确地使用批次大小进行广播的,因为我不知道在Keras中如何不使用批次大小来实现这一点。然而,这会导致错误,因为在构建计算图时批次大小不是明确已知的。
我如何避免明确的广播?是否有更有效的方法来计算这个距离矩阵,因为当前的方法非常笨拙?
回答:
您的损失函数可以使用隐式广播来实现,如下所示:
注意: 未经测试。