utils.py 1.5 KB
Newer Older
L
lifuchen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
L
lifuchen 已提交
14 15
import numpy as np

L
lifuchen 已提交
16

L
lifuchen 已提交
17
def get_alignment(attn_probs, mel_lens, n_head):
L
lifuchen 已提交
18 19 20 21 22 23
    max_F = 0
    assert attn_probs[0].shape[0] % n_head == 0
    batch_size = int(attn_probs[0].shape[0] // n_head)
    for i in range(len(attn_probs)):
        multi_attn = attn_probs[i].numpy()
        for j in range(n_head):
L
lifuchen 已提交
24
            attn = multi_attn[j * batch_size:(j + 1) * batch_size]
L
lifuchen 已提交
25 26 27 28
            F = score_F(attn)
            if max_F < F:
                max_F = F
                max_attn = attn
L
lifuchen 已提交
29
    alignment = compute_duration(max_attn, mel_lens)
30
    return alignment, max_attn
L
lifuchen 已提交
31 32


L
lifuchen 已提交
33 34 35 36 37
def score_F(attn):
    max = np.max(attn, axis=-1)
    mean = np.mean(max)
    return mean

L
lifuchen 已提交
38

L
lifuchen 已提交
39
def compute_duration(attn, mel_lens):
L
lifuchen 已提交
40
    alignment = np.zeros([attn.shape[0], attn.shape[2]])
L
lifuchen 已提交
41
    mel_lens = mel_lens.numpy()
L
lifuchen 已提交
42
    for i in range(attn.shape[0]):
L
lifuchen 已提交
43
        for j in range(mel_lens[i]):
L
lifuchen 已提交
44 45
            max_index = np.argmax(attn[i, j])
            alignment[i, max_index] += 1
L
lifuchen 已提交
46 47

    return alignment