You need to enable JavaScript to run this app. text features场景下Late Fusion可运行实现代码求助:领域入门者实操学习需求
优惠活动
大模型
产品
解决方案
定价
更多

text features场景下Late Fusion可运行实现代码求助:领域入门者实操学习需求

基于预生成文本特征的Late Fusion可落地实现(PyTorch)

核心本质:Late Fusion(晚期融合)和早期融合的核心区别是,不会在特征提取阶段就把不同来源的特征拼接到一起做交互,而是让每一路特征独立完成分类打分,最后在分数输出层做加权合并。你已经有抽好的文本特征,完全可以跳过最耗资源的文本编码环节,直接基于现有特征搭建融合流程,不需要从零改特征提取链路。

前置准备要求

  • 提前抽好的固定维度文本特征(一般存为.npy格式,shape为[总样本数, 文本特征维度])
  • 需要和文本特征融合的另一路特征(比如图像特征、结构化统计特征,维度和文本特征独立,样本数和文本特征完全对齐)
  • 安装基础依赖:numpy、torch 2.0+、scikit-learn

完整可运行参考代码

import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import accuracy_score

# ---------------------- 1. 自定义数据集:直接加载已存好的特征 ----------------------
class PreFeatureDataset(Dataset):
    def __init__(self, text_feat_path, other_feat_path, label_path):
        # 直接读取预存的.npy特征,无任何文本编码处理步骤
        self.text_feats = np.load(text_feat_path)
        self.other_feats = np.load(other_feat_path)
        self.labels = np.load(label_path)
    
    def __len__(self):
        return len(self.labels)
    
    def __getitem__(self, idx):
        return {
            "text_feat": torch.tensor(self.text_feats[idx], dtype=torch.float32),
            "other_feat": torch.tensor(self.other_feats[idx], dtype=torch.float32),
            "label": torch.tensor(self.labels[idx], dtype=torch.long)
        }

# ---------------------- 2. 核心Late Fusion模型实现 ----------------------
class LateFusionModel(nn.Module):
    def __init__(self, text_feat_dim, other_feat_dim, num_classes, fusion_weight=0.5):
        super().__init__()
        # 每一路配置独立分类头,不提前拼接特征——这是Late Fusion和Early Fusion的核心分界
        self.text_classifier = nn.Linear(text_feat_dim, num_classes)
        self.other_classifier = nn.Linear(other_feat_dim, num_classes)
        # 固定融合权重可手动调整,也可后续改成可学习参数
        self.fusion_weight = fusion_weight

    def forward(self, text_feat, other_feat):
        # 每一路独立输出分类logits,无特征层交互
        text_logits = self.text_classifier(text_feat)
        other_logits = self.other_classifier(other_feat)
        # 融合环节:在logits输出层做加权求和
        fused_logits = self.fusion_weight * text_logits + (1 - self.fusion_weight) * other_logits
        return text_logits, other_logits, fused_logits

# ---------------------- 3. 训练/推理流程 ----------------------
if __name__ == "__main__":
    # 替换成你自己的实际特征维度
    TEXT_FEAT_DIM = 768  # 例如BERT提取的文本特征维度
    OTHER_FEAT_DIM = 2048 # 例如ResNet提取的图像特征维度
    NUM_CLASSES = 10
    FUSION_WEIGHT = 0.6 # 文本贡献60%决策权重,另一路贡献40%

    # 替换成你本地存储的特征文件路径
    train_dataset = PreFeatureDataset(
        text_feat_path="./train_text_feats.npy",
        other_feat_path="./train_other_feats.npy",
        label_path="./train_labels.npy"
    )
    test_dataset = PreFeatureDataset(
        text_feat_path="./test_text_feats.npy",
        other_feat_path="./test_other_feats.npy",
        label_path="./test_labels.npy"
    )
    train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = LateFusionModel(TEXT_FEAT_DIM, OTHER_FEAT_DIM, NUM_CLASSES, FUSION_WEIGHT).to(device)
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)

    # 10轮基础训练
    for epoch in range(10):
        model.train()
        total_loss = 0
        for batch in train_loader:
            text_feat = batch["text_feat"].to(device)
            other_feat = batch["other_feat"].to(device)
            labels = batch["label"].to(device)
            
            # 前向传播
            text_logits, other_logits, fused_logits = model(text_feat, other_feat)
            # 损失项可自由调整:如果不需要辅助监督,直接计算融合后logits的交叉熵即可
            loss = 0.4 * criterion(text_logits, labels) + 0.4 * criterion(other_logits, labels) + 0.2 * criterion(fused_logits, labels)
            
            # 反向传播
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            total_loss += loss.item()
        
        # 测试集评估
        model.eval()
        all_preds = []
        all_labels = []
        with torch.no_grad():
            for batch in test_loader:
                text_feat = batch["text_feat"].to(device)
                other_feat = batch["other_feat"].to(device)
                labels = batch["label"].to(device)
                _, _, fused_logits = model(text_feat, other_feat)
                preds = torch.argmax(fused_logits, dim=1).cpu().numpy()
                all_preds.extend(preds)
                all_labels.extend(labels.cpu().numpy())
        acc = accuracy_score(all_labels, all_preds)
        print(f"Epoch {epoch+1}, 训练损失: {total_loss/len(train_loader):.4f}, 测试准确率: {acc:.4f}")

入门落地避坑提示

  • 不要混淆融合节点位置:如果在特征层就把文本特征、其他特征拼接后过全连接层再分类,属于Early Fusion,完全失去了Late Fusion“独立打分再合并”的设计初衷
  • 融合权重不用死记硬背:代码里写死的0.6文本权重只是示例,你可以把它改成可学习参数,训练时会自动学习最优的占比,只需要把初始化部分换成self.fusion_weight = nn.Parameter(torch.tensor(init_weight))即可
  • 训练效率优化:因为你已经有现成的预提取特征,不需要反复跑大模型提特征,整个训练过程只需要更新两个小分类头和融合权重,单卡甚至CPU都能快速跑完

内容的提问来源于stack exchange,提问作者Js541

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.21 04:15:00