File size: 2,959 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""CPU translation of Kong's DCASE2016_Task1 / Hat dense network.

Source versions and arithmetic correspondence are documented in ../PORT.md.
"""
import numpy as np

# Output-unit order in the author's config.py, mapped to the task's codes.
CLASS_CODES = np.array([13, 8, 12, 11, 9, 2, 6, 10, 5, 0, 3, 7, 1, 4, 14])


def windows(x):
    if len(x) < 11:
        x = np.concatenate([x, np.zeros((11 - len(x), x.shape[1]), dtype=x.dtype)])
    return np.asarray([x[i:i + 11].reshape(-1)
                       for i in range(0, len(x) - 10, 5)])


def initialize(rng, n_features):
    params = []
    for n_in, n_out in [(11 * n_features, 200), (200, 200), (200, 15)]:
        bound = np.sqrt(6.0 / (n_in + n_out))
        params.extend([rng.uniform(-bound, bound, (n_in, n_out)).astype(np.float32),
                       np.zeros(n_out, dtype=np.float32)])
    return params


def forward(x, params, masks=None):
    activations, inputs = [x], []
    for layer in range(3):
        inp = activations[-1] if masks is None else activations[-1] * masks[layer]
        inputs.append(inp)
        z = inp @ params[2 * layer] + params[2 * layer + 1]
        if layer < 2:
            activations.append(np.maximum(z, 0))
        else:
            z -= z.max(axis=1, keepdims=True)
            z = np.exp(z)
            activations.append(z / z.sum(axis=1, keepdims=True))
    return activations, inputs


def loss_and_grad(x, y, params, masks):
    acts, ins = forward(x, params, masks)
    probs = acts[-1]
    p_true = probs[np.arange(len(y)), y].copy()
    loss = -np.log(np.clip(p_true, 1e-7, 1.0 - 1e-7)).mean()
    delta = probs.copy()
    delta[np.arange(len(y)), y] -= 1
    # Hat clips probabilities before cross entropy; saturated rows have zero gradient.
    delta *= ((p_true >= 1e-7) & (p_true <= 1.0 - 1e-7))[:, None]
    delta /= len(y)
    grads = [None] * 6
    for layer in range(2, -1, -1):
        grads[2 * layer] = ins[layer].T @ delta
        grads[2 * layer + 1] = delta.sum(axis=0)
        if layer:
            delta = (delta @ params[2 * layer].T) * masks[layer]
            delta *= acts[layer] > 0
    return loss, grads


def adam_step(params, grads, moments, velocities, step):
    # Hat's fast Adam: epsilon is outside sqrt(v), before bias correction.
    alpha = 0.001 * np.sqrt(1 - 0.999 ** step) / (1 - 0.9 ** step)
    for p, g, m, v in zip(params, grads, moments, velocities):
        m *= 0.9
        m += 0.1 * g
        v *= 0.999
        v += 0.001 * g * g
        p -= alpha * m / (np.sqrt(v) + 1e-8)


def predict_record(x, params, mean, scale):
    x = windows((x.astype(np.float64) - mean) / scale).astype(np.float32)
    predictions = []
    for i in range(0, len(x), 500):
        acts, _ = forward(x[i:i + 500], params)
        predictions.extend(acts[-1].argmax(axis=1))
    # scipy.stats.mode chooses the smallest AUTHOR class index on ties.
    return CLASS_CODES[np.bincount(predictions, minlength=15).argmax()]