首页 > 解决方案 > 有没有一种方法可以通过 numpy 在 tensorflow 框架上制作动态长度矩阵?

问题描述

我想通过使用 TensorFlow 来制作引导注意力损失术语。就我而言,我在 encoder.py 中对其进行编码。在这种情况下,我必须制作动态长度权重矩阵。但在我的代码中,矩阵的形状是张量。所以我知道在运行时间。

引导注意力损失步骤为:

  1. 堆栈注意力对齐
  2. 制作引导损失图(喜欢堆栈注意力对齐形状)
  3. 逐元素两个矩阵并获得平均损失

所以我使用 TensorFlow 和 NumPy 制作了下面的代码。

self.guide_loss = self._make_guide_loss(states=self._video_encoder_final_state,
                            width_length=self._video_inputs_len,
                            height_length=self._audio_inputs_len,
                            _sigma=0.4
                            )

self._video_inputs_len&self._audio_inputs_len是张量

def _make_guide_loss(self, states, width_length, height_length, _sigma=0.4):
        # If, A->V att. layer loss
        # input - states : self._video_encoder_final_state
        #       - data_lengths : self._audio_inputs_len
        #       - sigma : hparameter (default : 0.4), small sigma makes the narrow attention loss map
        attention_map = states.alignment_history.stack()
        loss_weight = tf.sequence_mask(
                lengths=height_length,
                dtype=self._hparams.dtype,
                )
        guide_map = self._guided_attention_map(max_W=tf.reduce_max(width_length),
                batch_size=self._hparams.batch_size[0 if self._mode == 'train' else 1],
                max_H=tf.reduce_max(height_length),
                sigma=_sigma,
                )
        guide_map_tf = tf.convert_to_tensor(guide_map)
        guide_loss = tf.reduce_sum(tf.abs(attention_map * guide_map))
        guide_loss /= tf.reduce_sum(loss_weight)

        return guide_loss

    def _guided_attention_map(self, max_W, batch_size, max_H, sigma=0.4):    
        # dimension of attention_map : [width, batch_size, height]
        W = np.zeros((max_W, batch_size, max_H), dtype=self._hparams.dtype)
        for batch in range(W.shape[1]):
            for w_pos in range(W.shpae[0]):
                for h_pos in range(W.shape[2]):
                    W[w_pos, batch, h_pos] = 1 - np.exp(-(w_pos / float(max_W) - h_pos / float(max_H)) ** 2 / (2 * g * g))
        return W
TypeError: _guided_attention_map() got multiple values for argument 'max_W'

添加self参数后_guide_attention_map(self, max_W...)

TypeError: 'Tensor' object cannot be interpreted as an integer

标签: pythontensorflow

解决方案


推荐阅读