回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在自学一门贝叶斯a/B测试课程。但是在下面的代码中,它在某些函数中有一个Class对象。对于以下代码:<code>bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]</code>。你知道吗</p>
<p>我知道它将<code>0.2</code>、<code>0.5</code>和<code>0.75</code>应用于Bandit类对象,但是语句的输出是什么?它是从函数:<code>def pull(self)</code>或<code>def sample(self)</code>执行的,因为它们都在Bandit类中返回一些值。通过理解这一点,我就可以知道这段代码后面的<code>b</code>循环是什么。你知道吗</p>
<p>任何参考链接或文章也很感激。谢谢</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import beta
NUM_TRIALS = 2000
BANDIT_PROBABILITIES=[0.2,0.5,0.75]
class Bandit(object):
def __init__(self, p): #p=winning
self.p = p
self.a = 1
self.b = 1
def pull(self):
return np.random.random() < self.p
def sample(self):
return np.random.beta(self.a, self.b)
def update(self, x):
self.a =self.a+ x
self.b =self.b+ 1 - x #x is 0 or 1
def plot(bandits, trial):
x = np.linspace(0, 1, 200)
for b in bandits:
y = beta.pdf(x, b.a, b.b)
plt.plot(x, y, label="real p: %.4f" % b.p)
plt.title("Bandit distributions after %s trials" % trial)
plt.legend()
plt.show()
def experiment():
bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]
sample_points = [5,10,20,50,100,200,500,1000,1500,1999]
for i in range(NUM_TRIALS):
# take a sample from each bandit
bestb = None
maxsample = -1
allsamples = [] # let's collect these just to print for debugging
for b in bandits:
sample = b.sample()
allsamples.append("%.4f" % sample)
if sample > maxsample:
maxsample = sample
bestb = b
if i in sample_points:
print("current samples: %s" % allsamples)
plot(bandits, i)
# pull the arm for the bandit with the largest sample
x = bestb.pull()
# update the distribution for the bandit whose arm we just pulled
bestb.update(x)
if __name__ == "__main__":
experiment()
</code></pre>