MCPcopy Index your code
hub / github.com/lazyprogrammer/machine_learning_examples / run_experiment

Function run_experiment

rl/ucb1.py:38–77  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

36
37
38def run_experiment():
39 bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]
40 rewards = np.empty(NUM_TRIALS)
41 total_plays = 0
42
43 # initialization: play each bandit once
44 for j in range(len(bandits)):
45 x = bandits[j].pull()
46 total_plays += 1
47 bandits[j].update(x)
48
49 for i in range(NUM_TRIALS):
50 j = np.argmax([ucb(b.p_estimate, total_plays, b.N) for b in bandits])
51 x = bandits[j].pull()
52 total_plays += 1
53 bandits[j].update(x)
54
55 # for the plot
56 rewards[i] = x
57 cumulative_average = np.cumsum(rewards) / (np.arange(NUM_TRIALS) + 1)
58
59 # plot moving average ctr
60 plt.plot(cumulative_average)
61 plt.plot(np.ones(NUM_TRIALS)*np.max(BANDIT_PROBABILITIES))
62 plt.xscale('log')
63 plt.show()
64
65 # plot moving average ctr linear
66 plt.plot(cumulative_average)
67 plt.plot(np.ones(NUM_TRIALS)*np.max(BANDIT_PROBABILITIES))
68 plt.show()
69
70 for b in bandits:
71 print(b.p_estimate)
72
73 print("total reward earned:", rewards.sum())
74 print("overall win rate:", rewards.sum() / NUM_TRIALS)
75 print("num times selected each bandit:", [b.N for b in bandits])
76
77 return cumulative_average
78
79if __name__ == '__main__':
80 run_experiment()

Callers 1

ucb1.pyFile · 0.70

Calls 4

BanditClass · 0.70
ucbFunction · 0.70
pullMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected