常用的采样方法

今天简单列举两个常用的采样方法: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))
复制代码

返回结果:

 

posted @   今夜无风  阅读(1404)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示