python - 有没有一种方法可以通过 numpy 在 tensorflow 框架上制作动态长度矩阵?
问题描述
我想通过使用 TensorFlow 来制作引导注意力损失术语。就我而言,我在 encoder.py 中对其进行编码。在这种情况下,我必须制作动态长度权重矩阵。但在我的代码中,矩阵的形状是张量。所以我知道在运行时间。
引导注意力损失步骤为:
- 堆栈注意力对齐
- 制作引导损失图(喜欢堆栈注意力对齐形状)
- 逐元素两个矩阵并获得平均损失
所以我使用 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
解决方案
推荐阅读
- java - 切换日/夜模式时如何为组件(工具栏、搜索栏、操作栏等)设置自定义颜色?
- nhibernate - 在字符串属性上搜索不等式
- reactjs - 如何使用 springboot 和 reactjs 正确配置 websocket?
- sql - SQL - 如何在一年中的每个日期按年龄和状态对项目进行分组/计数?
- android - 每次退出应用程序后,用户都会重复相同的通知
- javascript - 如何使用 6 位时间戳进行 hh:mm:ss 倒计时?
- azure - 如何从我自己的自定义域向 b2clogin 域发送 Web 请求?
- c++ - c ++分段错误打印无符号字符
- php - 使用 php 将种子点随机分配给 128 个团队
- python-3.x - 同一个嵌入中的多个结果 | 不和谐.py