Loss Function in Metric Learning

General Idea:

For Classification Task:
Input the feature vector and the corresponding type,use the matrix to calculate the distance/simmilarity between the pairs. With different assumption or view, there're several different design for the loss function.
the code resource is from https://github.com/bnulihaixia/Deep_metric

The Main Scopes

  1. dynamic learning rate
  2. euclidean distance or similarity or js divergence
  3. whether consider the all samples or the select the hard samples
  4. how to evaluate the hard samples, absolute?relative? above/below mean? with sampling probability?
    if so, how to calculate the probability?
  5. whether use different weight for calculating loss
  6. whether use slice?BDW, like a batch normalization


    image.png

Details

BatchAll (almost same as A BatchAll, without the a_lr)

  • dynamic learning rate
            pos_logit = torch.sum(torch.exp(self.alpha * (1 - pos_pair)))
            neg_logit = torch.sum(torch.exp(self.alpha * (1 - neg_pair)))
            a_lr = 1 - (pos_logit / (pos_logit + neg_logit)).data[0]
            ......
            loss_ = a_lr*torch.sum(valid_triplets)
  • pos num: neg_num = 1:1 with the repeating operation
            pos_pair = pos_pair.repeat(num_neg_instances, 1)
            neg_pair = neg_pair.repeat((num_instances-1), 1).t()
  • self.margin
          triplet_mat = pos_pair - neg_pair + self.margin

A_hard_pair

  • dynamic learning rate
  • Focus on the hard pair, loss get value only when the pos pair exceeds the limit(too far) and the neg pair is within the margin(dis<1.1) (the absolute distance)
            pos_loss = torch.log(torch.sum(torch.exp(self.beta * (pos_pair - 0.8))))
            neg_loss = torch.log(torch.sum(torch.exp(self.beta * (1.1 - neg_pair))))

A_triplet/Triplet

  • dynamic learning rate
  • the pos distance exceed neg distance too much(the relative distance)
            triplet_mat = torch.log(torch.exp(self.beta*(pos_pair - neg_pair)) + 1)
            triplet_mask = triplet_mat > 0.65

BatchHard

select the max pos and min( both the hardest examples) by row in a batch;
(much more elegant for the neg_dist/pos_dist calculation)

        hard_pos = torch.max(pos_dist_mat, dim=0)[0]
        hard_neg = torch.min(neg_dist_mat, dim=0)[0]

BDWDistWeightNeighborloss( Slice+ DistWeightNeighborloss)

BinDevianceLoss(Branch)

  • use the similarity matrix, not the euclidean distance. The similarity score is high with the distance being short on the regularized case. and only select the neg pair of which similarity score is larger than the pos pair.
             neg_pair = torch.masked_select(neg_pair, neg_pair > pos_pair[0] - 0.05)
  • with constant margin to constrain
            pos_loss = torch.mean(torch.log(1 + torch.exp(-2*(pos_pair - self.margin))))
            neg_loss = 0.04*torch.mean(torch.log(1 + torch.exp(50*(neg_pair - self.margin))))

CenterLoss

(ref:https://blog.csdn.net/u014380165/article/details/76946339)

image.png

image.png

image.png

the distance to the center for every feature, smaller distance in the cluster represents the better results
Steps:

  1. store the centers and inputs
  2. calculate the center dist
  3. the closet neighbour center as neg sample and the farthest input to its center as pos sample.(also for selecting the hard samples)
            dist_an.append(centers_dist[i][targets_ != target].min())
            center_diff = inputs_list[i] - centers[i]
            center_diff_norm = torch.cat([torch.norm(temp) for temp in center_diff])
            dist_ap.append(center_diff_norm.max())

CenterNCA

Center+ base(I can't tell the apparent feature of NCA from the view of code, maybe the "base" setting,but here, the pos or neg selecting is the individual sample with the center)

CenterPair

constant limit to select pos/neg samples

       loss = torch.mean(pos_dist.clamp(min=0.15) -
       torch.log(torch.sum(torch.exp(-neg_dist.clamp(max=0.6)), 0)))

ClusterNCA

lable is not from the initialization but the kmean clustering result(need to point out the number of cluster)

Contrastive Loss

take the samples with in same class as positive examples.


image.png

DistWeightLoss

  • select the pos samples according to the similarity probability(the weight)
  • select the hard neg pair
pos_pair = torch.sort(pos_pair)[0]
sampled_index = torch.multinomial(torch.exp(5*pos_pair), 1)
neg_pair = torch.masked_select(neg_pair, neg_pair > pos_min - 0.01)

DistWeightContrastiveLoss

Gaussian Probability to select, with constant limit.

DistanceMatchLoss

regard the neg/pos samples distribution as Gaussian Distribution, and select the sample use the Gaussian parameters

            neg_pair = neg_dist[i]
            neg_mean, neg_std = GaussDistribution(neg_pair)
            prob = torch.exp(torch.pow(neg_pair - neg_mean, 2) / (2 * torch.pow(neg_std, 2)))
            neg_index = torch.multinomial(prob, 3*num_instances, replacement=False)

and different weight to calculate the loss

               base = [0.95, 1.05, 1.12]
                muls = [4, 8, 16]
                pos_diff = [pos_pair[i] - base[i] for i in range(len(base))]
                pos_diff = torch.cat([1.0 / muls[i] *torch.log(1 + torch.exp(pos_diff[i])) for i in range(len(base))])

Gaussian LDA

different way to calculate the loss

           pos_logit = torch.sum(torch.exp(self.alpha*(1 - pos_neig)))
            neg_logit = torch.sum(torch.exp(self.alpha*(1 - neg_neig)))
            loss_ = -torch.log(pos_logit/(pos_logit + neg_logit))

GaussianMetric

in the code, there's nothing about Gaussian. The main idea is to select the neg/pos pair according to the mean samples.
(it seems that those are all about how to select negative samples and positive samples)

NCA Loss

To select pos/neg in Top-K Neighborhood.
base function: in case the float number operation happened illegally


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,373评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,732评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,163评论 0 238
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,700评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,036评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,425评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,737评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,421评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,141评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,398评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,908评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,276评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,907评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,018评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,772评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,448评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,325评论 2 261

推荐阅读更多精彩内容