基于头部姿态和面部图像数据融合的MobileViT分类任务 - bias is not None:

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力2027 👁️ 568 次阅读

基于头部姿态和面部图像数据融合的MobileViT分类任务

本篇主要讲述深度学习网络中的数据融合。

一、网络模型

选用MobileViT网络,该网络的代码来自B站UP主“霹雳吧啦Wz”。

二、所需数据

1.经由实验室设备和代码采集的人面部图像(处理相机矫正过后拍摄的人上半身图像后得到)。

2.对相机矫正过后拍摄的人上半身图像中的人体头部姿态数据(pitch, roll, yaw),以CSV格式保存。

三、读取CSV文件

下载了MobileViT代码之后,只需要改动 my_dataset.py 和 utils.py 这两个文件就可以将我们准备好的csv文件读进我们的网络模型了。

1.my_dataset.py

import os.path

from PIL import Image

import torch

from torch.utils.data import Dataset

import csv

# 读取头部姿态文件

def readcsv():

num = 6 # 6分类任务,csv文件对应在6个文件类别里

path = {}

for i in range(num):

# 添加不同人的头部姿态数据集

pathl = os.path.join("/successFUL/MobileViT_SE/data2", str(i), "l.csv")

pathr = os.path.join("/successFUL/MobileViT_SE/data2", str(i), "r.csv")

pathwl = os.path.join("/successFUL/MobileViT_SE/data2", str(i), "ll.csv")

pathwr = os.path.join("/successFUL/MobileViT_SE/data2", str(i), "rr.csv")

# 每加载一个csv,都要处理一遍

with open(pathl, "r") as file:

rows = file.readlines()

for row in rows:

if row[0] != "I":

a = row.split(",")

path[a[0]] = (a[1], a[2], a[3])

with open(pathr, "r") as file:

rows = file.readlines()

for row in rows:

if row[0] != "I":

a = row.split(",")

path[a[0]] = (a[1], a[2], a[3])

with open(pathwl, "r") as file:

rows = file.readlines()

for row in rows:

if row[0] != "I":

a = row.split(",")

path[a[0]] = (a[1], a[2], a[3])

with open(pathwr, "r") as file:

rows = file.readlines()

for row in rows:

if row[0] != "I":

a = row.split(",")

path[a[0]] = (a[1], a[2], a[3])

return path

class MyDataSet(Dataset):

"""自定义数据集"""

def __init__(self, images_path: list, images_class: list, transform=None):

self.images_path = images_path

self.images_class = images_class

self.transform = transform

self.path = readcsv()

def __len__(self):

return len(self.images_path)

def __getitem__(self, item):

img = Image.open(self.images_path[item])

path = os.path.basename(self.images_path[item])

# pitch, roll, yaw是CSV文件中我定义的3个数据名

pitch, roll, yaw = float(self.path[path][0]), float(self.path[path][1]), float(self.path[path][2])

hplabel = torch.tensor([pitch, roll, yaw])

# RGB为彩色图片,L为灰度图片

if img.mode != 'RGB':

raise ValueError("image: {} isn't RGB mode.".format(self.images_path[item]))

label = self.images_class[item]

if self.transform is not None:

img = self.transform(img)

return img, label, hplabel # 增加返回 hplabel

@staticmethod

def collate_fn(batch):

# 官方实现的default_collate可以参考

# https://github.com/pytorch/pytorch/blob/67b7e751e6b5931a9f45274653f4f653a4e6cdf6/torch/utils/data/_utils/collate.py

images, labels, hplabels = tuple(zip(*batch))

images = torch.stack(images, dim=0)

labels = torch.as_tensor(labels)

hplabels = torch.stack(hplabels, dim=0)

return images, labels, hplabels

2.utils.py

import os

import sys

import json

import pickle

import random

import torch

from tqdm import tqdm

import matplotlib.pyplot as plt

def read_split_data(root: str, val_rate: float = 0.2):

random.seed(0) # 保证随机结果可复现

assert os.path.exists(root), "dataset root: {} does not exist.".format(root)

# 遍历文件夹,一个文件夹对应一个类别

flower_class = [cla for cla in os.listdir(root) if os.path.isdir(os.path.join(root, cla))]

# 排序,保证各平台顺序一致

flower_class.sort()

# 生成类别名称以及对应的数字索引

class_indices = dict((k, v) for v, k in enumerate(flower_class))

json_str = json.dumps(dict((val, key) for key, val in class_indices.items()), indent=4)

with open('class_indices.json', 'w') as json_file:

json_file.write(json_str)

train_images_path = [] # 存储训练集的所有图片路径

train_images_label = [] # 存储训练集图片对应索引信息

val_images_path = [] # 存储验证集的所有图片路径

val_images_label = [] # 存储验证集图片对应索引信息

every_class_num = [] # 存储每个类别的样本总数

supported = [".jpg", ".JPG", ".png", ".PNG"] # 支持的文件后缀类型

# 遍历每个文件夹下的文件

for cla in flower_class:

cla_path = os.path.join(root, cla)

# 遍历获取supported支持的所有文件路径

images = [os.path.join(root, cla, i) for i in os.listdir(cla_path)

if os.path.splitext(i)[-1] in supported]

# 排序,保证各平台顺序一致

images.sort()

# 获取该类别对应的索引

image_class = class_indices[cla]

# 记录该类别的样本数量

every_class_num.append(len(images))

# 按比例随机采样验证样本

val_path = random.sample(images, k=int(len(images) * val_rate))

for img_path in images:

if img_path in val_path: # 如果该路径在采样的验证集样本中则存入验证集

val_images_path.append(img_path)

val_images_label.append(image_class)

else: # 否则存入训练集

train_images_path.append(img_path)

train_images_label.append(image_class)

print("{} images were found in the dataset.".format(sum(every_class_num)))

print("{} images for training.".format(len(train_images_path)))

print("{} images for validation.".format(len(val_images_path)))

assert len(train_images_path) > 0, "number of training images must greater than 0."

assert len(val_images_path) > 0, "number of validation images must greater than 0."

plot_image = True # 改为了True

if plot_image:

# 绘制每种类别个数柱状图

plt.bar(range(len(flower_class)), every_class_num, align='center')

# 将横坐标0,1,2,3,4替换为相应的类别名称

plt.xticks(range(len(flower_class)), flower_class)

# 在柱状图上添加数值标签

for i, v in enumerate(every_class_num):

plt.text(x=i, y=v + 5, s=str(v), ha='center')

# 设置x坐标

plt.xlabel('image class')

# 设置y坐标

plt.ylabel('number of images')

# 设置柱状图的标题

plt.title('flower class distribution')

plt.show()

return train_images_path, train_images_label, val_images_path, val_images_label

def plot_data_loader_image(data_loader):

batch_size = data_loader.batch_size

plot_num = min(batch_size, 4)

json_path = './class_indices.json'

assert os.path.exists(json_path), json_path + " does not exist."

json_file = open(json_path, 'r')

class_indices = json.load(json_file)

for data in data_loader:

images, labels = data

for i in range(plot_num):

# [C, H, W] ->[H, W, C]

img = images[i].numpy().transpose(1, 2, 0)

# 反Normalize操作

img = (img * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406]) * 255

label = labels[i].item()

plt.subplot(1, plot_num, i+1)

plt.xlabel(class_indices[str(label)])

plt.xticks([]) # 去掉x轴的刻度

plt.yticks([]) # 去掉y轴的刻度

plt.imshow(img.astype('uint8'))

plt.show()

def write_pickle(list_info: list, file_name: str):

with open(file_name, 'wb') as f: 拼多多帮助力入口

pickle.dump(list_info, f)

def read_pickle(file_name: str) ->list:

with open(file_name, 'rb') as f:

info_list = pickle.load(f)

return info_list

def train_one_epoch(model, optimizer, data_loader, device, epoch):

model.train()

loss_function = torch.nn.CrossEntropyLoss(label_smoothing=0.1)

accu_loss = torch.zeros(1).to(device) # 累计损失

accu_num = torch.zeros(1).to(device) # 累计预测正确的样本数

optimizer.zero_grad()

sample_num = 0

data_loader = tqdm(data_loader, file=sys.stdout)

for step, data in enumerate(data_loader):

images, labels, hplabel = data

sample_num += images.shape[0]

hplabel = hplabel.to(device) # 确保任务都在GPU上进行

pred = model(images.to(device), hplabel)

pred_classes = torch.max(pred, dim=1)[1]

accu_num += torch.eq(pred_classes, labels.to(device)).sum()

loss = loss_function(pred, labels.to(device))

loss.backward()

accu_loss += loss.detach()

data_loader.desc = "[train epoch {}] loss: {:.3f}, acc: {:.3f}".format(epoch,

accu_loss.item() / (step + 1),

accu_num.item() / sample_num)

if not torch.isfinite(loss):

print('WARNING: non-finite loss, ending training ', loss)

sys.exit(1)

optimizer.step()

optimizer.zero_grad()

return accu_loss.item() / (step + 1), accu_num.item() / sample_num

@torch.no_grad()

def evaluate(model, data_loader, device, epoch):

loss_function = torch.nn.CrossEntropyLoss()

model.eval()

accu_num = torch.zeros(1).to(device) # 累计预测正确的样本数

accu_loss = torch.zeros(1).to(device) # 累计损失

sample_num = 0

data_loader = tqdm(data_loader, file=sys.stdout)

for step, data in enumerate(data_loader):

images, labels, hplabel = data

sample_num += images.shape[0]

hplabel = hplabel.to(device) # 确保任务都在GPU上进行

pred = model(images.to(device), hplabel)

pred_classes = torch.max(pred, dim=1)[1]

accu_num += torch.eq(pred_classes, labels.to(device)).sum()

loss = loss_function(pred, labels.to(device))

accu_loss += loss

data_loader.desc = "[valid epoch {}] loss: {:.3f}, acc: {:.3f}".format(epoch,

accu_loss.item() / (step + 1),

accu_num.item() / sample_num)

return accu_loss.item() / (step + 1), accu_num.item() / sample_num

四、网络修改

只需要修改 model.py 中 class MobileViT(nn.Module) 中的 def forward 和 def __init__。

class MobileViT(nn.Module):

"""

This class implements the `MobileViT architecture`_

"""

def __init__(self, model_cfg: Dict, num_classes: int = 1000):

super().__init__()

image_channels = 3

out_channels = 16

# MobileViT一开始就是一个卷积

self.conv_1 = ConvLayer(

in_channels=image_channels,

out_channels=out_channels,

kernel_size=3,

stride=2

)

# 输出你想在哪加的那个维度,第一个100改这个维度

# 16*7*7 = 784

self.fcimage = nn.Linear(784, 100)

self.fchp = nn.Linear(3, 100)

self.tempconv1 = nn.AvgPool2d(kernel_size=2, stride=2)

self.tempconv2 = nn.AvgPool2d(kernel_size=2, stride=2)

self.tempconv3 = nn.AvgPool2d(kernel_size=2, stride=2)

self.tempconv4 = nn.AvgPool2d(kernel_size=2, stride=2)

self.fc = nn.Linear(100, 784)

self.layer_1, out_channels = self._make_layer(input_channel=out_channels, cfg=model_cfg["layer1"])

self.layer_2, out_channels = self._make_layer(input_channel=out_channels, cfg=model_cfg["layer2"])

self.layer_3, out_channels = self._make_layer(input_channel=out_channels, cfg=model_cfg["layer3"])

self.layer_4, out_channels = self._make_layer(input_channel=out_channels, cfg=model_cfg["layer4"])

self.layer_5, out_channels = self._make_layer(input_channel=out_channels, cfg=model_cfg["layer5"])

exp_channels = min(model_cfg["last_layer_exp_factor"] * out_channels, 960)

self.conv_1x1_exp = ConvLayer(

in_channels=out_channels,

out_channels=exp_channels,

kernel_size=1

)

self.classifier = nn.Sequential()

self.classifier.add_module(name="global_pool", module=nn.AdaptiveAvgPool2d(1))

self.classifier.add_module(name="flatten", module=nn.Flatten())

if 0.0 < model_cfg["cls_dropout"] < 1.0:

self.classifier.add_module(name="dropout", module=nn.Dropout(p=model_cfg["cls_dropout"]))

self.classifier.add_module(name="fc", module=nn.Linear(in_features=exp_channels, out_features=num_classes))

# weight init

self.apply(self.init_parameters)

def _make_layer(self, input_channel, cfg: Dict) ->Tuple[nn.Sequential, int]:

block_type = cfg.get("block_type", "mobilevit")

if block_type.lower() == "mobilevit":

return self._make_mit_layer(input_channel=input_channel, cfg=cfg)

else:

return self._make_mobilenet_layer(input_channel=input_channel, cfg=cfg)

@staticmethod

def _make_mobilenet_layer(input_channel: int, cfg: Dict) ->Tuple[nn.Sequential, int]:

output_channels = cfg.get("out_channels")

num_blocks = cfg.get("num_blocks", 2)

expand_ratio = cfg.get("expand_ratio", 4)

block = []

for i in range(num_blocks):

stride = cfg.get("stride", 1) if i == 0 else 1

layer = InvertedResidual(

in_channels=input_channel,

out_channels=output_channels,

stride=stride,

expand_ratio=expand_ratio

)

block.append(layer)

input_channel = output_channels

return nn.Sequential(*block), input_channel

@staticmethod

def _make_mit_layer(input_channel: int, cfg: Dict) ->[nn.Sequential, int]:

stride = cfg.get("stride", 1)

block = []

if stride == 2:

layer = InvertedResidual(

in_channels=input_channel,

out_channels=cfg.get("out_channels"),

stride=stride,

expand_ratio=cfg.get("mv_expand_ratio", 4)

)

block.append(layer)

input_channel = cfg.get("out_channels")

transformer_dim = cfg["transformer_channels"]

ffn_dim = cfg.get("ffn_dim")

num_heads = cfg.get("num_heads", 4)

head_dim = transformer_dim // num_heads

if transformer_dim % head_dim != 0:

raise ValueError("Transformer input dimension should be divisible by head dimension. "

"Got {} and {}.".format(transformer_dim, head_dim))

block.append(MobileViTBlock(

in_channels=input_channel,

transformer_dim=transformer_dim,

ffn_dim=ffn_dim,

n_transformer_blocks=cfg.get("transformer_blocks", 1),

patch_h=cfg.get("patch_h", 2),

patch_w=cfg.get("patch_w", 2),

dropout=cfg.get("dropout", 0.1),

ffn_dropout=cfg.get("ffn_dropout", 0.0),

attn_dropout=cfg.get("attn_dropout", 0.1),

head_dim=head_dim,

conv_ksize=3

))

return nn.Sequential(*block), input_channel

@staticmethod

def init_parameters(m):

if isinstance(m, nn.Conv2d):

if m.weight is not None:

nn.init.kaiming_normal_(m.weight, mode="fan_out")

if m.bias is not None:

nn.init.zeros_(m.bias)

elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)):

if m.weight is not None:

nn.init.ones_(m.weight)

if m.bias is not None:

nn.init.zeros_(m.bias)

elif isinstance(m, (nn.Linear,)):

if m.weight is not None:

nn.init.trunc_normal_(m.weight, mean=0.0, std=0.02)

if m.bias is not None:

nn.init.zeros_(m.bias)

else:

pass

def forward(self, x: Tensor, hp) ->Tensor:

x = self.conv_1(x)

# 从此处开始融合我们的数据

x = self.tempconv1(x)

x = self.tempconv2(x)

x = self.tempconv3(x)

x = self.tempconv4(x)

# 经过上面的卷积和平均池化,x = (32, 16, 7, 7)

x = x.view(x.size(0), -1) # 将四维张量调整为二维张量,才能送进全连接层

xout = self.fcimage(x) # xout=(32, 100)

hpout = self.fchp(hp) # hpout = (32, 100)

x = xout + hpout # 数据拼接

x = self.fc(x) # 拼接后的x进行一次nn.Linear,x=(32, 784)

# 此处的参数应该通过计算得到,但(, , 7, 7)可以手动计算得到,是一种偷懒的写法

x = x.view(x.size(0), 16, 7, 7)

x = self.layer_1(x)

x = self.layer_2(x)

x = self.layer_3(x)

x = self.layer_4(x)

x = self.layer_5(x)

x = self.conv_1x1_exp(x)

x = self.classifier(x)

return x

五、试验结论

在师兄的帮助下,完成了这部分内容,遗憾的是融合了头部姿态后的分类效果不太理想,稍低于单纯的面部图像数据的分类效果。就在刚刚,我察觉到是否是头部姿态数据有误的原因导致训练效果不理想,于是将头部姿态的数据全部替换为0, 1, 2, 3, 4, 5五个数字进行试验,但结果与之前真实头部姿态数据相比几乎没有差距。所以需要改进呀!

六、实验改进

在哪里融合面部图像和头部姿态数据最合适?是让实验结果起死回生的关键。师兄告诉我正常的数据融合方式应该是从靠后的位置逐渐往前试,直到找到效果最好的地方进行融合。

1.之前的融合位置

# 输入图像的形状为(32, 3, 224, 224)——(bath_size, channel, height, weight)

def forward(self, x: Tensor, hp) ->Tensor:

x = self.conv_1(x) # 经过一次卷积后, x = (32, 16, 112, 112)

"""

从此处开始融合我们的数据,下面4个tempconv在__init__处定义

目的是降低图像宽和高的尺寸,以便送入全连接层进行特征融合

"""

x = self.tempconv1(x)

x = self.tempconv2(x)

x = self.tempconv3(x)

x = self.tempconv4(x)

# 经过上面的卷积和平均池化,x = (32, 16, 7, 7)

x = x.view(x.size(0), -1) # 将四维张量调整为二维张量,才能送进全连接层

xout = self.fcimage(x) # xout=(32, 100)

hpout = self.fchp(hp) # hpout = (32, 100)

x = xout + hpout # 数据拼接

x = self.fc(x) # 拼接后的x进行一次nn.Linear,x=(32, 784)

# 此处的参数应该通过计算得到,但(, , 7, 7)可以手动计算得到,是一种偷懒的写法

x = x.view(x.size(0), 16, 7, 7)

x = self.layer_1(x)

x = self.layer_2(x)

x = self.layer_3(x)

x = self.layer_4(x)

x = self.layer_5(x)

x = self.conv_1x1_exp(x)

x = self.classifier(x)

return x

这份代码是在 x = self.conv_1(x) 之后进行了数据融合。为什么要进行4次tempconv呢?详细解答如下:

self.fcimage = nn.Linear(784, 100)

self.fchp = nn.Linear(3, 100)

fcimage 和 fchp 分别对应了 面部图像和头部姿态数据,这两者是需要通过全连接层进行融合的。而融合的前提是两者的维度要匹配上。fcimage的参数(784, 100)——(输入尺寸, 输出尺寸)是怎么得到的呢?首先来说784,784 = 16 * 7 * 7,是我们人为操作得到的结果,因为对于全连接层而言,输入尺寸的值最好小于1000(师兄告诉我的)。所以说4次tempconv的目的就是减小图像的宽和高。

fchp的参数很简单, 3就表示它是一个三维数据(pitch, roll, yaw)。

关于 fcimage 和 fchp 的第二个参数100,这是通过经验得到的,选择相信就是了。

2.新的融合位置

这次我选择在Layer_5之后进行特征融合。

def forward(self, x: Tensor, hp) ->Tensor:

x = self.conv_1(x)

x = self.layer_1(x)

x = self.layer_2(x)

x = self.layer_3(x)

x = self.layer_4(x)

x = self.layer_5(x)

# 使用1*1的卷积降低通道数

x = self.conv_2(x)

x = x.view(x.size(0), -1)

xout = self.fcimage(x)

hpout = self.fchp(hp)

x = xout + hpout # 数据拼接

x = self.fc(x)

x = x.view(x.size(0), 20, 7, 7) # 固定值

x = self.conv_1x1_exp(x) # 相较于原来的代码,这行的声明处也要改

x = self.classifier(x)

return x

原始MobileViT对应此处的代码中x的形状是这样变化的:

After conv_1 : (32, 16, 112, 112)

After Layer_1 : (32, 16, 112, 112)

After Layer_2 : (32, 24, 56, 56)

After Layer_3 : (32, 48, 28, 28)

After Layer_4 : (32, 64, 14, 14)

After Layer_5 : (32, 80, 7, 7)

由于我们选择在Layer_5之后进行数据融合,此时要送入全连接层的尺寸为 80 * 7 * 7 = 3920,这个数字太大了,所以我们可以选用1 * 1的卷积来减少通道数(宽高不会变的)。将80降到20,此时 20 * 7 * 7 = 980,就是一个很理想的输入尺寸了。

通道数达到预期了,数据也融合了,但运行代码的适合在 x = self.conv_1x1_exp(x) 处报错了,应该改为:

self.conv_1x1_exp = ConvLayer(

in_channels=20,

out_channels=exp_channels,

kernel_size=1

)

直接将in_channels设置为20,即我们计算得到的结果,代码就不会报错了,大功告成!

最终的分类准确率非常可观!

基于头部姿态和面部图像数据融合的MobileViT分类任务

推荐文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