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.

A probability is a width of the choice space
Standard · 0.5Vegetarian · 0.3Premium · 0.2
Standard · 0.5Vegetarian · 0.3Premium · 0.2
Reference illustration. The authored categorical input weights are 0.5, 0.3 and 0.2. These are model probabilities, not the finite simulated frequencies. A separate mapping assigns a cost to each selected category.

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.

Tools
About Python ↗

The code is editable. Press Ctrl+Enter or ⌘+Enter to run Python from the editor.

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?

Back to the Python editor

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?

Choose an answer
Need a hint?
Hint 1

Ask whether the alternatives are mutually exclusive.

Hint 2

Separate probabilities from arbitrary relative weights.

Your notes