Python中调整辅助矩阵输出维度的技术问询
调整辅助矩阵输出维度的修改方案
原代码返回的矩阵维度为[out_channels, out_channels],要改为[input_channels, out_channels]且保持核心计算逻辑不变,只需修改最终的返回部分:
修改步骤
- 移除原代码中最后两行的计算(
dot_product_with_hidden_matrix和res的定义) - 直接返回已经计算好的
dot_product_pseudo变量
修改后的代码片段
def my_fun( self, H: torch.FloatTensor,) -> torch.FloatTensor: self.input_channels = 4 self.out_channels = 16 self.forgettingFactor = 0.92 self.lamb = 0.01 self.M = torch.inverse(self.lamb*torch.eye(self.out_channels)) HH = self.calculateHiddenLayerActivation(H) # [4,16] Ht = HH.t() # [16 , 4] ###### Computation of auxiliary matrix initial_product = torch.mm((1 / self.forgettingFactor) * self.M, Ht) # [16, 4] intermediate_matrix = torch.mm(HH, initial_product ) # [4, 4] sum_inside_pseudoinverse = torch.eye(self.input_channels) + intermediate_matrix # [4, 4] pseudoinverse_sum = torch.pinverse(sum_inside_pseudoinverse) # [4, 4] product_inside_expression = torch.mm(HH, (1/self.forgettingFactor) * self.M) # [4, 16] dot_product_pseudo = torch.mm( pseudoinverse_sum , product_inside_expression) # [4, 16] # 直接返回符合目标维度的核心计算结果 return dot_product_pseudo
原理说明
dot_product_pseudo的计算逻辑完全继承了原代码的核心推导:通过伪逆矩阵结合隐藏层激活值HH与正则化矩阵M的乘积,得到的结果维度恰好是[input_channels, out_channels],完全匹配你的需求。原代码后续的计算是基于该中间变量进一步推导out_channels维度的自相关矩阵,截断到dot_product_pseudo返回即可在不改变核心逻辑的前提下得到目标维度的辅助矩阵。
内容的提问来源于stack exchange,提问作者Asif
相关产品推荐
相关产品推荐

