2017-05-22 47 views
0

我正在嘗試爲自定義RL算法創建一個隨機環境,該代碼的陰影需要一個有序的字典(例如:OrderedDict([(0,1),(1,0) ,(2,0),(3,0)])元組中的第一個數是indx,其次是概率),並按照有序字典中定義的狀態出現的概率隨機返回新狀態(在上例中有它進入狀態0)選擇按概率加權的隨機狀態

我有問題是由於某種原因,當INDX是0爲上述示例輸入100%的機率,機率也爲0。我期望概率爲1

在這種情況下,pcloud [0] == 1這就是我想要的。這意味着我在枚舉的使用中存在一些錯誤,但我不知道它是什麼。

def collapse(pcloud): 
     randomnum = Random.uniform(0,1) 
     threshold = 0 

     for indx , probability in enumerate(pcloud): 
      threshold += probability 
      if randomnum <= threshold:      
       return indx 
     raise ValueError("For some reason the probabilities can't be compared with the <= operator.") 
     #it should never get here. 
     return 

運行代碼創建一個有序的字典。

from collections import OrderedDict 
import random as Random 
#all probabilities should sum to 1 
pcloud = OrderedDict() 
pcloud[0] = 1 
pcloud[1] = 0 
pcloud[2] = 0 
pcloud[3] = 0 

#then run the function 
print collapse(pcloud) 
+1

是'pcloud'了' OrderedDict'?你爲什麼「列舉」它? – user2357112

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在發佈您的MCVE代碼並準確描述問題之前,我們無法爲您提供有效的幫助。 我們應該能夠將發佈的代碼粘貼到文本文件中,並重現您描述的問題。 – Prune

+0

是的。此外,我列舉,因爲我需要一種方法來提取索引和索引可能並不總是一個數字。 –

回答

0

只因爲涉及指數,您不應該使用enumerate。這些指數已經作爲OrderedDict的關鍵字出現了。你需要通過你的OrderedDict的鍵值對迭代,所以你應該對Python的2遍歷其items(),或iteritems()(因爲items()建立在Python 2中不必要的列表):

for index, probability in pcloud.items(): 
    ... 
+0

這工作!謝謝。 –