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]])
**************************************************
相关推荐
aminghhhh5 分钟前
多模态融合【十九】——MRFS: Mutually Reinforcing Image Fusion and Segmentation
人工智能·深度学习·学习·计算机视觉·多模态
陈苏同学36 分钟前
MPC控制器从入门到进阶(小车动态避障变道仿真 - Python)
人工智能·python·机器学习·数学建模·机器人·自动驾驶
mahuifa39 分钟前
python实现usb热插拔检测(linux)
linux·服务器·python
努力毕业的小土博^_^1 小时前
【深度学习|学习笔记】 Generalized additive model广义可加模型(GAM)详解,附代码
人工智能·笔记·深度学习·神经网络·学习
MyhEhud1 小时前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
狐凄1 小时前
Python实例题:pygame开发打飞机游戏
python·游戏·pygame
天上路人1 小时前
采用AI神经网络降噪算法的语言降噪消回音处理芯片NR2049-P
深度学习·神经网络·算法·硬件架构·音视频·实时音视频·可用性测试
漫谈网络1 小时前
Telnet 类图解析
python·自动化·netdevops·telnetlib·网络自动化运维
农夫山泉2号3 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI4 小时前
Flask Docker Demo 项目指南
python·docker·flask