Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Expected Value
An expectation is a weighted average. Each outcome contributes its value, weighted by how likely it is:
Read it out loud as "multiply each outcome by its probability, then add them up". That is all ever means, however intimidating the surrounding notation gets.
It is not the average of the outcomes. A lottery paying £1,000,000 with probability 0.000001 and £0 otherwise has an expected value of £1, not £500,000.
values = [0, 10] probs = [0.9, 0.1] E[X] = 0.9*0 + 0.1*10 = 1.0
Every loss function you will meet is an expectation. "Minimise the expected loss over the data" means exactly this sum, with each training example weighted 1/n.
Your task:
Implement expected_value(values, probs) returning as a float.
Do it with array arithmetic, not a loop.
Example Tests
A 10% chance of 10 and a 90% chance of nothing is worth 1
Input: {"probs":[0.9,0.1],"values":[0,10]}
Expected: 1
A fair die averages 3.5
Input: {"probs":[0.16666666666666666,0.16666666666666666,0.16666666666666666,0.16666666666666666,0.16666666666666666,0.16666666666666666],"values":[1,2,3,4,5,6]}
Expected: 3.5
Negative outcomes pull the expectation below zero
Input: {"probs":[0.75,0.25],"values":[-2,5]}
Expected: -0.25
import numpy as np
def expected_value(values, probs):
"""
Weighted average of values under the distribution probs.
Args:
values: array of outcomes, shape (n,)
probs: array of probabilities, shape (n,), summing to 1
Returns:
float: the expected value
"""
# YOUR CODE HERE
pass