多任务学习 Pytorch实现

article/2025/11/8 13:40:07

多任务学习MTL的简单实现,主要是为了理解MTL

代码写得挺烂的,有时间回来整理一下

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
from torch.autograd import Variable
import pandas as pd
import math
import sklearn.preprocessing as sk
from tensorboardX import SummaryWriter
import seaborn as sns
from sklearn.model_selection import KFold
from sklearn import metrics
from sklearn.feature_selection import VarianceThreshold
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split
import randomseed = 42
random.seed(seed)
torch.cuda.manual_seed_all(seed)N = 10000
M = 100
c = 0.5
p = 0.9
k = np.random.randn(M)
u1 = np.random.randn(M)
u1 -= u1.dot(k) * k / np.linalg.norm(k)**2
u1 /= np.linalg.norm(u1) 
k /= np.linalg.norm(k) 
u2 = k
w1 = c*u1
w2 = c*(p*u1+np.sqrt((1-p**2))*u2)
X = np.random.normal(0, 1, (N, M))
eps1 = np.random.normal(0, 0.01)
eps2 = np.random.normal(0, 0.01)
Y1 = np.matmul(X, w1) + np.sin(np.matmul(X, w1))+eps1
Y2 = np.matmul(X, w2) + np.sin(np.matmul(X, w2))+eps2
split = list(np.random.permutation(N))X_train = X[split[0:8000],:]
Y1_train = Y1[split[0:8000]]
Y2_train = Y2[split[0:8000]]
X_valid = X[8000:9000,:]
Y1_valid = Y1[8000:9000]
Y2_valid = Y2[8000:9000]
X_test = X[9000:10000,:]
Y1_test = Y1[9000:10000]
Y2_test = Y2[9000:10000]
print(X_train.shape)
print(X_valid.shape)
print(X_test.shape)
print(Y1_train.shape)
print(Y2_train.shape)
print(Y1_valid.shape)
print(Y2_valid.shape)
print(Y1_test.shape)
print(Y2_test.shape)X_train = torch.from_numpy(X_train)
X_train = X_train.float()
Y1_train = torch.tensor(Y1_train)
Y1_train = Y1_train.float()
Y2_train = torch.tensor(Y2_train)
Y2_train = Y2_train.float()X_valid = torch.from_numpy(X_valid)
X_valid = X_valid.float()
Y1_valid = torch.tensor(Y1_valid)
Y1_valid = Y1_valid.float()
Y2_valid = torch.tensor(Y2_valid)
Y2_valid = Y2_valid.float()X_test = torch.from_numpy(X_test)
X_test = X_test.float()
Y1_test = torch.tensor(Y1_test)
Y1_test = Y1_test.float()
Y2_test = torch.tensor(Y2_test)
Y2_test = Y2_test.float()print(X_train.shape)
print(X_valid.shape)
print(X_test.shape)
print(Y1_train.shape)
print(Y2_train.shape)
print(Y1_valid.shape)
print(Y2_valid.shape)
print(Y1_test.shape)
print(Y2_test.shape)input_size, feature_size = X.shape
shared_layer_size = 64
tower_h1 = 32
tower_h2 = 16
output_size = 1
LR = 0.001
epoch = 50
mb_size = 100
cost1tr = []
cost2tr = []
cost1D = []
cost2D = []
cost1ts = []
cost2ts = []
costtr = []
costD = []
costts = []class MTLnet(nn.Module):def __init__(self):super(MTLnet, self).__init__()self.sharedlayer = nn.Sequential(nn.Linear(feature_size, shared_layer_size),nn.ReLU(),nn.Dropout())self.tower1 = nn.Sequential(nn.Linear(shared_layer_size, tower_h1),nn.ReLU(),nn.Dropout(),nn.Linear(tower_h1, tower_h2),nn.ReLU(),nn.Dropout(),nn.Linear(tower_h2, output_size))self.tower2 = nn.Sequential(nn.Linear(shared_layer_size, tower_h1),nn.ReLU(),nn.Dropout(),nn.Linear(tower_h1, tower_h2),nn.ReLU(),nn.Dropout(),nn.Linear(tower_h2, output_size))        def forward(self, x):h_shared = self.sharedlayer(x)out1 = self.tower1(h_shared)out2 = self.tower2(h_shared)return out1, out2def random_mini_batches(XE, R1E, R2E, mini_batch_size = 10, seed = 42): # Creating the mini-batchesnp.random.seed(seed)            m = XE.shape[0]                  mini_batches = []permutation = list(np.random.permutation(m))shuffled_XE = XE[permutation,:]shuffled_X1R = R1E[permutation]shuffled_X2R = R2E[permutation]num_complete_minibatches = math.floor(m/mini_batch_size)for k in range(0, int(num_complete_minibatches)):mini_batch_XE = shuffled_XE[k * mini_batch_size : (k+1) * mini_batch_size, :]mini_batch_X1R = shuffled_X1R[k * mini_batch_size : (k+1) * mini_batch_size]mini_batch_X2R = shuffled_X2R[k * mini_batch_size : (k+1) * mini_batch_size]mini_batch = (mini_batch_XE, mini_batch_X1R, mini_batch_X2R)mini_batches.append(mini_batch)Lower = int(num_complete_minibatches * mini_batch_size)Upper = int(m - (mini_batch_size * math.floor(m/mini_batch_size)))if m % mini_batch_size != 0:mini_batch_XE = shuffled_XE[Lower : Lower + Upper, :]mini_batch_X1R = shuffled_X1R[Lower : Lower + Upper]mini_batch_X2R = shuffled_X2R[Lower : Lower + Upper]mini_batch = (mini_batch_XE, mini_batch_X1R, mini_batch_X2R)mini_batches.append(mini_batch)return mini_batchesMTL = MTLnet()
optimizer = torch.optim.Adam(MTL.parameters(), lr=LR)
loss_func = nn.MSELoss()for it in range(epoch):epoch_cost = 0epoch_cost1 = 0epoch_cost2 = 0num_minibatches = int(input_size / mb_size) minibatches = random_mini_batches(X_train, Y1_train, Y2_train, mb_size)for minibatch in minibatches:XE, YE1, YE2  = minibatch Yhat1, Yhat2 = MTL(XE)l1 = loss_func(Yhat1, YE1.view(-1,1))    l2 = loss_func(Yhat2, YE2.view(-1,1))loss =  (l1 + l2)/2optimizer.zero_grad()loss.backward()optimizer.step()epoch_cost = epoch_cost + (loss / num_minibatches)epoch_cost1 = epoch_cost1 + (l1 / num_minibatches)epoch_cost2 = epoch_cost2 + (l2 / num_minibatches)costtr.append(torch.mean(epoch_cost))cost1tr.append(torch.mean(epoch_cost1))cost2tr.append(torch.mean(epoch_cost2))with torch.no_grad():Yhat1D, Yhat2D = MTL(X_valid)l1D = loss_func(Yhat1D, Y1_valid.view(-1,1))l2D = loss_func(Yhat2D, Y2_valid.view(-1,1))cost1D.append(l1D)cost2D.append(l2D)costD.append((l1D+l2D)/2)print('Iter-{}; Total loss: {:.4}'.format(it, loss.item()))plt.plot(np.squeeze(costtr), '-r',np.squeeze(costD), '-b')
plt.ylabel('total cost')
plt.xlabel('iterations (per tens)')
plt.show() plt.plot(np.squeeze(cost1tr), '-r', np.squeeze(cost1D), '-b')
plt.ylabel('task 1 cost')
plt.xlabel('iterations (per tens)')
plt.show() plt.plot(np.squeeze(cost2tr),'-r', np.squeeze(cost2D),'-b')
plt.ylabel('task 2 cost')
plt.xlabel('iterations (per tens)')
plt.show()

 

