值从类对象返回

2024-05-15 23:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在自学一门贝叶斯a/B测试课程。但是在下面的代码中,它在某些函数中有一个Class对象。对于以下代码:bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]。你知道吗

我知道它将0.20.50.75应用于Bandit类对象,但是语句的输出是什么?它是从函数:def pull(self)def sample(self)执行的,因为它们都在Bandit类中返回一些值。通过理解这一点,我就可以知道这段代码后面的b循环是什么。你知道吗

任何参考链接或文章也很感激。谢谢

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()

Tags: thesample代码inselffordefnp
3条回答

它返回3个具有不同p概率初始化的Bandit类对象。你知道吗

进一步,sample=b.sample(),它将返回np.random.beta测试版(自我a,自我b)

声明

bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]

这叫做列表理解,它基本上是一种创建列表的方法。例如,您可以看到this作为引用(有很多源代码)。你知道吗

其基本思想是使用如下机制:

[ expression for item in list if conditional ]

因此,在您的例子中,BANDIT_PROBABILITIES是上面包含3个元素的列表,您的列表理解评估的表达式只是Bandit类的实例。换句话说,您将得到一个包含Bandit类的3个实例的列表,每个实例都用不同的参数初始化。你知道吗

pull(self)sample(self)只是属于类的函数,它们不在该语句中使用。如果有来自__init__(self, p)成员函数的调用,则可以使用它们。你知道吗

为了简单起见,创建类实例时只使用__init__。如果在后一个函数中有其他对成员函数的调用,比如sample()等,那么它们也会被调用,但是列表理解中的输出仍然是一个有3个Bandit实例的列表。你知道吗

也许您应该检查this answer(以及任何其他的,因为有很多源代码)关于__init__功能的信息。你知道吗

bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]是一个列表理解。BANDIT_PROBABILITIES是一个由3个浮点值组成的列表,因此bandits是一个包含Bandit类的3个对象的列表,这些对象由p属性的3个不同值创建:

print(type(bandit[0]))
print(bandits[0].p)

输出:

<class '__main__.Bandit'>
0.2

到目前为止,只调用了方法__init__()来初始化对象。列表bandits中的每个强盗都有属性p, a, b和方法pull(), sample(), update()。你知道吗

相关问题 更多 >