import numpy as np
# 定义k-摇臂赌博机类
class Bandit:
def __init__(self, k):
self.k = k
self.q_star = np.random.normal(0, 1, k) # 真实回报分布
# 选择拉杆并获得奖励
def pull(self, action):
reward = np.random.normal(self.q_star[action], 1)
return reward
# 请在下面的 Begin-End 之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# Softmax算法
def softmax(bandit, temperature, num_steps):
# 第一步:初始化摇臂的偏好值
action_preferences = np.zeros(bandit.k)
# 第二步:初始化累积奖励
rewards = np.zeros(num_steps)
for step in range(num_steps):
# 第三步:计算每个摇臂被选择的概率
action_probs = np.exp(action_preferences / temperature) / np.sum(np.exp(action_preferences / temperature))
# 第四步:根据概率选择一个摇臂进行探索
action = np.random.choice(range(bandit.k), p=action_probs)
# 第五步:选择摇臂并获得奖励
reward = bandit.pull(action)
# 第六步:更新摇臂的偏好值
action_preferences[action] += reward
# 第七步:更新累积奖励
rewards[step] = reward
return rewards
########## End ##########
# 创建一个k-摇臂赌博机实例
bandit = Bandit(k=10)
# 使用Softmax算法进行探索与利用
temperature = 0.65
num_steps = 10
rewards_softmax = softmax(bandit, temperature, num_steps)
K-摇臂赌博机 第3关:Softmax
最新推荐文章于 2025-11-12 14:17:40 发布
4019

被折叠的 条评论
为什么被折叠?



