如何将这种用烤宽面条写的损失函数转换成Keras?

问题描述 投票:0回答:1

我一直致力于将用Lasagne编写的CNN转换为Keras(链接到Lasagne版本:https://github.com/MTG/DeepConvSep/blob/master/examples/dsd100/trainCNN.py)我相信我已经把大部分内容都删掉了,但是,损失函数是我正在努力重写的部分。

网络的输出具有形状(32,513,30,4),并且损失函数使用不同的层(最后的暗淡)。我试图将其重写为自定义丢失函数,我可以将其插入到model.compile()这里是我编写的代码:


rand_num = np.random.uniform(size=(32,513,30,1))
epsilon=1e-8                                        
alpha=0.001                                        
beta=0.01                                          
beta_voc=0.03 

def loss_func(y_true, y_pred):

    global alpha, beta, beta_voc, rand_num

    voc =  y_pred[:,:,:,0:1] + epsilon * rand_num
    bass = y_pred[:,:,:,1:2] + epsilon * rand_num
    dru = y_pred[:,:,:,2:3] + epsilon * rand_num
    oth = y_pred[:,:,:,3:4] + epsilon * rand_num

    mask_vox = voc/(voc+bass+dru+oth)
    mask_bass = bass/(voc+bass+dru+oth)
    mask_drums = dru/(voc+bass+dru+oth)
    mask_oth = oth/(voc+bass+dru+oth)

    vocals = mask_vox * inp
    bass = mask_bass * inp
    drums = mask_drums * inp
    other = mask_oth * inp

    train_loss_vocals = mean_squared_error(y_true=y_true[:,:,:,0:1],y_pred=vocals)
    alpha_component = alpha*mean_squared_error(y_true=y_true[:,:,:,1:2],y_pred=vocals)
    alpha_component += alpha*mean_squared_error(y_true=y_true[:,:,:,2:3],y_pred=vocals)
    train_loss_recon_neg_voc = beta_voc*mean_squared_error(y_true=y_true[:,:,:,3:4],y_pred=vocals)

    train_loss_bass = mean_squared_error(y_true=y_true[:,:,:,1:2],y_pred=bass)
    alpha_component += alpha*mean_squared_error(y_true=y_true[:,:,:,0:1],y_pred=bass)
    alpha_component += alpha*mean_squared_error(y_true=y_true[:,:,:,2:3],y_pred=bass)
    train_loss_recon_neg = beta*mean_squared_error(y_true=y_true[:,:,:,3:4],y_pred=bass)

    train_loss_drums = mean_squared_error(y_true=y_true[:,:,:,2:3],y_pred=drums)
    alpha_component += alpha*mean_squared_error(y_true=y_true[:,:,:,0:1],y_pred=drums)
    alpha_component += alpha*mean_squared_error(y_true=y_true[:,:,:,1:2],y_pred=drums)
    train_loss_recon_neg += beta*mean_squared_error(y_true=y_true[:,:,:,3:4],y_pred=drums)

    vocals_error=train_loss_vocals.sum()
    drums_error=train_loss_drums.sum()
    bass_error=train_loss_bass.sum()
    negative_error=train_loss_recon_neg.sum()
    negative_error_voc=train_loss_recon_neg_voc.sum()
    alpha_component=alpha_component.sum()

    loss=abs(vocals_error+drums_error+bass_error-negative_error-alpha_component-negative_error_voc)

    return loss 

我得到的第一个错误是:

AttributeError:'Tensor'对象没有属性'sum'

但是,我不确定其他一些操作,即使是不正确的操作,也会引发错误。

我真的很感激一些帮助。谢谢。

python keras conv-neural-network loss-function lasagne
1个回答
0
投票

例如,参见this关于如何在Keras中定义自定义损失的示例。

y_pred是Keras模型的输出是张量。你必须调整你的操作以适应张量,所以你不得不使用np.sum而不是kazxswpoi,而K是你的keras后端。

一些运算符过载,因此您可以使用K.sum添加两个张量。

© www.soinside.com 2019 - 2024. All rights reserved.