迁移学习-域适应损失函数MMD-代码实现及验证

迁移学习损失函数MMD(最大均值化差异)–python代码实现

MMD介绍

MMD(Max mean discrepancy 最大均值差异)是迁移学习,尤其是Domain adaptation (域适应)中使用最广泛(目前)的一种损失函数,主要用来度量两个不同但相关的分布的距离。两个分布的距离定义为:
M M D ( X , Y ) = ∥ 1 n ∑ i = 1 n ϕ ( x i ) − 1 m ∑ j = 1 m ϕ ( y j ) ∥ H 2 M M D(X, Y)=\left\|\frac{1}{n} \sum_{i=1}^{n} \phi\left(x_{i}\right)-\frac{1}{m} \sum_{j=1}^{m} \phi\left(y_{j}\right)\right\|_{H}^{2} MMD(X,Y)=n1i=1nϕ(xi)m1j=1mϕ(yj)H2

主代码编写

该代码基于torch.version = ‘1.9.0’

import torch
import torch.nn as nn

class MMDLoss(nn.Module):
    '''
    计算源域数据和目标域数据的MMD距离
    Params:
    source: 源域数据(n * len(x))
    target: 目标域数据(m * len(y))
    kernel_mul:
    kernel_num: 取不同高斯核的数量
    fix_sigma: 不同高斯核的sigma值
    Return:
    loss: MMD loss
    '''
    def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5, fix_sigma=None, **kwargs):
        super(MMDLoss, self).__init__()
        self.kernel_num = kernel_num
        self.kernel_mul = kernel_mul
        self.fix_sigma = None
        self.kernel_type = kernel_type

    def guassian_kernel(self, source, target, kernel_mul, kernel_num, fix_sigma):
        n_samples = int(source.size()[0]) + int(target.size()[0])
        total = torch.cat([source, target], dim=0)
        total0 = total.unsqueeze(0).expand(
            int(total.size(0)), int(total.size(0)), int(total.size(1)))
        total1 = total.unsqueeze(1).expand(
            int(total.size(0)), int(total.size(0)), int(total.size(1)))
        L2_distance = ((total0-total1)**2).sum(2)
        if fix_sigma:
            bandwidth = fix_sigma
        else:
            bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)
        bandwidth /= kernel_mul ** (kernel_num // 2)
        bandwidth_list = [bandwidth * (kernel_mul**i)
                          for i in range(kernel_num)]
        kernel_val = [torch.exp(-L2_distance / bandwidth_temp)
                      for bandwidth_temp in bandwidth_list]
        return sum(kernel_val)

    def linear_mmd2(self, f_of_X, f_of_Y):
        loss = 0.0
        delta = f_of_X.float().mean(0) - f_of_Y.float().mean(0)
        loss = delta.dot(delta.T)
        return loss

    def forward(self, source, target):
        if self.kernel_type == 'linear':
            return self.linear_mmd2(source, target)
        elif self.kernel_type == 'rbf':
            batch_size = int(source.size()[0])
            kernels = self.guassian_kernel(
                source, target, kernel_mul=self.kernel_mul, kernel_num=self.kernel_num, fix_sigma=self.fix_sigma)
            XX = torch.mean(kernels[:batch_size, :batch_size])
            YY = torch.mean(kernels[batch_size:, batch_size:])
            XY = torch.mean(kernels[:batch_size, batch_size:])
            YX = torch.mean(kernels[batch_size:, :batch_size])
            loss = torch.mean(XX + YY - XY - YX)
            return loss

程序验证

##在这里 第2维一定要相同,否则报错
source = torch.rand(64,14)  # 可以理解为源域有64个14维数据
target = torch.rand(32,14)  # 可以理解为源域有32个14维数据
print(target)
>>>output
tensor([[0.9035, 0.0088, 0.5867, 0.5595, 0.9350, 0.2739, 0.8775, 0.5562, 0.5402,
         0.5242, 0.4745, 0.7307, 0.7791, 0.7420],
        [0.2798, 0.6476, 0.3744, 0.5406, 0.3941, 0.6669, 0.2026, 0.8296, 0.3071,
         0.9042, 0.4810, 0.5235, 0.0547, 0.9110],
        [0.8051, 0.0702, 0.7907, 0.9708, 0.5310, 0.5851, 0.7881, 0.9082, 0.5963,
         0.9400, 0.3670, 0.8042, 0.5024, 0.2368],
        [0.5021, 0.7290, 0.3521, 0.6293, 0.8796, 0.2098, 0.0304, 0.9125, 0.3285,
         0.8485, 0.6877, 0.5695, 0.9506, 0.0752],
        [0.0798, 0.7908, 0.2785, 0.1369, 0.6762, 0.3342, 0.4930, 0.1807, 0.5963,
         0.2114, 0.4937, 0.4692, 0.3694, 0.9456],
         ...
        [0.1638, 0.7100, 0.9024, 0.5154, 0.8746, 0.8611, 0.1314, 0.0308, 0.6660,
         0.3719, 0.6827, 0.6789, 0.2416, 0.4617],
        [0.4449, 0.8304, 0.4036, 0.0563, 0.3832, 0.3553, 0.7947, 0.9335, 0.2704,
         0.9798, 0.2621, 0.4497, 0.9440, 0.7362]])
MMD = MMDLoss()
a = MMD(source=source, target=target)
print(a)
>>>output
tensor(0.1448)

嵌入到CNN中代码实现

先定义一个简单的CNN模型

class Net_only(nn.Module):
    '''
    计算源域数据和目标域数据的MMD距离
    Params:
    x_in: 输入数据(batch, channel, hight, width)
    Return:
    x_out: 输出数据(batch, n_labes)
    '''
    ## 这里 x_in:batch=64, channel=3, hight=128, width=128
    ## x_out:batch=64, n_labes=5
    def __init__(self):
        super(Net_only, self).__init__()
        self.conv1 = nn.Conv2d(3, 32, 3)
        self.pool = nn.MaxPool2d(2, 2)
        self.bn1 = nn.BatchNorm2d(32)
        self.conv2 = nn.Conv2d(32, 64, 3)
        self.pool = nn.MaxPool2d(2, 2)
        self.bn2 = nn.BatchNorm2d(64)
        self.conv3 = nn.Conv2d(64, 64, 3)
        self.pool = nn.MaxPool2d(2, 2)
        self.bn3 = nn.BatchNorm2d(64)
        self.conv3 = nn.Conv2d(64, 64, 3)
        self.drop1d = nn.Dropout(0.2)
        self.bn4 = nn.BatchNorm2d(64)
        self.fc1 = nn.Linear(64 * 14 * 14, 1024)
        self.fc2 = nn.Linear(1024, 256)
        self.fc3 = nn.Linear(256, 5)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.bn1(x)
        x = self.pool(F.relu(self.conv2(x)))
        x = self.bn2(x)
        x = self.pool(F.relu(self.conv3(x)))
        x = self.bn3(x)
        x = x.view(-1, x.size(1) * x.size(2) * x.size(3))
        x = F.relu(self.fc1(x))
        x = self.drop1d(x)
        x = F.relu(self.fc2(x))
        x = self.drop1d(x)
        x = self.fc3(x)
        return x

对CNN模型进行测试

model = Net_only()
source = torch.rand(64, 3, 128, 128) # 模拟产生batch=64,channel=3, hight=128, width=128 的源域图片数据
target = torch.rand(32, 3, 128, 128) # 模拟产生batch=32,channel=3, hight=128, width=128 的源域图片数据
source = model(source)
target = model(target)
print(source.shape)
>>>output
torch.Size([64, 5])

现在计算MMD损失

MMD = MMDLoss()
loss = MMD(source=source, target=target)
print(loss)
>>>output
tensor(0.0884, grad_fn=<MeanBackward0>)

迁移学习损失的运用

loss = clf_loss + lamb * transfer_loss
clf_loss是源域的分类损失,transfer_loss即本篇所介绍的MMD_loss,lamb是超参数

总结

迁移损失MMD其输入X, Y分别是souce = Net(source),target = Net(target),也就是模型的输出。
参考资料:
链接: 王晋东github
链接:https://blog.csdn.net/a529975125/article/details/81176029
欢迎关注公众号:故障诊断与python学习

  • 40
    点赞
  • 273
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 27
    评论
可以使用以下代码实现: ```python import torch import torch.nn as nn import torch.optim as optim import numpy as np from sklearn.metrics import accuracy_score from torch.autograd import Variable class DomainAdaptationModel(nn.Module): def __init__(self, num_classes=2): super(DomainAdaptationModel, self).__init__() self.feature_extractor = nn.Sequential( nn.Conv2d(3, 64, kernel_size=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(64, 128, kernel_size=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(128, 256, kernel_size=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(256, 512, kernel_size=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(512, 1024, kernel_size=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), ) self.classifier = nn.Sequential( nn.Linear(1024, 1024), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(1024, num_classes), ) def forward(self, x): x = self.feature_extractor(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x def mmd_loss(source_features, target_features): source_mean = torch.mean(source_features, dim=0) target_mean = torch.mean(target_features, dim=0) mmd = torch.mean(torch.pow(source_mean - target_mean, 2)) return mmd def domain_discriminator_loss(source_features, target_features): source_labels = torch.zeros(source_features.size(0)) target_labels = torch.ones(target_features.size(0)) labels = torch.cat((source_labels, target_labels), dim=0) features = torch.cat((source_features, target_features), dim=0) criterion = nn.BCEWithLogitsLoss() loss = criterion(features, labels) return loss def train(model, source_loader, target_loader, optimizer, num_epochs=10): model.train() for epoch in range(num_epochs): for i, (source_data, target_data) in enumerate(zip(source_loader, target_loader)): source_inputs, source_labels = source_data target_inputs, _ = target_data inputs = torch.cat((source_inputs, target_inputs), dim=0) inputs = Variable(inputs.cuda()) source_labels = Variable(source_labels.cuda()) optimizer.zero_grad() source_features = model(inputs[:source_inputs.size(0)]) target_features = model(inputs[source_inputs.size(0):]) mmd_loss_value = mmd_loss(source_features, target_features) domain_discriminator_loss_value = domain_discriminator_loss(source_features, target_features) classification_loss = nn.CrossEntropyLoss()(model(inputs[:source_inputs.size(0)]), source_labels) loss = classification_loss + mmd_loss_value + domain_discriminator_loss_value loss.backward() optimizer.step() if i % 100 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, len(source_loader), loss.item())) source_loader = torch.utils.data.DataLoader(source_dataset, batch_size=32, shuffle=True) target_loader = torch.utils.data.DataLoader(target_dataset, batch_size=32, shuffle=True) model = DomainAdaptationModel(num_classes=10) model.cuda() optimizer = optim.Adam(model.parameters(), lr=0.001) train(model, source_loader, target_loader, optimizer, num_epochs=10) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故障诊断与python学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值