首页 > 解决方案 > ValueError:形状必须为 2 级,但对于 'loss/dense_2_loss/Npairloss/MatMul'(操作:'MatMul')为 1 级,输入形状为:[?]、[?,10]

问题描述

错误 ValueError: Shape must be rank 2 but is rank 1 for 'loss/dense_2_loss/Npairloss/MatMul' (op: 'MatMul') with input shapes: [?], [?,10]

def Npairloss(y_true,y_pred):
        l2_reg = 0.02
        anchors = y_pred[:,0]    # (n, embedding_size)
        positives = y_pred[:,1]  # (n, embedding_size)
        negatives = y_pred[:2]    # (n, n-1, embedding_size)
        sub_n_p =  negatives - positives
        trans_a= K.transpose(anchors)
        logit = K.dot(trans_a,sub_n_p)  # (n, 1, n-1)
        x = K.sum(K.exp(logit), 2)  # (n, 1)
        loss = K.mean(K.log(1 + x))
        l2_loss = K.sum(anchors ** 2 + positives ** 2) / anchors.shape[0]
        losses = loss + l2_reg * l2_loss
        return losses

我正在尝试在 MNIST 上实现 Keras 学习中的 N 对损失。这里的anchor和positive来自同一类,anchor和negative来自不同的类。我不知道怎么了。非常感谢你的帮助。

标签: pythontensorflowkerastriplet

解决方案


推荐阅读