2017-01-15 61 views
-2

我運行以下代碼,其中函數weighted_values返回具有指定概率的隨機值序列。我使用這個功能,從這個答案Generating discrete random variables with weights索引錯誤:索引3超出大小爲3的軸1的邊界

以下是我的代碼:

def weighted_values(values, probabilities, size): 
    bins = np.add.accumulate(probabilities) 
    return np.array(values[np.digitize(random_sample(size), bins)]) 

def weak_softmax(a): 
    b=np.exp(a) 
    return b/(1+sum(b)) 


elements=np.array([1,2,3]) 
prob=np.array([0.2,0.5,0.3]) 


system_index=0; 
T=10;M=2; 

for t in np.arange(T): 

    prob=weak_softmax(np.random.uniform(0,1,M+1)); 

    system_index=weighted_values(np.arange(M+1),prob,1)[0] 

print(system_index) 

然而,當我運行此代碼,有時我得到這個錯誤

Traceback (most recent call last): 
File "gradient_checking.py", line 75, in <module> 
    system_index=weighted_values(np.arange(M+1),prob,1)[0] 
File "gradient_checking.py", line 57, in weighted_values 
    return np.array(values[np.digitize(random_sample(size), bins)]) 
IndexError: index 3 is out of bounds for axis 1 with size 3 

任何人都可以提出什麼我做錯了,如何修改它?

+1

你可以發佈你的整個代碼以及完整的錯誤和它被拋出的行嗎?什麼是'random_sample(...)'在做什麼? –

+0

@Shiva:random_sample顯然會產生介於0和1之間的統一隨機數,正如前面答案的鏈接所述。 – pikachuchameleon

回答

1

錯誤告訴我,你有形狀(n,3)(軸1個大小3)一個數組,而你試圖索引它與3

In [9]: np.ones((5,3))[:,3] 
... 
IndexError: index 3 is out of bounds for axis 1 with size 3 

問題陳述:

values[np.digitize(random_sample(size), bins)] 

我建議檢查values的形狀。它的外觀看起來像是np.arange(M+1),其中M是2.這是尺碼3,但1d。

另外np.digitize(random_sample(size), bins)產生了什麼?

當你有這樣的錯誤時,你需要檢查可疑陣列的形狀,並檢查指數值的範圍。我們只能從閱讀你的代碼中猜出這麼多。

+0

在這個np.ones((5,3))[:,3]中,行是5,列是3,所以爲什麼doesnt [:,3]打印最後一列? –

相關問題