Machine Learning for CybersecuritySource on GitHub

Unit 6 · Exercises

Unit 6 exercises

These exercises use the equations of the three lessons and the labs. Calculations are worked out and were checked in Python. The formulas needed are restated here so each exercise is self-contained.

Exercise 1. Output size and parameters of a convolutional layer

A convolutional layer receives a 64 by 64 input with 3 channels and applies 16 filters of size 5 by 5 with stride 2 and padding 2. Give the spatial size of the output, the number of channels, and the number of trainable parameters.

Show the answer

The spatial size follows from the output-size formula \(H_{\mathrm{out}} = \lfloor (H_{\mathrm{in}} - K + 2P)/S \rfloor + 1\), where \(H_{\mathrm{in}}\) is the input height (or width), \(K\) the filter size, \(P\) the padding added on each side and \(S\) the stride. Here it gives

\[ \begin{aligned} H_{\mathrm{out}} &= \lfloor (64 - 5 + 2 \times 2)/2 \rfloor + 1 \\ &= \lfloor 63/2 \rfloor + 1 = 31 + 1 = 32, \end{aligned} \]

so the output is 32 by 32. The number of output channels equals the number of filters, 16. Each filter has \(3 \times 5 \times 5 = 75\) weights plus one bias, so the layer has \(16 \times (75 + 1) = 1{,}216\) parameters. The parameter count does not depend on the 64 by 64 input size.

Exercise 2. Where the parameters would go in a dense layer

A convolutional layer with 12 filters of size 3 by 3, stride 1 and padding 1 maps a single-channel 100 by 100 input to 12 feature maps of the same size. Suppose you wanted the same outputs from a fully connected layer instead. Compare the parameter counts.

Show the answer

The convolutional layer has \(12 \times (1 \times 3 \times 3 + 1) = 120\) parameters. A fully connected layer mapping the \(100 \times 100 = 10{,}000\) inputs to \(12 \times 100 \times 100 = 120{,}000\) outputs has

\[ \begin{aligned} &10{,}000 \times 120{,}000 + 120{,}000 \\ &\qquad = 1{,}200{,}120{,}000 \end{aligned} \]

parameters, about ten million times as many. This saving comes from the local receptive fields and the weight sharing of Lesson 6.1 (local connections alone would leave \(120{,}000 \times 10 = 1{,}200{,}000\) parameters, and sharing removes the remaining factor of 10,000), and it is why the convolutional feature extractor is cheap while the dense classifier on top holds most of a small network's parameters.

Exercise 3. One step of an LSTM cell

A scalar LSTM cell has previous cell state \(c_{t-1} = 0.4\) and previous output \(h_{t-1} = 0\). At the current step the gate pre-activations are \(1.1\) for the forget gate, \(-0.3\) for the input gate, \(0.5\) for the output gate, and \(0.8\) for the candidate. Using the LSTM relations \(c_t = f_t c_{t-1} + i_t \tilde{c}_t\) and \(h_t = o_t \tanh(c_t)\), with the gates given by the logistic sigmoid of their pre-activations and the candidate by \(\tanh\), compute \(c_t\) and \(h_t\).

Show the answer

The gates are \(f_t = \sigma(1.1) = 0.7503\), \(i_t = \sigma(-0.3) = 0.4256\), \(o_t = \sigma(0.5) = 0.6225\), and the candidate is \(\tilde{c}_t = \tanh(0.8) = 0.6640\). Then

\[ \begin{aligned} c_t &= f_t c_{t-1} + i_t \tilde{c}_t \\ &= 0.7503 \times 0.4 + 0.4256 \times 0.6640 \\ &= 0.3001 + 0.2826 = 0.5827, \end{aligned} \]

and

\[ \begin{aligned} h_t &= o_t \tanh(c_t) \\ &= 0.6225 \times \tanh(0.5827) \\ &= 0.6225 \times 0.5246 = 0.3266. \end{aligned} \]

The forget gate retains three quarters of the old cell state while the input gate admits part of the candidate.

Exercise 4. Vanishing and exploding gradients

In a recurrent network the gradient of a late loss with respect to an early state is a product of per-step factors. Suppose each of 25 steps multiplies the gradient by a factor of magnitude 0.6, and separately consider a factor of 1.2. What are the resulting scales, and what does each imply for learning a dependency spanning those 25 steps?

Show the answer

With factor 0.6, the scale after 25 steps is \(0.6^{25} \approx 2.84 \times 10^{-6}\), so the gradient reaching the early state is about three millionths of its original size and carries almost no training signal, which is the vanishing-gradient case of Bengio et al. (1994). With factor 1.2, the scale is \(1.2^{25} \approx 95.4\), which amplifies the gradient and can destabilize training, the exploding case. Either way plain recurrent networks struggle to learn dependencies across 25 steps, which motivates the additive cell state of the LSTM in Lesson 6.2.

Exercise 5. Q-learning updates propagate reward backward

Use the Q-learning update

\[ \begin{aligned} Q(s, a) &\leftarrow Q(s, a) \\ &\quad + \alpha[r + \gamma \max_{a'} Q(s', a') \\ &\qquad - Q(s, a)] \end{aligned} \]

where \(s\) is the current state, \(a\) the action taken, \(r\) the reward received, \(s'\) the next state, \(a'\) ranges over the actions available in \(s'\), \(\alpha\) is the learning rate and \(\gamma\) the discount factor. Take \(\alpha = 0.3\) and \(\gamma = 0.9\), starting from all action-values at zero. (a) An action reaches the target, a terminal state, with reward 1. What is that action's value after the update? (b) From a predecessor state, the best action leads with reward 0 to the state updated in part (a). What is the predecessor action's value after one update? (c) Instead, an action reaches the monitored host, a terminal state with reward \(-1\). What is its value?

Show the answer

(a) The transition is terminal, so there is no successor term, and \(Q \leftarrow 0 + 0.3(1 - 0) = 0.3\). (b) The successor's best value is now 0.3, so

\[ \begin{aligned} Q &\leftarrow 0 + 0.3(0 + 0.9 \times 0.3 - 0) \\ &= 0.3 \times 0.27 = 0.081. \end{aligned} \]

The reward has propagated one step back, discounted and scaled by the learning rate. (c) The transition is terminal with reward \(-1\), so \(Q \leftarrow 0 + 0.3(-1 - 0) = -0.3\) and the greedy policy will avoid that action. Repeating such updates over many episodes is how the agent in Lab 6c learns the safe route.

Exercise 6. The tie-breaking failure (uses Lab 6c)

In Lab 6c, the agent using a deterministic first-index argmax with zero-initialized values learns nothing, while the random-tie-breaking agent succeeds. Explain precisely why, and give two fixes other than random tie-breaking. Then predict what happens to the first-index agent if you raise the exploration rate epsilon (the probability of taking a uniformly random action instead of the greedy one) from 0.1 to 0.5, and check your prediction by running the lab with that change.

Show the answer

With all action-values equal to zero at the start, the greedy action from a first-index argmax is always the same action (index 0) in every state. At the start host, action 0 targets the start host itself and wastes a step, and from the start host's neighbors it leads straight back. The agent therefore repeats that action except on the epsilon fraction of steps that are random, so it explores very little. With a sparse reward that appears only after at least three moves (four on either safe route), it reaches the target in only a few episodes, too rarely for the reward to propagate back, and the action-values at the start host stay at zero. Two fixes other than random tie-breaking are optimistic initialization, setting all initial action-values above the largest achievable return so every untried action looks attractive and is tried (Sutton and Barto, 2018), and adding a small random perturbation to the initial values to break the symmetry. Raising epsilon to 0.5 gives the first-index agent much more random exploration, so it should begin to reach the reward and learn a usable policy, though at the cost of a lower return during the random steps; running the lab with epsilon 0.5 and the first-index rule confirms that it now learns, unlike at epsilon 0.1.

Exercise 7. What a sequence model adds (design)

A colleague, asked whether the LSTM log detector of Lab 6b could be replaced with a logistic regression, claims this would fail because "a logistic regression cannot use the order of events." Explain why that claim is wrong, describe how you would give a logistic regression access to order, and state what the LSTM actually adds.

Show the answer

The claim is wrong because order can be encoded in features. A logistic regression can be given the identity of the previous one or two events as lag features, counts of each event within a sliding window, or indicators for specific n-grams of events, all of which carry order. What the LSTM adds is the ability to summarize a variable-length history in a learned hidden state and to generalize across histories it did not see exactly, where the logistic regression relies on a fixed, human-chosen set of window or lag features. The right comparison is between a model that learns its own summary of the past and one given a fixed summary, as Lesson 6.2 states. A reasonable experiment is to train a logistic regression next-event model on lag and window-count features, apply the same top-g rule to its predicted probabilities (flag a sequence when any of its events is not among the \(g\) most probable next events), and compare its precision and recall with those of the LSTM at each \(g\). In Lab 6b the workflow is first order, so the count-based n-gram model with its short history is already the correct model there, and its recall is at least as high as the LSTM's at every \(g\). At \(g = 4\), where neither model flags a normal sequence, the n-gram model keeps recall 1.00 while the LSTM's recall falls to 0.95, although at \(g = 2\) and \(g = 3\) the LSTM has the slightly higher precision (0.29 against 0.25 at \(g = 2\)). A fair test of what the LSTM adds needs dependencies that reach further back.

References

  1. Bengio, Y., Simard, P., and Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157-166. https://doi.org/10.1109/72.279181
  2. Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, second edition. http://incompleteideas.net/book/the-book-2nd.html