"""Chapter 28 starter: the memory-carry measurement and the sign task. Download me next to your notebook and run me (python ch28_starter.py). Section 5 of the chapter uses memory_carry(); the Hands-On uses make_data(). Nothing here is hidden - it is the same code the chapter prints. run() needs tensorflow: see Listing 28.1. """ import numpy as np def memory_carry(u_std, n=16, T=40, seed=0): """Frobenius norm of dh_T/dh_0 for an untrained SimpleRNN cell.""" rng = np.random.default_rng(seed) U = rng.normal(0, u_std, (n, n)) # recurrent weights W = rng.normal(0, 1.0, n) # input weights (1 input feature) b = np.zeros(n) h = np.zeros(n); P = np.eye(n) # P = running Jacobian product for t in range(T): x = rng.uniform(-1, 1) h = np.tanh(U @ h + W * x + b) P = (np.diag(1 - h**2) @ U) @ P # one more step of the chain rule return np.linalg.norm(P) def make_data(n, length, seed): """Sign-memory task: was the first value of the sequence positive?""" rng = np.random.default_rng(seed) X = rng.uniform(-1, 1, size=(n, length, 1)).astype('float32') y = (X[:, 0, 0] > 0).astype('int32') return X, y if __name__ == '__main__': for std in (0.25, 1.0): c = np.array([memory_carry(std, seed=s) for s in range(10)]) print(std, f"geometric mean {np.exp(np.log(c).mean()):.1e}", f"range {c.min():.0e} ... {c.max():.0e}")