Choose random inputsLesson 07 of 76 · 6 min
Sample weighted alternatives
Generate categorical choices with explicit probabilities.
Some inputs are categories rather than continuous measurements. A visitor might choose a standard, vegetarian or premium meal. Represent the categories and their probabilities together so their meaning stays inspectable. Mutually exclusive means one visitor cannot belong to two meal categories here; we also assume every visitor chooses one.
The probabilities must be nonnegative and sum to one. NumPy choice samples from the alternatives using those weights. The sample frequencies will fluctuate around the stated probabilities; they are not required to reproduce them exactly in one batch. Relative weights are different: [5,3,2] become [.5,.3,.2] by dividing by their total 10, but only if they really mean relative frequencies.
A category can select another calculation, such as ingredient cost. Averaging those costs estimates the expected cost under the assumed mix. This preserves the distinction between a category label and the numerical outcome it produces.
Will a sample of ten meals necessarily contain exactly three vegetarian meals if their probability is 0.3?
Write a prediction (optional)
Seeded teaching simulation
Select Run Python below with the code unchanged.
A saved draft is open. To run the published example, open Tools and select Restore example. Recover draft brings your code back.
Execution error
Technical error details
Your result
Published example output
This result comes from the original Python. Your runs appear above. Build environment ↗
{np.str_('standard'): np.float64(0.5014), np.str_('vegetarian'): np.float64(0.3042), np.str_('premium'): np.float64(0.1944)}
Estimated mean ingredient cost (£): 7.473
Read the first result
The first line gives the sampled fraction for each named meal. Compare those fractions with the weights in probabilities. The next line averages ingredient costs using the mapping in costs.
Try an edit
Replace [.5, .3, .2] with [.4, .3, .3]. Select Run Python again. Compare the printed standard and premium sample fractions and Estimated mean ingredient cost (£). What happens when the same probability is moved from standard to the more expensive premium option?
Scope. The mix and prices are invented. Sampling a category does not establish that actual visitors follow these weights.
Try a fresh case
Your category weights sum to 1.2. What should happen before simulation?
Need a hint?
Hint 1
Ask whether the alternatives are mutually exclusive.
Hint 2
Separate probabilities from arbitrary relative weights.