簡體   English   中英

具有不同概率的矢量化 np.random.choice

[英]Vectorised np.random.choice with varying probabilities

我已經使用 sklearn 訓練了一個機器學習模型,並希望通過根據 predict_proba 概率對預測進行采樣來模擬結果。 所以我想做類似的事情

samples = np.random.choice(a = possible_outcomes, size = (n_data, n_samples), p = probabilities)

Where probabilities would be is an (n_data, n_possible_outcomes) array

但是 np.random.choice 只允許 p 參數使用一維數組。 我目前已經使用如下實現的 for 循環解決了這個問題

sample_outcomes = np.zeros((len(probs), n_samples))
for i in trange(len(probs)):
    sample_outcomes[i, :] = np.random.choice(outcomes, s = n_samples, p=probs[i])

但這相對較慢。 任何加快速度的建議將不勝感激!

如果我正確理解您的問題,以下是您可以做什么的示例:

import numpy as np
#create a list of indices
index_list = np.arange(len(possible_outcomes))
# sample indices based on the probabilities
choice = np.random.choice(a = index_list, size = n_samples, p = probabilities)
# get samples based on randomly chosen indices
samples = possible_outcomes[choice]

如果我理解正確,您需要一種多次應用選擇的矢量化方式,並且每次都使用不同的概率向量。 您可以按如下方式手動實現:

import numpy as np

# for reproducibility
np.random.seed(42)

# number of samples
k = 5

# possible outcomes
outcomes = np.arange(10)

# generate a random probability matrix for 15 runs
probabilities = np.random.random((15, 10))
probs = probabilities / probabilities.sum(1)[:, None]

# generate the choices by picking those probabilities above a random generated number
# the higher the value in probs the higher the probability to pick it
choices = probs - np.random.random((15, 10))

# to pick the top k using argpartition need to multiply by -1
choices = -1 * choices

# pick the top k values
res = outcomes[np.argpartition(choices, k, axis=1)][:, :k]

# flatten to match the expected output
print(res.flatten())

輸出

[1 8 2 5 3 6 4 8 7 0 1 5 9 3 7 1 4 9 0 8 5 0 4 3 6 8 5 1 2 6 5 3 2 0 6 5 4
 2 3 7 7 9 4 6 1 3 6 4 2 1 4 9 3 0 1 6 9 2 3 8 5 4 7 6 1 5 3 8 2 1 1 0 9 7
 4]

在上面的例子中的代碼樣品5( k從圖10(a人口)元素outcomes )15次,每次使用不同的概率向量(時間probs與10的15的形狀)。

我確保我正確理解你的問題。 您可以將samples創建為大小為n_data * n_samples的數組,然后使用 resize 方法將其設置為正確的大小嗎?

samples = np.random.choice(a = possible_outcomes, size = n_data * n_samples, p = probabilities)
samples.resize((n_data, n_samples))

如果您使用 NumPy 的新界面來生成隨機數,那么您想要的應該很簡單: https : //numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html

請參見此處的示例:

samples = np.random.choice(array_of_samps, n_samples, p=probs)

但請注意, len(probs)將等於array_of_samps.shape[0] (即array_of_samps的行數),而不是samples.shape[0] 每行samples將是array_of_samps的隨機選擇行。

從您的sample_outcomes數組的形狀來看, sample_outcomes可能是samples.T

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM