Exercises

These exercises check whether you can make randomized code rerunnable.

Exercise: Fixed seed

What value makes this random sequence repeatable?

rng = np.random.default_rng(42)

Answer it first, then check.

Hint

The seed is the value inside default_rng(...).

Solution

The seed is:

42

It is the value passed to default_rng.

Exercise: Generate repeatable integers

Edit the code so two generators start from seed 5 and the program prints same: True.

Use a fixed generator

Runs locally with Python in your browser.

Ready to run.

Hint

Initialize both generators with:

np.random.default_rng(5)

Keep the same integer range and size for both draws.

Solution

One fix is:

The exercise checks the reproducibility property without depending on the exact numbers produced by a particular generator implementation.

Exercise: Sample without replacement

Which argument prevents repeated items in rng.choice?

Answer it first, then check.

Hint

The argument name is replace.

Solution

Use:

replace=False

This samples without putting selected items back.

Exercise: Shuffle paired arrays

Why should one shuffled index array be used for both X and y?

Choose one

Select one choice, then check.

Hint

If X and y are shuffled independently, examples and labels can stop matching.

Solution

Use one shuffled index array for both arrays so each example stays with its label.

Exercise: Run from configuration

Edit the code so two runs use the configuration seed and print same: True.

Rerun with the same configuration

Runs locally with Python in your browser.

Ready to run.

Hint

Create the generator with:

rng = np.random.default_rng(config.seed)
Solution

One fix is:

Each call creates a generator from the same seed, so the same sequence is used.