常用的采樣方法


今天簡單列舉兩個常用的采樣方法:softmax采樣和gamble采樣。

在我們已知數據的概率分布后,想要根據已有的概率值,抽取出適合的數據。此時,就需要特定的采樣函數拿數據。

簡要代碼如下:

"""
    采樣方法
"""
import numpy as np

np.random.seed(1111)    # 隨機種植,固定每次生成相同的數據
logits = (np.random.random(10) - 0.5 ) * 2  # 拉到-1到1

def inv_gumble_cdf(y, mu=0, beta=1, eps=1e-20):
    return mu - beta * np.log(-np.log(y+eps))

def sample_gamble(shape):
    p = np.random.random(shape)
    return inv_gumble_cdf(p)

def softmax(logits):
    max_value = np.max(logits)
    exp = np.exp(logits - max_value)
    exp_sum = np.sum(exp)
    dist = exp / exp_sum
    return dist

def sample_with_softmax(logits, size):
    pros = softmax(logits)
    print(pros)
    return np.random.choice(len(logits), size, p=pros)

def sample_with_gumbel_noise(logits, size):
    noise = sample_gamble((size, len(logits)))
    return np.argmax(logits + noise, axis=1)


print('logits:{}'.format(logits))
pop = 1
softmax_samples = sample_with_softmax(logits, pop)
print('softmax_samples:{}'.format(softmax_samples))
gamble_samples = sample_with_gumbel_noise(logits, pop)
print('gamble_sample:{}'.format(gamble_samples))

返回結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM