├── .gitignore ├── images ├── density.png ├── impsam_light.jpg ├── impsam_pdf.png ├── integrate_fx.png ├── impsam_example.png ├── impsam_rabbit.jpg ├── impsam_uniform.png ├── integrate_fx2.png ├── impsam_stormtrooper.png ├── impsam_divided_by_self.png └── impsam_stormtrooper2.png ├── README.md ├── inverse-transform-sampling.ipynb ├── monte-carlo-method.ipynb └── importance-sampling.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | # Project 2 | .ipynb_checkpoints 3 | 4 | # Python 5 | *.pyc 6 | 7 | -------------------------------------------------------------------------------- /images/density.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/density.png -------------------------------------------------------------------------------- /images/impsam_light.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_light.jpg -------------------------------------------------------------------------------- /images/impsam_pdf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_pdf.png -------------------------------------------------------------------------------- /images/integrate_fx.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/integrate_fx.png -------------------------------------------------------------------------------- /images/impsam_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_example.png -------------------------------------------------------------------------------- /images/impsam_rabbit.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_rabbit.jpg -------------------------------------------------------------------------------- /images/impsam_uniform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_uniform.png -------------------------------------------------------------------------------- /images/integrate_fx2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/integrate_fx2.png -------------------------------------------------------------------------------- /images/impsam_stormtrooper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_stormtrooper.png -------------------------------------------------------------------------------- /images/impsam_divided_by_self.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_divided_by_self.png -------------------------------------------------------------------------------- /images/impsam_stormtrooper2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndersonJo/monte-carlo-integration/master/images/impsam_stormtrooper2.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # monte-carlo-integration 2 | Monte Carlo Integration 3 | 4 | The repository explains Monte Carlo Integration including Importance Sampling. 5 | 6 | 1. [Monte Carlo Integration](https://github.com/AndersonJo/monte-carlo-integration/blob/master/monte-carlo-method.ipynb) 7 | 2. [Importance Sampling](https://github.com/AndersonJo/monte-carlo-integration/blob/master/importance-sampling.ipynb) 8 | -------------------------------------------------------------------------------- /inverse-transform-sampling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Inverse Transform Sampling\n", 8 | "\n", 9 | "![Storm Trooper](images/impsam_stormtrooper.png)\n", 10 | "\n", 11 | "예를 들어서 게임을 개발하고 있다고 가정합니다.
\n", 12 | "게임의 재미를 위해서 게임속 스톰 트루퍼의 능력을 10%는 강하게, 20%는 약하게, 나머지 70%는 평균적 능력으로 설정을 합니다.
\n", 13 | "\n", 14 | "$$ \\text{Probability} = \\{ \\text{Weak}: 0.2, \\text{Standard}: 0.7, \\text{Strong}: 0.2\\} $$\n", 15 | "\n", 16 | "$$ \\begin{align}\n", 17 | "\\text{CDF} = \\{& P[Ability = Weak] = 0.2, \\\\\n", 18 | "& P[Ability = Weak or Standard] = 0.9, \\\\\n", 19 | "& P[Ability = Weak or Standard or Strong] = 1 \\} \n", 20 | "\\end{align} $$\n", 21 | "\n", 22 | "![Storm Trooper2](images/impsam_stormtrooper2.png)\n", 23 | "\n", 24 | "\n", 25 | "위의 distribution을 simulate하는 방법으로 가장 쉬운 방법은 pre-allocate하는 방법입니다.
\n", 26 | "즉 10명의 스톰트루퍼가 있다면, 2명은 약하게, 1명은 강하게, 나머지는 기본설정으로 미리 설정을 합니다.
\n", 27 | "문제는 이렇게 하면 게임이 너무 예측가능해지며, 실제 inverse sampling을 구현할때 샘플들의 갯수를 모르는 경우가 많습니다.\n", 28 | "\n", 29 | "\n", 30 | "**포인트는 현재 CDF를 알고있고, CDF를 갖고서 원하는 알고리즘을 replicate하는 것입니다.**
\n", 31 | "방법은 매우 간단합니다.\n", 32 | "\n", 33 | "1. 0~1사이의 random value를 uniform distribution으로 생성합니다.\n", 34 | "2. 생성한 random value의 값이...\n", 35 | " - 0.2 이하: 약한놈을 생성\n", 36 | " - 0.2 이상 0.9 이하 : 평범한 좀 생성\n", 37 | " - 0.9 이상 1.0 이하 : 쌘놈 생성 " 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [] 46 | } 47 | ], 48 | "metadata": { 49 | "kernelspec": { 50 | "display_name": "Python 3", 51 | "language": "python", 52 | "name": "python3" 53 | }, 54 | "language_info": { 55 | "codemirror_mode": { 56 | "name": "ipython", 57 | "version": 3 58 | }, 59 | "file_extension": ".py", 60 | "mimetype": "text/x-python", 61 | "name": "python", 62 | "nbconvert_exporter": "python", 63 | "pygments_lexer": "ipython3", 64 | "version": "3.6.1" 65 | } 66 | }, 67 | "nbformat": 4, 68 | "nbformat_minor": 2 69 | } 70 | -------------------------------------------------------------------------------- /monte-carlo-method.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# [Note] Prerequisites \n", 8 | "\n", 9 | "### Expected Value of D0iscrete Random Variable\n", 10 | "\n", 11 | "Discrete random variable $ X $ 를 $ f $ 확률의 함수로 $ S $ 에서 어떤 값을 꺼낸다면 $ E(X) $ (expected valud of $ X $ 라고 함) 는 다음과 같습니다.\n", 12 | "\n", 13 | "$$ E(X) = \\sum_{i = 1} x_i p_i $$\n", 14 | "\n", 15 | "* $ X $ : Discrete random variable \n", 16 | "* $ p_i $ : 각각의 random variable $ x_i $ 의 확률이며, 위키피디아에서는 $ f(x) $ 를 사용하여 probability density function으로 표현하기도 한다.\n", 17 | "* $ E(X) $ : weighted avarage of the values $ X $ \n", 18 | "\n", 19 | "### Expected Value of Continuous Random Variable\n", 20 | "\n", 21 | "Continuous random variable $ Y = f(X) $ 에 대한 expected value는 다음과 같습니다.\n", 22 | "\n", 23 | "$$ \\int f(x)\\ pdf(x)\\ dx $$\n", 24 | "\n", 25 | "**Example.** 예를 들어서 주사위를 굴렸을때의 expected value의 값은 다음과 같습니다.\n", 26 | "\n", 27 | "$$ \\begin{align}\n", 28 | "E(X) &= 1*P(x=1) + 2*P(x=2) + 3*P(x=3) + 4*P(x=4) + 5*P(x=5) + 6*P(x=6) \\\\\n", 29 | "&= 1 * \\frac{1}{6} + 2 * \\frac{1}{6} + 3 * \\frac{1}{6} + 4 * \\frac{1}{6} + 5 * \\frac{1}{6} + 6 * \\frac{1}{6} \\\\\n", 30 | "&= 3.5\n", 31 | "\\end{align} $$\n", 32 | "\n", 33 | "따라서 expected value $ E(X) $ 는 3.5 입니다." 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "### Expected Value Rules\n", 41 | "\n", 42 | "* Random variables 합의 expected value 는 expected values의 합과 동일합니다.\n", 43 | "\n", 44 | "$$ E\\left[ \\sum_{i} Y_i \\right] = \\sum_{i} E[Y_i] $$\n", 45 | "\n", 46 | "* 상수는 다음과 같이 처리 할수 있습니다. (a, b는 상수)\n", 47 | "\n", 48 | "$$ E[aX + b] = aE[X] + b $$\n", 49 | "\n", 50 | "$$ E[aY] = aE[Y] $$" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "### Variance\n", 58 | "\n", 59 | "$$ \\begin{align} \n", 60 | "\\sigma^2[X] &= E[ (X - E[X])^2] \\\\\n", 61 | "&= E[X^2] - E[X]^2\n", 62 | "\\end{align} $$\n", 63 | "\n", 64 | "상수는 다음과 같이 빠질수 있습니다.\n", 65 | "\n", 66 | "$$ E[aY] = aE[Y] $$\n", 67 | "\n", 68 | "$$ \\sigma^2[aY] = a^2 \\sigma^2[Y] $$\n", 69 | "\n", 70 | "또한 random variables이 [uncorrelated](https://en.wikipedia.org/wiki/Uncorrelated_random_variables)이라면 summation은 variance를 갖고 있을수 있습니다.\n", 71 | "\n", 72 | "$$ \\sigma^2 \\left[ \\sum_i Y_i \\right] = \\sum_i \\sigma^2 [Y_i] $$" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "### The Law of Large Numbers\n", 80 | "\n", 81 | "* **The Law of Large Numbers** : Sample size 가 증가할수록 population의 평균값에 가까워진다는 뜻으로.. 예를 들어서 동전 던지기를 대략 1,000,000번 던지면 앞면 뒷면이 나올 확률이 1:1로 거의 유사하게 나올 것 입니다. 하지만 10번정도밖에 안 던지면 1:1이 아닌 3:7 또는 2:8처럼 모수와 전혀 다른 비율로 나올 것 입니다.\n", 82 | "\n", 83 | "* 즉.. 여러번의 experiments (또는 trials) 를 거치고 난뒤의 평균값은 **expected value** 와 점점 가까워지게 될 것입니다. " 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "# Basic Monte Carlo Method\n", 91 | "\n", 92 | "## Intuition\n", 93 | "\n", 94 | "One-dimensional function $ f(x) $ 를 a부터 b까지 integrate한다고 basic Monte Carlo integration은 다음과 같습니다.\n", 95 | "\n", 96 | "$$ F = \\int^b_a f(x)\\ dx $$\n", 97 | "\n", 98 | "잘 알다시피, Integration은 함수의 curve아래의 면적을 구합니다. (Fgure 1)
\n", 99 | "만약 random value x 를 하나 선택한뒤 $ f(x) * (b-a) $ 를 하게 되면 Figure 2 처럼 직사각형 형태를 면적으로 구하게 됩니다.
\n", 100 | "\n", 101 | "![one-dimensional-function](images/integrate_fx.png)\n", 102 | "\n", 103 | "적당한 값을 찾아서 직사각형의 넓이를 구한다면 조잡하지만 curve아래의 정확한 면적을 approximate할수 있게 됩니다.
\n", 104 | "하지만 만약 $ x_1 $ 을 선택하게 된다면 면적을 너무 좁게 볼 것이고, $ x_2 $ 로 잡으면 면적을 너무 크게 잡게 될 것입니다.
\n", 105 | "\n", 106 | "![one-dimensional-function](images/integrate_fx2.png)\n", 107 | "\n", 108 | "한번에 정확한 면적을 구할수는 없지만, 여러번의 random points를 잡아서 계속해서 직사각형의 면적을 구하고, 평균을 구하면 실제 curve아래의 면적과 유사해질것입니다. 포인트는 samples의 갯수가 늘어날수록 좀 더 정확한 approximation 을 할 수 있게 됩니다.\n" 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": {}, 114 | "source": [ 115 | "## Basic Monte Carlo\n", 116 | "\n", 117 | "위의 아이디어처럼 samples (직사각형)의 갯수가 늘어나면 날수록 integral 결과값에 approximate한다는 것을 수식화하면 다음과 같습니다.\n", 118 | "\n", 119 | "$$ \\langle F^N \\rangle = (b-a) \\frac{1}{N} \\sum^{N-1}_{i=0} f(X_i) $$\n", 120 | "\n", 121 | "* $ N $ : Sample의 갯수\n", 122 | "* $ f(X_i) $ : 위의 예제에서 직사각형의 높이\n", 123 | "* $ b-a $ : 위의 예제에서 직사각형의 가로길이\n", 124 | "* $ \\frac{1}{N} \\sum^{N}_{i=1} f(X_i) $ : 즉 y값의 평균을 sample로 부터 구해서 $ (b-a) $와 곱하게 되면 curve아래의 면적을 approximate할 수 있게 된다.\n", 125 | "* $ \\langle S \\rangle $ : [위키피디아](https://en.wikipedia.org/wiki/List_of_mathematical_symbols) 에 따르면 S안의 subgroup의 평균값을 가르킵니다. $ \\langle F^N \\rangle $ 는 즉 N개의 samples들의 평균값을 뜻하며 $ \\bar{X}_n $ 같은 notation과 같은 의미입니다.\n", 126 | "* **Random point**: a와 b사이의 random point는 0~1사이의 random값을 numpy로 뽑고 그 랜덤값을 (a-b) 에 곱하면 됩니다. \n", 127 | " \n", 128 | "* **Uniformly Distributed Random Value**
\n", 129 | "$$ x_i = U(b-a) $$ \n", 130 | " $ U $ 는 uniformly distributed 라는 뜻으로, $ b-a $ 의 값중에서 모두 동일한 확률로 sampling하겠다는 뜻\n", 131 | "\n", 132 | "* **PDF** : Probability Density Function의 경우 동일한 확률(equiprobability)로 뽑혔기 때문에 $ \\frac{1}{b-a} $ 이다.
\n", 133 | "만약 discrete 데이터이라면 $ \\frac{1}{\\text{total number of outcomes}} $ 하면되나, 여기에서는 continuous 데이터이기 때문에 1에다 interval [a, b] 를 나누게 된다.\n", 134 | "\n", 135 | "### 증명 \n", 136 | "\n", 137 | "The law of large number에 따르면, sample들의 평균 $ \\langle F^N \\rangle $ 은 sample 의 갯수 $ N $ 이 많아질수록 실제 curve 아래의 면적 F 와 동일진다고 봅니다.
\n", 138 | "아래 공식에서 확률은 1이라는 뜻은 \"맞다\" 라는 뜻으로 보면 됩니다.\n", 139 | "\n", 140 | "\n", 141 | "$$ Pr \\left(\\lim_{N \\to \\infty} \\langle F^N \\rangle = F \\right) = 1 $$\n", 142 | "\n", 143 | "이때 $ \\langle F^N \\rangle $ 은 random variable 이며, 증명은 다음과 같습니다.\n", 144 | "\n", 145 | "$$ \\begin{align} \n", 146 | "E[ \\langle F^N \\rangle ] &= E \\left[ (b-a) \\frac{1}{N} \\sum^{N-1}_{i=0} f(x_i) \\right] & [1] \\\\\n", 147 | "&= (b-a) \\frac{1}{N} \\sum^{N-1}_{i=0} E[f(x_i)] & [2] \\\\\n", 148 | "&= (b-a) \\frac{1}{N} \\sum^{N-1}_{i=0} \\int^b_a f(x) pdf(x)\\ dx & [3] \\\\\n", 149 | "&= \\frac{1}{N} \\sum^{N}_{i=1} \\int^b_a f(x)\\ dx & [4] \\\\\n", 150 | "&= \\int^b_a f(x)\\ dx & [5] \\\\\n", 151 | "&= F & [6]\n", 152 | "\\end{align} $$\n", 153 | "\n", 154 | "* [1] : basic monte carlo를 적용하며, 해당 공식은 uniform distribution에만 적용될 수 있다.\n", 155 | "* [2] : expectation은 상수를 밖으로 뺄수 있으며, summation 안쪽으로 들어올수 있다.\n", 156 | "* [3] : continuous random variable에 대한 expectation으로 바꿔준다.\n", 157 | "* [4] : pdf는 continuous data이기 때문에 $ \\frac{1}{b-a} $ 이며, 이는 앞쪽의 $ (b-a) $ 를 상쇄시킨다.
summation은 $ \\sum^{N-1}_{i=0} = \\sum^{N}_{i=1} $ 이다.\n", 158 | "* [5] : $ \\sum^N_{i=1} I $ 가 있다면 $ N * I $ 와 같게 된다.\n", 159 | "\n" 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "## Multidimensional Integration\n", 167 | "\n", 168 | "위의 Basic Monte Carlo의 경우 PDF가 오직 uniform일때만 가능합니다.
\n", 169 | "만약 random variable $ X $ 의 arbitrary PDF라면, 다음과 같이 공식화 할 수 있습니다.
\n", 170 | "위에거는 외울 필요가 없지만, 아래것은 외워야 합니다.\n", 171 | "\n", 172 | "$$ \\langle F^N \\rangle = \\frac{1}{N} \\sum^{N-1}_{i=0} \\frac{f(x_i)}{pdf(x_i)} $$\n", 173 | "\n", 174 | "\n", 175 | "위의 generalized estimator는 다음과 같은 expected value를 갖습니다.\n", 176 | "\n", 177 | "$$ \\begin{align} \n", 178 | "E[\\langle F^N \\rangle] &= E \\left[ \\frac{1}{N} \\sum^{N-1}_{i=0} \\frac{f(X_i)}{pdf(X_i)} \\right] &[1] \\\\\n", 179 | "&= \\frac{1}{N} \\sum^{N-1}_{i=0} E \\left[ \\frac{f(X_i)}{pdf(X_i)} \\right] &[2] \\\\\n", 180 | "&= \\frac{1}{N} \\sum^{N-1}_{i=0} \\int_{\\Omega} \\frac{f(x)}{pdf(x)} pdf(x)\\ dx &[3] \\\\\n", 181 | "&= \\frac{1}{N} \\sum^{N-1}_{i=0} \\int_{\\Omega} f(x) \\ dx &[4] \\\\\n", 182 | "&= \\int_{\\Omega} f(x) \\ dx &[5] \\\\\n", 183 | "&= F\n", 184 | "\\end{align} $$\n", 185 | "\n", 186 | "* $ \\int_\\Omega $ : integrating을 하려는 region을 뜻한다. 1-dimension일때는 line, 2-dimensions은 area이고, 3-dimensions은 volumn을 생각하면 된다.\n", 187 | "\n", 188 | "Monte Carlo Estimator의 convergence rate 는 $ O(\\sqrt{N}) $ 입니다.
\n", 189 | "Convergence rate를 제외하고도 기존 numerical integration techniques와 비교하여 장점은 multiple dimensions 으로 확장이 가능합니다.
\n", 190 | "Deterministic Quadrature techniques 경우 $ N^d $ samples이 d-dimensional integral을 위해서 필요로 합니다.
\n", 191 | "반면 Monte Carlo techniques의 경우 samples의 갯수는 정해져 있지 않습니다. (상황에 따라서 다르게 쓰면 됨)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "# References\n", 199 | "\n", 200 | "* https://cs.dartmouth.edu/~wjarosz/publications/dissertation/appendixA.pdf\n", 201 | "* https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/monte-carlo-methods-in-practice/monte-carlo-integration" 202 | ] 203 | } 204 | ], 205 | "metadata": { 206 | "kernelspec": { 207 | "display_name": "Python 3", 208 | "language": "python", 209 | "name": "python3" 210 | }, 211 | "language_info": { 212 | "codemirror_mode": { 213 | "name": "ipython", 214 | "version": 3 215 | }, 216 | "file_extension": ".py", 217 | "mimetype": "text/x-python", 218 | "name": "python", 219 | "nbconvert_exporter": "python", 220 | "pygments_lexer": "ipython3", 221 | "version": "3.6.3" 222 | } 223 | }, 224 | "nbformat": 4, 225 | "nbformat_minor": 2 226 | } 227 | -------------------------------------------------------------------------------- /importance-sampling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Importance Sampling\n", 8 | "\n", 9 | "## Introduction to Importance Sampling\n", 10 | "\n", 11 | "아래의 토끼는 배경에서 반사된 빛을 받아서 다시 재반사(reflect)하여 카메라에 투영된 이미지의 모습니다.
\n", 12 | "\n", 13 | "![Illumination Integral Illustration](images/impsam_rabbit.jpg)\n", 14 | "\n", 15 | "3D rendering으로 나온 토끼의 이미지처럼, 특정 방향 $ L_i(\\mathbf{u}) $ 으로부터 들어오는 빛을 받아서, 카메라 $ \\mathbf{v} $ 방향으로 재반사 하기 위해서는, Bidirectional reflectance distribution function (BRDF) 라는 material function $ f $ 를 사용합니다. 전체 반사되는 빛 $ L_0(\\mathbf{v}) $ 의 양을 계산하기 위해서는 모든 각각의 방향 $ \\mathbf{u} $ 으로부터 오는 모든 빛을 합 하거나 또는 integration해야 합니다. 공식은 다음과 같습니다.\n", 16 | "\n", 17 | "$$ L_0(\\mathbf{v}) = \\int_H L_i(\\mathbf{u}) f(\\mathbf{u}, \\mathbf{v}) \\cos \\theta_u \\ du $$\n", 18 | "\n", 19 | "공식을 자세하게 알 필요는 없습니다.
\n", 20 | "포인트는 모든 방향에서는 오는 빛을 계산하여 반사되는 빛을 계산하여 적분하는것은 계산의 양이 너무나 많기 때문에 할 수 없는 방법입니다.
\n", 21 | "따라서 uniform distribution으로 랜덤으로 들어오는 빛을 samples로 integral을 계산합니다. 샘플들의 평균은 해당 integral의 approximation과도 같습니다.\n", 22 | "\n", 23 | "![Illumination Integral Illustration](images/impsam_light.jpg)\n", 24 | "\n", 25 | "\n", 26 | "\n", 27 | "**만약 integrated function이 어떻게 작동하는줄 대략적으로 알고 있다면**,
\n", 28 | "Uniform ramdom directions로부터 integral을 approximation하는 것은 좋은 방법이 아닙니다.
\n", 29 | "**예를 들어서 카메라에 반사되는 빛을 구하기 위해서, 사물에 닿는 모든 빛을 구하는게 아니라, 바로 거울 처럼 반사되는 지점에서 오는 빛을 samples로 사용하는 것이 좋을 것입니다.** 왜냐하면 대부분의 카메라에 반사되는 빛은 해당 방향으로부터 빛이 오기 때문입니다.\n", 30 | "\n", 31 | "수학적으로 표현하기 위해서, probability density function (PDF)를 사용하여 샘플링을 위한 최적의 방향을 정하게 됩니다.
\n", 32 | "PDF는 normalized function이며, PDF함수의 전체 도메인에 대한 integral의 값은 1이고, 샘플링에 가장 중요한 지점은 peaks로 나타나게 됩니다." 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "metadata": {}, 38 | "source": [ 39 | "## Variance Reduction\n", 40 | "\n", 41 | "Monte Carlo integration의 퀄리티를 높이기 위해서는 variance 를 낮춰야 합니다.
\n", 42 | "Monte Carlo에서 사용되는 Samples들은 independent하기 때문에 $ \\sigma^2 \\left[ \\sum_i Y_i \\right] = \\sum_i \\sigma^2 [Y_i] $ property를 이용해서 문제를 더 간결하게 만들수 있습니다.\n", 43 | "\n", 44 | "\n", 45 | "$$ \\begin{align} \n", 46 | "\\sigma^2\\left[ \\langle F^N \\rangle \\right] &= \\sigma^2 \\left[ \\frac{1}{N} \\sum^{N-1}_{i=0} \\frac{f(X_i)}{pdf(X_i)} \\right] &[1] \\\\\n", 47 | "&= \\frac{1}{N^2} \\sum^{N-1}_{i=0} \\sigma^2 \\left[ \\frac{f(X_i)}{pdf(X_i)} \\right] &[2] \\\\\n", 48 | "&= \\frac{1}{N^2} \\sum^{N-1}_{i=0} \\sigma^2 [Y_i] &[3] \\\\\n", 49 | "&= \\frac{1}{N} \\sigma^2[Y] &[4] \n", 50 | "\\end{align} $$\n", 51 | "\n", 52 | "따라서...\n", 53 | "\n", 54 | "$$ \\sigma \\left[ \\langle F^N \\rangle \\right] = \\frac{1}{\\sqrt{N}} \\sigma[Y] $$\n", 55 | "\n", 56 | "* $ Y_i = \\frac{f(X_i)}{pdf(X_i)} $\n", 57 | "* $ Y $ : 어떤 특정 $ Y_i $ 의 값을 뜻합니다. 예를 들어서 $ Y = Y_2 $ 또는 $ Y = Y_3 $\n", 58 | "\n", 59 | "위의 유도공식(derivation)은 위에서 언급한 standard deviationdms $ O(\\sqrt{N}) $ 로 converge가 되는 것을 증명합니다.
\n", 60 | "각각의 $ Y_i $ 의 variance를 낮춤으로서 전체적인 $ \\langle F^N \\rangle $ 의 variance또한 낮춰줍니다.\n", 61 | "\n", 62 | "Variance Reduction 기법은 각각의 $ Y_i $ 를 가능하면 constant로 만들려고 하는 것입니다. 이를 통해서 전체적인 에러률을 낮춥니다.\n", 63 | "\n", 64 | "\n", 65 | "왜 f(x) 를 pdf(x) 로 나누려고 하는지 직관적으로 설명하겠습니다.
\n", 66 | "pdf가 높다는것은 random variable $ X $ 가 어떤 값 $ x_i $ 을 가져올 확률을 높여줍니다.
\n", 67 | "예를 들어 아래 그림의 normal distribution에서 중앙에 samples들이 몰려있기 때문에 중앙부분..즉 높은 pdf값을 갖은 samples들을 Monte Carlo 알고리즘에 사용이 될 것입니다. 즉 위의 예제처럼 면적을 구하고자 할때.. y축으로 높은 부분을 사용해서 계산하기 때문에 당연히 결과값도 bias가 생기게 될 것입니다. \n", 68 | "\n", 69 | "하지만 f(x) 를 pdf(x)로 나누면 확률이 높은 부분은 더 낮아지고, 반대로 확률이 적은 부분은 높아지게 됩니다.
\n", 70 | "예를 들어서 rare한 부분의 sample의 경우 1/0.1 = 10 처럼 값이 더 올라가게 됩니다.\n", 71 | "\n", 72 | "![higher density of samples](images/density.png)" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "## No Prior Knowledge on the Integrated Function\n", 80 | "\n", 81 | "위에서 저런 가설이 사용가능한 이유는 Integrated function에 대해서 알고 있기 때문입니다.
\n", 82 | "하지만 **대부분의 경우에는 integrated function에 대해서 사전에 지식이 없는 경우가 대부분이며, 어느 부분이 중요한지 알아서 샘플링은 불가능 합니다.**\n", 83 | "\n", 84 | "여기서 Variance Reduction과 상충되게 됩니다.
\n", 85 | "Variance Reduction 은 integrated function에 대해서 사전에 알고 있어야 하지만 현실은 대부분의 경우 모른다는 것입니다.
\n", 86 | "\n", 87 | "가장 이상적인 상황은 다음과 같습니다.
\n", 88 | "Integrand를 non-constant function에서 constant function으로 만들어주면 됩니다.
\n", 89 | "Constant function으로 만든다는 뜻은 variance은 0으로 만들며 approximation은 항상 동일한 값을 얻는다는 뜻입니다.
\n", 90 | "이는 Monte Carlo Integration의 목표가 variance를 최대한 작게 만들고, samples은 최대한 적은 양을 사용하는 것과도 부합합니다.
\n", 91 | "아래의 그림처럼 constant function이 되면 uniform distribution으로 samples을 얻을 수 있게 됩니다.\n", 92 | "\n", 93 | "![constant-function](images/impsam_uniform.png)\n", 94 | "\n", 95 | "물론 이는 가장 이상적인 상황일때 입니다. 실제로 이런 일은 일어나기 쉽지 않습니다.\n" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "## Convert Non-Constant Function to Constant Function\n", 103 | "\n", 104 | "함수를 자기자신과 나누어 버리면 항상 결과값은 1이 나오게 됩니다.
\n", 105 | "예를 들어서 $ f(0)=2 $ 일때 $ \\frac{f(0)}{2} = 1 $ 이 되고,
\n", 106 | "$ f(2)=0.5 $ 일때 $ \\frac{f(2)}{0.5} = 1 $ 이 되게 됩니다.\n", 107 | "\n", 108 | "![function f(x) is divided by itset](images/impsam_divided_by_self.png)\n", 109 | "\n", 110 | "General Monte Carlo integration $ \\langle F^N \\rangle = \\frac{1}{N} \\sum^{N-1}_{i=0} \\frac{f(x_i)}{pdf(x_i)} $ 에서 $ pdf(x_i) $ 부분을 $ pdf(x_i) = cf(x_i) $ 바꿔서줄 수 있습니다.
\n", 111 | "(이때 조건은 가장 이상적인 상황으로서 $ pdf(x_i) $ 는 integral과 정확히 또는 매우 유사하게 비례한다고 가정한다.
\n", 112 | "따라서 2번째 그림처럼 위치는 다르지만 비율은 동일하기 때문에 $ f(x) = cf'(x) $ 가 된다)\n", 113 | "\n", 114 | "\n", 115 | "$$ \\require{enclose} Y_i = \\frac{f(X_i)}{pdf(X_i)} = \\frac{ \\enclose{updiagonalstrike}{f(X_i)}}{ c \\enclose{updiagonalstrike}{f(X_i)}} = \\frac{1}{c} $$\n", 116 | "\n", 117 | "각각의 $ Y_i $ 는 동일한 값을 리턴하기 때문에, 전체적으로 variance도 0입니다.
\n", 118 | "\n", 119 | "c를 유도하는 방법은 PDF가 integrate하면 1이 되는 점을 이용합니다.
\n", 120 | "\n", 121 | "$ pdf(X_i) = cf(X_i) $ 이므로.. $ \\int cf(X_i) = 1 $ 이 됩니다.
\n", 122 | "상수에 대한 곱은 intgration rule에서 밖으로 빠질수 있으므로 $ c \\int f(X_i) = 1 $ 가 됩니다.
\n", 123 | " 여기서 다시 $ \\int f(X_i) $ 를 우측으로 보내면 아래와 같은 공식이 나오게 됩니다.\n", 124 | "
\n", 125 | "\n", 126 | "$$ c = \\frac{1}{\\int f(x)\\ dx} $$\n", 127 | "\n", 128 | "해당 공식은 불행하게도 integral $ f(x) $ 를 연산해야지만 pdf에서 사용되는 normalization constant $ c $ 를 얻을수 있다는 것을 보여줍니다.
즉 이 방법을 사용하기 위해서는 $ c $ 를 알아야 하는데.. 애초 처음에 integral $ f(x) $ 를 연산을 처음에 해놔야 한다는 뜻입니다.\n", 129 | "\n", 130 | "따라서 실제 적용은 매우 어려운 경우가 많습니다. (일단 integral f(x)를 한다는 것 자체를 모르기 때문에 못하는 경우가 많기 때문에)
\n", 131 | "아래 그림에서 파란색은 intgrand function 이고 빨간색은 pdf를 나타냅니다.\n", 132 | "\n", 133 | "![Importance Sampling to work](images/impsam_pdf.png)\n", 134 | "\n", 135 | "만약 integrand function의 shape에 대해서 전혀 모른다면 그냥 uniform distribution으로 가는게 좋습니다.
\n", 136 | "물론 pdf와 intgrand가 유사한 분포를 갖고 있는것보다는 좋지 않겠지만.. 잘못 선택하여 전혀 다른 분포를 갖은 pdf 를 사용하는 것 보다는 낫습니다." 137 | ] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "# Example\n", 144 | "\n", 145 | "다음의 integral를 Monte Carlo Integration을 사용하여 $ sin(x) $ 함수를 approximate합니다.\n", 146 | "\n", 147 | "$$ F = \\int^{\\pi/2}_{0} sin(x)\\ dx $$\n", 148 | "\n", 149 | "Second fundamental of calculus에 따르면 antiderivate of $ sin(x) $ 는 $ - cos(x) $ 이므로 다음과 같이 쓸수 있습니다.\n", 150 | "\n", 151 | "$$ \\begin{align} \n", 152 | "F &= \\left[ - \\cos \\left( x \\right) \\right]^{\\frac{\\pi}{2}}_0 \\\\\n", 153 | "&= - cos\\left( \\frac{\\pi}{2} \\right) - (- cos(0)) \\\\\n", 154 | "&= 1\n", 155 | "\\end{align}$$\n", 156 | "\n", 157 | "해당 integral의 결과값은 1입니다.
\n", 158 | "해당 integral을 Monte Carlo integration으로 위의 integral을 approximate하겠습니다.
\n", 159 | "이때 2개의 서로다른 pdf를 사용합니다.\n", 160 | "\n", 161 | "* $ \\text{Uniform probability distribution} (p(x) = \\frac{2}{\\pi x}) $\n", 162 | "* $ \\text{pdf}(p'(x) = \\frac{8x}{\\pi^2}) $\n", 163 | "\n", 164 | "아래 그림에서 보듯이 두번째 PDF가 uniform probability distribution보다 integrand의 shape에 더 유사합니다.
\n", 165 | "위에서 배운 이론대로라면 uniform probability distribution보다 두번째 PDF가 variance를 더 줄여줍니다.\n", 166 | "\n", 167 | "![](images/impsam_example.png)\n", 168 | "\n", 169 | "### 첫번째 Uniform Distribution에 대해서..\n", 170 | "* **Uniform distribution에는 다음의 estimator를 사용합니다.**
\n", 171 | "여기서 $ X_i $ 는 uniform distribution을 갖는 PDF에서 가져오게 됩니다.
\n", 172 | "\n", 173 | " Uniform distribution를 가정하는 Basic Monte Carlo Integration을 사용합니다.
\n", 174 | " 즉 $ X_i $ 는 uniform distribution으로 가져오게됩니다.
\n", 175 | " $ \\langle F^N \\rangle = (b-a) \\frac{1}{N} \\sum^{N}_{i=1} f(X_i) $\n", 176 | "
\n", 177 | "\n", 178 | "$$ \\langle F^N \\rangle = \\frac{\\pi/2}{N} \\sum^{N-1}_{i=0} sin(X_i) $$\n", 179 | "\n", 180 | "\n", 181 | "### 두번째 General Monte Carlo에 대해서..\n", 182 | "\n", 183 | "* **두번째 PDF의 $ X_i $ 를 구하기 위해서 먼저 CDF를 구합니다.**\n", 184 | "\n", 185 | "\n", 186 | "$$ CDF(x < \\mu) = \\int^{\\mu}_{0} \\frac{8x}{\\pi^2} = \\left[ \\frac{4x^2}{\\pi^2} \\right]^{\\mu}_{0} = \\frac{4\\mu^2}{\\pi^2} - 0 $$\n", 187 | "\n", 188 | "* **이후 inverse CDF를 해줍니다.**
\n", 189 | "\n", 190 | " CDF를 통해서 x보다 작거나 같을 확률을 얻을 수 있습니다.
\n", 191 | " Inverse CDF를 통해서는 반대로 확률 $ p $ 가 주어지면 상응하는 $ x $ 값을 알아냅니다.
\n", 192 | "
\n", 193 | "\n", 194 | "$$ \\begin{align} \n", 195 | "CDF(x < \\mu) &= \\frac{4x^2}{\\pi^2} \\\\\n", 196 | "x^2 &= \\frac{\\pi^2}{4} CDF(x < \\mu) \\\\\n", 197 | "x &= \\frac{\\pi}{2} \\sqrt{CDF(x < \\mu)}\n", 198 | "\\end{align}$$\n", 199 | "\n", 200 | "* **궁극적으로 두번째 PDF의 경우 General Monte Carlo를 사용합니다.**
\n", 201 | "\n", 202 | "$ X_i $ 는 위의 inverse CDF에서 나온것을 사용합니다.
\n", 203 | "아래공식에서 PDF는 $ \\frac{8X_i}{\\pi^2} $ 를 가르킵니다.\n", 204 | "
\n", 205 | "\n", 206 | "$$ \\langle F^N \\rangle = \\frac{1}{N} \\sum^{N-1}_{i=0} \\frac{f(x_i)}{pdf(x_i)} $$\n", 207 | "\n", 208 | "\n" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": 68, 214 | "metadata": {}, 215 | "outputs": [ 216 | { 217 | "name": "stdout", 218 | "output_type": "stream", 219 | "text": [ 220 | "Uniform error:0.3% Importance error:0.5% Uniform:0.997 Importance:1.01 \n", 221 | "Uniform error:26.2% Importance error:5.9% Uniform:0.738 Importance:1.06 \n", 222 | "Uniform error:6.0% Importance error:1.8% Uniform:0.94 Importance:1.02 \n", 223 | "Uniform error:8.7% Importance error:2.0% Uniform:1.09 Importance:0.98 \n", 224 | "Uniform error:3.6% Importance error:1.1% Uniform:0.964 Importance:1.01 \n", 225 | "Uniform error:3.5% Importance error:0.4% Uniform:0.965 Importance:1.0 \n", 226 | "Uniform error:3.9% Importance error:1.7% Uniform:1.04 Importance:0.983 \n", 227 | "Uniform error:1.2% Importance error:1.5% Uniform:1.01 Importance:0.985 \n", 228 | "Uniform error:5.4% Importance error:0.5% Uniform:1.05 Importance:0.995 \n", 229 | "Uniform error:0.9% Importance error:0.8% Uniform:1.01 Importance:0.992 \n" 230 | ] 231 | } 232 | ], 233 | "source": [ 234 | "import numpy as np\n", 235 | "from sklearn.metrics import mean_squared_error\n", 236 | "\n", 237 | "N = 16\n", 238 | "\n", 239 | "x = np.arange(0, np.pi/2, 0.001)\n", 240 | "\n", 241 | "def train(N):\n", 242 | " sum_uniform = 0\n", 243 | " sum_importance = 0\n", 244 | " for i in range(N):\n", 245 | " rand = np.random.rand(1)\n", 246 | " sum_uniform += np.sin(rand * np.pi * 0.5)\n", 247 | "\n", 248 | " x_i = np.sqrt(rand) * np.pi * 0.5\n", 249 | " sum_importance += np.sin(x_i)/ ((8 * x_i) / (np.pi**2))\n", 250 | " \n", 251 | " sum_uniform *= (np.pi * 0.5)/N\n", 252 | " sum_importance *= 1/N\n", 253 | " return sum_uniform[0], sum_importance[0]\n", 254 | " \n", 255 | "\n", 256 | "for i in range(10):\n", 257 | " uniform, importance = train(N)\n", 258 | " a = np.abs(1-uniform) \n", 259 | " b = np.abs(1-importance)\n", 260 | " print(f'Uniform error:{a:<8.1%} Importance error:{b:<8.1%}'\n", 261 | " f'Uniform:{uniform:<8.3} Importance:{importance:<8.3}' )\n", 262 | " " 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "## 결론 \n", 270 | "\n", 271 | "**integral $ f(X) $ 에 대해서 알고 있다면**
\n", 272 | " - integral $ f(X) $ 와 유사한 pdf를 사용하여 variance를 낮춘다. \n", 273 | " \n", 274 | " \n", 275 | "**integral $ f(X) $ 에 대해서 모르고 있다면**
\n", 276 | " - 전혀 알수 없다면 uniform distribution을 사용한다. \n", 277 | " \n", 278 | "\n", 279 | " \n", 280 | " " 281 | ] 282 | } 283 | ], 284 | "metadata": { 285 | "kernelspec": { 286 | "display_name": "Python 3", 287 | "language": "python", 288 | "name": "python3" 289 | }, 290 | "language_info": { 291 | "codemirror_mode": { 292 | "name": "ipython", 293 | "version": 3 294 | }, 295 | "file_extension": ".py", 296 | "mimetype": "text/x-python", 297 | "name": "python", 298 | "nbconvert_exporter": "python", 299 | "pygments_lexer": "ipython3", 300 | "version": "3.6.3" 301 | } 302 | }, 303 | "nbformat": 4, 304 | "nbformat_minor": 2 305 | } 306 | --------------------------------------------------------------------------------