Exercises
These exercises check whether you can make randomized code rerunnable.
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.
Edit the code so two generators start from seed 5 and the program prints
same: True.
Use a fixed generator
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.
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.
Why should one shuffled index array be used for both X and y?
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.
Edit the code so two runs use the configuration seed and print same: True.
Rerun with the same configuration
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.