#!/usr/bin/env python3
# Source: q3-deep-learning.html
import numpy as np

def dropout(h, p, training):
    if not 0 <= p < 1:
        raise ValueError("Drop probability must satisfy 0 <= p < 1")
    if not training or p == 0:
        return h
    mask = (np.random.rand(*h.shape) > p) / (1 - p)   # keep with prob 1-p, rescale
    return h * mask                                   # reuse mask in backward
