KatInterview

Horvitz-Thompson Event Rate from Weighted Inspection Records

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashinginverse-probability-weightingsamplingestimation

Last updated

Estimate a population-wide event rate from samples drawn with known unequal inclusion probabilities, using inverse-probability weighting divided by the population size.

Horvitz-Thompson Event Rate from Weighted Inspection Records

A population contains population_size units. Only some of them were inspected, and each inspected unit had a known probability of being picked for inspection. You are given one record for every inspected unit, and each record says whether the event of interest occurred for that unit.

Implement a function that estimates the event rate of the whole population, meaning the expected fraction of all units in which the event occurs.

Input

  • population_size: an integer, the total number of units in the population (inspected or not).
  • sampled_records: a list of records, one per inspected unit. Each record is a two-element list [inclusion_probability, event]:
    • inclusion_probability: the probability that this unit was selected for inspection, with 0 < inclusion_probability <= 1.
    • event: 1 if the event occurred for this unit, 0 otherwise.

Task

Use inverse-probability weighting. Each inspected unit stands in for 1 / inclusion_probability units of the population. Estimate the total number of events in the population as the sum of event / inclusion_probability over all inspected records. The estimated rate is that total divided by population_size (a known denominator).

Edge cases

  • If population_size <= 0, return 0.0.
  • If sampled_records is empty, return 0.0.

Return the estimate as a float.

Constraints

  • population_size is an integer.
  • Every inclusion_probability is in (0, 1].
  • Every event is 0 or 1.
  • The denominator is the known population size, not the number of inspected records and not a sum of weights.
  • Results are compared to the expected values with ordinary floating-point tolerance.

Examples

Example 1

Input: population_event_rate(1000, [[1, 1], [1, 0], [0.1, 1], [0.1, 0], [0.1, 1]])

Output: 0.021

Example 2

Input: population_event_rate(100, [[1, 1], [1, 0], [0.25, 1], [0.25, 0]])

Output: 0.05

Example 3

Input: population_event_rate(500, [[1, 1], [0.5, 1], [0.5, 0], [0.2, 1]])

Output: 0.016

Hints

Hint 1

Think about how many population units each inspected unit represents when its chance of being picked was p.

Hint 2

A unit with an event contributes 1/p to the estimated number of events; a unit without an event contributes nothing.

Hint 3

Divide the weighted event total by the known population size, not by the number of sampled records, and handle the empty or non-positive cases first.