LossMaskMatrix损失函数掩码矩阵

文章目录

  • [1. 理论](#1. 理论)
  • [2. python](#2. python)

1. 理论

A = [ 1 2 0 0 2 3 4 0 ] → B = [ 1 1 0 0 1 1 1 0 ] → C = [ 0.225 0.610 0 0 0.089 0.242 0.657 0 ] \begin{equation} A=\begin{bmatrix} 1&2&0&0\\\\ 2&3&4&0\end{bmatrix}\to B=\begin{bmatrix} 1&1&0&0\\\\ 1&1&1&0\end{bmatrix}\to C=\begin{bmatrix} 0.225&0.610&0&0\\\\ 0.089&0.242&0.657&0\end{bmatrix} \end{equation} A= 12230400 →B= 11110100 →C= 0.2250.0890.6100.24200.65700

2. python

python 复制代码
import torch
from torch import nn
from torch.nn import functional as F

torch.set_printoptions(precision=3, sci_mode=False)


class MatrixNoneZero2OnesLike(object):
    def __init__(self, in_matrix):
        self.in_matrix = in_matrix
        self._result = torch.zeros_like(self.in_matrix)

    @property
    def result(self):
        my_result = torch.zeros_like(self.in_matrix)
        my_result_bool = self.in_matrix.to(torch.bool)
        self._result = my_result.masked_fill(my_result_bool, 1)
        return self._result


class LossMaskedMatrix(object):
    def __init__(self, src_matrix):
        self.src_matrix = src_matrix.to(torch.float)
        self.nonzero = MatrixNoneZero2OnesLike(self.src_matrix)
        self.nonzero_matrix = self.nonzero.result
        self._loss_matrix = torch.zeros_like(self.src_matrix)

    @property
    def loss_matrix(self):
        my_soft_matrix = F.softmax(self.src_matrix, dim=-1)
        my_loss_matrix = my_soft_matrix * self.nonzero_matrix
        print(f"*" * 50)
        print(f"src_matrix=\n{self.src_matrix}")
        print(f"nonzero_matrix=\n{self.nonzero_matrix}")
        print(f"loss_matrix=\n{my_loss_matrix}")
        print(f"*" * 50)
        self._loss_matrix = my_loss_matrix

        return self._loss_matrix


if __name__ == "__main__":
    in_matrix = torch.tensor([[1, 2, 0, 0], [2, 3, 4, 0]]).to(torch.float)
    test_loss_matrix = LossMaskedMatrix(in_matrix)
    result = test_loss_matrix.loss_matrix
  • 结果:
python 复制代码
**************************************************
src_matrix=
tensor([[1., 2., 0., 0.],
        [2., 3., 4., 0.]])
nonzero_matrix=
tensor([[1., 1., 0., 0.],
        [1., 1., 1., 0.]])
loss_matrix=
tensor([[0.225, 0.610, 0.000, 0.000],
        [0.089, 0.242, 0.657, 0.000]])
**************************************************
相关推荐
SteveKenny1 小时前
Python 梯度下降法(六):Nadam Optimize
开发语言·python
dreadp3 小时前
解锁豆瓣高清海报(二) 使用 OpenCV 拼接和压缩
图像处理·python·opencv·计算机视觉·数据分析
梦云澜3 小时前
论文阅读(十二):全基因组关联研究中生物通路的图形建模
论文阅读·人工智能·深度学习
Tester_孙大壮3 小时前
第32章 测试驱动开发(TDD)的原理、实践、关联与争议(Python 版)
驱动开发·python·tdd
IT古董4 小时前
【深度学习】常见模型-Transformer模型
人工智能·深度学习·transformer
摸鱼仙人~6 小时前
Attention Free Transformer (AFT)-2020论文笔记
论文阅读·深度学习·transformer
python算法(魔法师版)6 小时前
深度学习深度解析:从基础到前沿
人工智能·深度学习
小王子10246 小时前
设计模式Python版 组合模式
python·设计模式·组合模式
kakaZhui6 小时前
【llm对话系统】大模型源码分析之 LLaMA 位置编码 RoPE
人工智能·深度学习·chatgpt·aigc·llama
struggle20257 小时前
一个开源 GenBI AI 本地代理(确保本地数据安全),使数据驱动型团队能够与其数据进行互动,生成文本到 SQL、图表、电子表格、报告和 BI
人工智能·深度学习·目标检测·语言模型·自然语言处理·数据挖掘·集成学习