参考:

https://github.com/hosseinshn/Basic-Multi-task-Learning


http://chatgpt.dhexx.cn/article/6SY1g9FW.shtml

相关文章

【综述】多任务学习

前言 本文对多任务学习(multi-task learning, MTL)领域近期的综述文章进行整理,从模型结构和训练过程两个层面回顾了其发展变化,旨在提供一份 MTL 入门指南,帮助大家快速了解多任务学习的进化史。 1. 什么是多任务学习? 多任务学习…

多任务学习原理与优化

文章目录 一、什么是多任务学习二、为什么我们需要多任务学习三、多任务学习模型演进Hard shared bottom 硬共享Soft shared bottom 软共享软共享: MOE & MMOE软共享: CGC & PLE加入FMMMOE/PLE 的调参ESMM 四、 loss权重1, 利用任务的…

【多任务学习-Multitask Learning概述】

多任务学习-Multitask Learning概述 1.单任务学习VS多任务学习多任务学习的提出多任务学习和单任务学习对比 2.多任务学习共享表示shared representation:多任务学习的优点那么如何衡量两个任务是否相关呢? 当任务之间相关性弱多任务MLP特点总结多任务学…

多任务学习(Multi-Task Learning, MTL)

目录 [显示] 1 背景2 什么是多任务学习?3 多任务学习如何发挥作用? 3.1 提高泛化能力的潜在原因3.2 多任务学习机制3.3 后向传播多任务学习如何发现任务是相关的4 多任务学习可被广泛应用? 4.1 使用未来预测现在4.2 多种表示和度量4.3 时间序…

Tensorflow 多任务学习

之前在caffe上实现了两个标签的多任务学习,如今换到了tensorflow,也想尝试一下,总的来说也不是很复杂。 建立多任务图 多任务的一个特点是单个tensor输入(X),多个输出(Y_1,Y_2...)。因此在定义占位符时要定义多个输出。同样也需要…

多任务学习:Multi-Task Learning as Multi-Objective Optimization

前言 最近在写一篇文章,是一篇深度学习与安全相结合的文章,模型的输出会交给两个损失函数(availability & security)进行损失计算,进而反向传播。起初的想法是直接将两项损失进行加权平均,共同进行反向…

深度学习中的多任务学习(一)

任务学习-Multitask Learning概述 Reference https://blog.csdn.net/u010417185/article/details/83065506 1、单任务学习VS多任务学习 单任务学习:一次只学习一个任务(task),大部分的机器学习任务都属于单任务学习。多任务学习…

C# 多线程八 任务Task的简单理解与运用二

目录 一.Task 1.AsyncState 2.CompletedTask 3.CreationOptions 4.CurrentId 5.Exception 6.Factory 7.Id 8.IsCanceled 9.IsCompleted 10.IsFaulted 11.Status 二.Task<TResult> 1.Result 上篇&#xff1a; C#…

多任务学习(一)

多任务学习 单任务学习 样本之间没有关联性。 缺点&#xff1a;训练出来的模型不具有泛化性&#xff1b;不共享信息使得学习能力下降。 多任务学习 多任务学习的构建原则 建模任务之间的相关性同时对多个任务的模型参数进行联合学习&#xff0c;挖掘其中的共享信息&#…

多任务学习-Multitask Learning概述

2020-02-22 09:59:48 1、单任务学习VS多任务学习 单任务学习&#xff1a;一次只学习一个任务&#xff08;task&#xff09;&#xff0c;大部分的机器学习任务都属于单任务学习。 多任务学习&#xff1a;把多个相关&#xff08;related&#xff09;的任务放在一起学习&#x…

深度学习之----多任务学习

介绍 在机器学习&#xff08;ML&#xff09;中&#xff0c;通常的关注点是对特定度量进行优化&#xff0c;度量有很多种&#xff0c;例如特定基准或商业 KPI 的分数。为了做到这一点&#xff0c;我们通常训练一个模型或模型组合来执行目标任务。然后&#xff0c;我们微调这些模…

深度学习中的多任务学习介绍

在2017年有一篇关于在深度神经网络中多任务学习概述的论文&#xff1a;《An Overview of Multi-Task Learning in Deep Neural Networks》&#xff0c;论文链接为&#xff1a;https://arxiv.org/pdf/1706.05098.pdf&#xff0c;它介绍了在深度学习中多任务学习(Multi-task Lear…

C# 多线程七 任务Task的简单理解与运用一

目录 一.Task 二.Task中的全局队列和本地队列 三.TaskCreationOptions 枚举 四.CancellationTokenSource/CancellationToken 1.延时取消线程 2.立即取消&#xff1a; 五.Task的三种调用方式 为了防止大家被标题误导 写在前面&#xff1a; Task并不是线程 Task的执行需要…

整理学习之多任务学习

如果有n个任务&#xff08;传统的深度学习方法旨在使用一种特定模型仅解决一项任务&#xff09;&#xff0c;而这n个任务或它们的一个子集彼此相关但不完全相同&#xff0c;则称为多任务学习&#xff08;MTL&#xff09; 通过使用所有n个任务中包含的知识&#xff0c;将有助于改…

多任务学习优化总结 Multi-task learning(附代码)

目录 一、多重梯度下降multiple gradient descent algorithm (MGDA) 二、Gradient Normalization (GradNorm) 三、Uncertainty 多任务学习的优势不用说了&#xff0c;主要是可以合并模型&#xff0c;减小模型体积&#xff0c;只用一次推理也可以加快速度。对于任务表现的提升…

经验 | 训练多任务学习(Multi-task Learning)方法总结

点击上方“小白学视觉”&#xff0c;选择加"星标"或“置顶” 重磅干货&#xff0c;第一时间送达 转载于&#xff1a;知乎Anticoder https://zhuanlan.zhihu.com/p/59413549 背景&#xff1a;只专注于单个模型可能会忽略一些相关任务中可能提升目标任务的潜在信息&…

多任务学习(Multi-Task Learning)

转自&#xff1a;https://www.cnblogs.com/zeze/p/8244357.html 1. 前言 多任务学习&#xff08;Multi-task learning&#xff09;是和单任务学习&#xff08;single-task learning&#xff09;相对的一种机器学习方法。在机器学习领域&#xff0c;标准的算法理论是一次学习一…

多任务学习 | YOLOP,一个网络同时完成三大任务

关注并星标 从此不迷路 计算机视觉研究院 公众号ID&#xff5c;ComputerVisionGzq 学习群&#xff5c;扫码在主页获取加入方式 paper: https://arxiv.org/abs/2108.11250 code: https://github.com/hustvl/YOLOP 计算机视觉研究院专栏 作者&#xff1a;Edison_G YOLOP: You Onl…

多任务学习概述

文章目录 前言1 文章信息2 背景、目的、结论2.1 背景2.1.1 多任务的类型分类2.1.1.1 相关任务的分类2.1.1.2 将输入变输出的逆多任务学习2.1.1.3 对抗性多任务学习2.1.1.4 辅助任务提供注意力特征的多任务学习2.1.1.5 附加预测性辅助任务的多任务学习 3 内容与讨论3.1 多任务学…

多任务学习(Multi-task Learning)方法总结

多任务学习&#xff08;multi task learning&#xff09;简称为MTL。简单来说有多个目标函数loss同时学习的就算多任务学习。多任务既可以每个任务都搞一个模型来学&#xff0c;也可以一个模型多任务学习来一次全搞定的。 作者丨Anticoder知乎 链接丨https://zhuanlan.zhihu.co…