BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Probability and statistics4 of 24 in topic

55. 使用逆 CDF 从固定均匀分布中进行类别采样

EasyProbability and statistics
提问于GoogleUber

生产环境中的采样器通常使用固定的随机采样值进行测试。逆 CDF 采样将一个均匀分布的数字转换为一个类别。

编写 categorical_sample(probs, u)。probs 是一个总和为 1 的 1D array,u 是一个在 [0, 1) 范围内的均匀分布 1D array。对于每个 u,返回满足 cumsum(probs)[i] > u 的最小索引 i。返回一个 int array。

函数def categorical_sample(probs, u)

示例 1

输入: categorical_sample([0.2, 0.5, 0.3], [0.1, 0.2, 0.95])

输出: [0, 1, 2]

示例 2

输入: probs = [0.5, 0.5], u = [0.5, 0.0]

输出: [1, 0]

示例 3

输入: probs = [0.3, 0.0, 0.7], u = [0.3, 0.29, 0.31]

输出: [2, 0, 2]

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

The cumulative sum splits [0, 1) into consecutive intervals whose widths are the probabilities, so each u falls into exactly one category's interval.

提示 2

Compute np.cumsum(probs), then for every u find the first position whose cumulative value is strictly greater than u, using a binary search instead of a loop.

提示 3

np.searchsorted(c, u, side="right") returns the first index with c[i] > u. Clamp the result with np.minimum(idx, len(c) - 1) in case floating point makes the last cumsum slightly below 1.

理解思路

逆 CDF 采样将一个均匀分布的随机数转换为一个类别。将概率像尺子上的线段一样,从 0 到 1 首尾相连地排列;采样值 u 正好落在其中一个线段内,该线段的索引即为采样结果。

Worked example

probs = [0.1, 0.6, 0.3],因此累加和为 [0.1, 0.7, 1.0]。u = 0.05 小于 0.1,所以索引为 0。u = 0.1 正好落在边界上;

规则选择满足 cumsum > u 的最小 i,由于 0.1 > 0.1 为假,因此它进入索引 1。u = 0.69 得到 1,u = 0.7 得到 2。对于 [0.05, 0.1, 0.69, 0.7] 的答案是: [0, 1, 1, 2]。
c = probs 的累加和;对于每个 u,返回第一个满足 c > u(严格大于)的索引。通过排序搜索,这是一个 "right side" 插入点。使用大于等于(greater-or-equal)会将边界采样值交给前一个类别,甚至可能选中概率为零的类别。这就是在已知 next-token 概率后 token sampling 的工作方式,而固定采样值使得采样器变得可测试。
主题
Probability and statistics
公司2
  • Google a candidate reported this question Google AI/ML, RAG and agentic AI interview (AI Engineering Insider)
  • Uber the topic appears in interview reports Uber Machine Learning Engineer Interview Process

来自公开面试报告和指南。与这些公司无隶属关系或背书关系。

相似题目
  • 单次遍历追踪流的均值和方差Easy
  • 计算两个对角高斯分布之间的 KL divergenceEasy
  • 使用 Jensen-Shannon divergence 比较两个 token 分布Easy
  • 计算离散随机变量及其 aX + b 的均值和方差Easy
所有 Probability and statistics 道题目
反馈
55 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def categorical_sample(probs, u):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS