KWIK 算法來自論文 Knows What It Knows: A Framework For Self-Aware Learning
下面實作其中的 Algorithm 2: The enumeration algorithm
首先問題中列出所有的可能組合情況,然後就是要周遊每個情況
用 votes 來存儲每個組合情況的投票結果
周遊 H 中的每個 h
h 的第一個位置當作 instigator的,第二個位置是 peacemaker的
patrons 就是一輪的出席資料,例如 0 0 0 1
是以就是 patrons 是固定的一個,按照 H 中的 12 個下标組合情況一個一個去試驗,每個組合就是假定這就是真正的下标了,然後給出fight的結果
def pred_or_learn(patrons, num_patrons, H, fight):
# corner case:if all patrons present, no fight will occur for sure
if sum(patrons) == num_patrons:
return (H, 0)
# 用來存儲每個組合情況的投票結果
votes = []
# 周遊 H 中的每個 h
for h in H:
instigator_ind, peacemaker_ind = h[0], h[1] # 【h 的第一個位置當作 instigator的,第二個位置是 peacemaker的】
instigator_presence = (patrons[instigator_ind] == 1) # 【patrons 就是一輪的出席資料,例如 0 0 0 1】
peacemaker_presence = (patrons[peacemaker_ind] == 1) # 【是以就是 patrons 是固定的一個,按照 H 中的 12 個下标組合情況一個一個去試驗,每個組合就是假定這就是真正的下标了,然後給出fight的結果】
# fight 産生的條件
if (instigator_presence and not peacemaker_presence):
votes.append(1)
else:
votes.append(0)
if (sum(votes) == len(votes) or sum(votes) == 0):
return (H, votes[0])
else:
remove_indices = [i for i, x in enumerate(votes) if x == (1-fight)]
for ind in sorted(remove_indices, reverse=True):
del H[ind]
return (H, -1)
複制