【Python/Pytorch - 网络模型】-- TV Loss损失函数

文章目录

文章目录

  • [00 写在前面](#00 写在前面)
  • [01 基于Pytorch版本的TV Loss代码](#01 基于Pytorch版本的TV Loss代码)
  • [02 论文下载](#02 论文下载)

00 写在前面

在医学图像重建过程中,经常在代价方程中加入TV 正则项,该正则项作为去噪项,对于重建可以起到很大帮助作用。但是对于一些纹理细节要求较高的任务,加入TV 正则项,在一定程度上可能会降低纹理细节。

对于连续函数,其表达式为:

对于图片而言,即为离散的数值,求每一个像素和横向下一个像素的差的平方,加上纵向下一个像素的差的平方,再开β/2次根:

01 基于Pytorch版本的TV Loss代码

python 复制代码
import torch
from torch.autograd import Variable


class TVLoss(torch.nn.Module):
    """
    TV loss
    """

    def __init__(self, weight=1):
        super(TVLoss, self).__init__()
        self.weight = weight

    def forward(self, x):
        batch_size = x.size()[0]
        h_x = x.size()[2]
        w_x = x.size()[3]
        count_h = self._tensor_size(x[:, :, 1:, :])
        count_w = self._tensor_size(x[:, :, :, 1:])
        h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, :h_x - 1, :]), 2).sum()
        w_tv = torch.pow((x[:, :, :, 1:] - x[:, :, :, :w_x - 1]), 2).sum()
        return self.weight * 2 * (h_tv / count_h + w_tv / count_w) / batch_size

    def _tensor_size(self, t):
        return t.size()[1] * t.size()[2] * t.size()[3]


if __name__ == "__main__":
    x = Variable(
        torch.FloatTensor([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]).view(1, 2, 3, 3),
        requires_grad=True)
    tv = TVLoss()
    result = tv(x)
    print(result)

02 论文下载

Understanding Deep Image Representations by Inverting Them

相关推荐
luckdewei1 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
用户3521802454751 小时前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
米小虾2 小时前
手把手教你搭建第一个生产级AI Agent:从选型到实战的完整指南
人工智能·agent
任沫2 小时前
Agent之Function Call
javascript·人工智能·go
米小虾2 小时前
2026年AI Agent全面爆发:从开源生态到企业级应用的进化之路
人工智能·agent
用户6919026813392 小时前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
To_OC3 小时前
别再跟 AI 死磕 prompt 了,我写了个 Loop 让它自己改到满意为止
人工智能·aigc·agent
血小溅3 小时前
三大 AI 编码框架深度对比:GSD vs OpenSpec vs Superpowers
人工智能·后端
武子康6 小时前
调查研究-186 LangChain 和 LangGraph 的区别:从快速构建 Agent 到生产级工作流编排
人工智能·langchain·llm
武子康7 小时前
调查研究-185 CodeGraph 调研:给 AI 编程 Agent 一张代码库地图,少一点反复 grep(2026)
人工智能·openai·claude