2025.7.16学习日记
1.语义分割任务练习1-Unet
1.1 语义分割简介
语义分割(semantic segmentation)就是按照语义给图像上的每一个点打一个标签,即像素级的分类任务。具体来讲给定一对RGB图片与灰度图像的pair,输出一个分割图(有时候也被称为分割图谱)。这个分割图其实是公式Fij=argmax(f1ij,f2ij,..fnij)的结果,这个公式找到了f1(i,j),f2(i,j),...,fn(i,j)的最大索引通道号。
【注】:这里有种转换思想,n分类问题可以直接输出n种类别的概率,涉及到的就是多分类交叉熵损失;但还可以使用embedding的方式,为每个数字(类别)进行onehot(直接字段编码)
1.2 模型搭建
等待中...
1.3 模型训练
煮啵在微信公众号上找到了一篇比较适合入门的Unet模型训练的指南,WX搜索该作者JackCui,然后找到其关于Unet的训练文章即可
作者谈及到要想训练一个深度学习模型,简单来说分为

- 数据加载
Pytorch提供了一个类,方便我们加载数据,以下是伪代码的框架
# ================================================================== #
# Input pipeline for custom dataset #
# ================================================================== #
class CustomDataset(torch.utils.data.Dataset):
def __init__(self):
# TODO
# 1. 初始化 file paths 或者 a list of file names.
# 这里最重要的是做一个关于数据存储路径的列表
# 例如我们可以创建一个self.img_path=['YourPath/1.png','YourPath/2.png',...]
pass
def __getitem__(self, index):
# TODO
# 1. 从file中read一份数据 (e.g. using numpy.fromfile, PIL.Image.open).
# 2. 对数据进行 preprocess (e.g. torchvision.Transform).
# 3. 返回一份 data pair (e.g. image and label).
pass
def __len__(self):
# 返回数据集的长度,把下面的0改成你的数据集的长度
return 0
【注】:CRUD属于数据库中的概念,是增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete)几个单词的首字母简写,数据加载中的主要用到R,获得路径
【注】:在获取label或anno时,如果没有label或者anno,可以使用现有的预训练大模型获得label或anno。
如果真实用到Unet所需要处理的数据集中,需要做如下修改
import torch
import cv2
import os
import glob
from torch.utils.data import Dataset
import random
class ISBI_Loader(Dataset):
def __init__(self, data_path):
# 初始化函数,读取所有data_path下的图片
self.data_path = data_path
self.imgs_path = glob.glob(os.path.join(data_path, 'image/*.png'))
def augment(self, image, flipCode):
# 使用cv2.flip进行数据增强,filpCode为1水平翻转,0垂直翻转,-1水平+垂直翻转
flip = cv2.flip(image, flipCode)
return flip
def __getitem__(self, index):
# 根据index读取图片
image_path = self.imgs_path[index]
# 根据image_path生成label_path
label_path = image_path.replace('image', 'label')
# 读取训练图片和标签图片
image = cv2.imread(image_path)
label = cv2.imread(label_path)
# 将数据转为单通道的图片
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
label = cv2.cvtColor(label, cv2.COLOR_BGR2GRAY)
image = image.reshape(1, image.shape[0], image.shape[1])
label = label.reshape(1, label.shape[0], label.shape[1])
# 处理标签,将像素值为255的改为1
if label.max() > 1:
label = label / 255
# 随机进行数据增强,为2时不做处理
flipCode = random.choice([-1, 0, 1, 2])
if flipCode != 2:
image = self.augment(image, flipCode)
label = self.augment(label, flipCode)
return image, label
def __len__(self):
# 返回训练集大小
return len(self.imgs_path)
if __name__ == "__main__":
isbi_dataset = ISBI_Loader("data/train/")
print("数据个数:", len(isbi_dataset))
train_loader = torch.utils.data.DataLoader(dataset=isbi_dataset,
batch_size=2,
shuffle=True)
for image, label in train_loader:
print(image.shape)
- 模型选择
如果使用论文中的网络结构。模型的输出尺寸会稍微小于图片的输入尺寸,按照公共号作者的说法,最后需要进行一个resize的操作,为了能实现“原图直出”的效果,下图是作者编写的各种组件,写入unet_parts.py文件中。
""" Parts of the U-Net model """
"""https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.double_conv(x)
class Down(nn.Module):
"""Downscaling with maxpool then double conv"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.maxpool_conv = nn.Sequential(
nn.MaxPool2d(2),
DoubleConv(in_channels, out_channels)
)
def forward(self, x):
return self.maxpool_conv(x)
class Up(nn.Module):
"""Upscaling then double conv"""
def __init__(self, in_channels, out_channels, bilinear=True):
super().__init__()
# if bilinear, use the normal convolutions to reduce the number of channels
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
else:
self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2)
self.conv = DoubleConv(in_channels, out_channels)
def forward(self, x1, x2):
x1 = self.up(x1)
# input is CHW
diffY = torch.tensor([x2.size()[2] - x1.size()[2]])
diffX = torch.tensor([x2.size()[3] - x1.size()[3]])
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
diffY // 2, diffY - diffY // 2])
x = torch.cat([x2, x1], dim=1)
return self.conv(x)
class OutConv(nn.Module):
def __init__(self, in_channels, out_channels):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
def forward(self, x):
return self.conv(x)
最后我们可以写一个组装文件unet.model.py,组装成完整的模型
""" Full assembly of the parts to form the complete network """
"""Refer https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_model.py"""
import torch.nn.functional as F
from .unet_parts import *
class UNet(nn.Module):
def __init__(self, n_channels, n_classes, bilinear=True):
super(UNet, self).__init__()
self.n_channels = n_channels
self.n_classes = n_classes
self.bilinear = bilinear
self.inc = DoubleConv(n_channels, 64)
self.down1 = Down(64, 128)
self.down2 = Down(128, 256)
self.down3 = Down(256, 512)
self.down4 = Down(512, 512)
self.up1 = Up(1024, 256, bilinear)
self.up2 = Up(512, 128, bilinear)
self.up3 = Up(256, 64, bilinear)
self.up4 = Up(128, 64, bilinear)
self.outc = OutConv(64, n_classes)
def forward(self, x):
x1 = self.inc(x)
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
x = self.up1(x5, x4)
x = self.up2(x, x3)
x = self.up3(x, x2)
x = self.up4(x, x1)
logits = self.outc(x)
return logits
if __name__ == '__main__':
net = UNet(n_channels=3, n_classes=1)
print(net)
这里需要注意一下n_classes这个参数,由于实际上背景也算一个类别,所以如果你需要完成n分类的任务时,实际上为n-1
2.VGGT论文的相关工作
煮啵最近虽然有想法,但是不知道怎么训练,所以看了看相关工作,煮啵基本上从Google Scholar上找的相关工作。后相关的工作有VLM,前相关工作有DUST3R,VGGT作者给予DUST3R的工作评价相当高可以重点关注下。
2.1 VLM 等待中...
VLM为视觉语言模型的简称,这篇论文的标题是利用几何蒸馏对视觉语言模型进行微调,在Related Work中提及到微调VLMs(Fine-tuning),3D Foundation Models,以及其中的Bridging
2.2 DUST3R
等待中...
3.预训练大模型在个人学习任务中的使用
煮啵在接触完预训练大模型后,比较深刻的感受就是预训练大模型对于数据注释的帮助。还有就是能力比较强的LLM,能够给出的信息更多。煮啵从GPT4o身上学到了怎么去冻结参数,即使煮啵完全没有给任何的提示词。但是出现了optimizer(list(Parameter))的形式
ToDoList
【 】VLM:什么是Geometry先验,什么是基础空间推理任务,什么是直接监督,什么是无需标注的微调方法,什么是自监督,什么是3D数据模态(点云或3D高斯分布)

浙公网安备 33010602011771号