Monte Carlo integral approximation - importance sampling Question.

Asked 2 years ago, Updated 2 years ago, 20 views

% matplotlib inline
from sympy import *
from scipy import random
import numpy as np
import matplotlib.pyplot as plt

a = 0
b = 1        
M = 100000   
xrand = np.zeros(M)
yrand = np.zeros(M)
zrand = np.zeros(M)

for i in range(len(xrand)):
    xrand[i] = random.uniform(a,b)
    yrand[i] = random.uniform(a,b)
    zrand[i] = random.uniform(a,b)

As above, we created a structure in which the random value varies depending on the i value in the form of xrand[i] = random value, but after that, it didn't work as well as we thought. The exact situation is as follows.

import random

N = 900
def monte_carlo(the_list) :
    if len(the_list) > N :
        return the_list
    else :
        x = random.random()
        y = random.random()
        z = random.random()
        if p(y)/p(x) > z :
            the_list.append(y)    
            return monte_carlo(the_list)
        else :
            the_list.append(x)   
                # Recursive
            return monte_carlo(the_list)

new_list = []
print(monte_carlo(new_list)) 

The above code is the code that a master posted when I asked a question before (a kind of importance sampling as I found out later).

This person picked it in the form of a recursive function, but the error came out bigger than I thought. I'm going to change the way.

After creating x[i] that relies on the i value according to the method advised by a successful lab colleague by coding with C, when the determination condition (p(y[i])/p(x[i] > z[i]) is satisfied, keep it as it is Append y,

In the case of else, we don't take a recursive action, we just move on to i = i + 1 and make a new decision p(y[i+1])/p(x[i+1]) > z[i+1].. I want to create such a structure and get N random values that satisfy the judgment, but it doesn't work. (Note that even in this case, M random value values are likely to run out before N random values are extracted. I don't know if it's possible to make an infinite random value list, so I'm going to do it this way.)

What should I do? Please give me some advice.

Add) First of all, the sloppy code I completed a few days ago is as follows. I'm embarrassed, but please give me some advice."T" The middle part of the code is importance sampling.

from sympy import *
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
a = Symbol('a')

def f(x):
    return 3 * x **2
def p(x):
    return 2 * x 
def g(x) :
    return f(x)/p(x)

Integral(f(x),x).doit()
pprint(Integral(f(x),x).doit()) 
pprint(Integral(f(x), (x,0,1)).doit()) # accurate integration value
pprint(Integral(p(x), (x,0,1)).doit()) # Normalization check

# Attempt to Solve Function Static Equations with Parcel Spanning Method

% % matplotlib inline
from sympy import *
from scipy import random
import numpy as np
import matplotlib.pyplot as plt

a = 0
b = 1 # limit of integration 0 to pi function integration
M = 100000 #Number of splits
xrand = np.zeros(M)

for i in range(len(xrand)):
    xrand[i] = random.uniform(a,b)

integral = 0.0
for i in range(M):
    integral += f(xrand[i])

answer = (b-a)/float(M)*integral
error = abs(1-answer)
print("The integral from 0 to 1 of f(x): ", answer)
print("error: ", error)


import random

# Try importance sampling.

'''
 Dear Yupto.

 The basic idea is to obtain the integral(f(x))dx (from 0 to 1) as an approximation process using random numbers.
 f(x) = (f(x)/p(x)) * p(x) = g(x) * p(x) where p(x) is called weight function or probability distribution function (pdf).

 At this time, if you extract N x values that satisfy a specific determination condition (conditional expression in the code below) and obtain the average value of g(x), 
 " Mean value of g(x) = the original static integral value of f(x)" is known to be valid. The larger the N value, the smaller the difference between the two values.

 (For your information, assume that f(x) = 3x^2, p(x) = 2x and g(x) = 3x^2/2x.)
 (So the final value to get close is the static value of 1.)
''' 

# If you give an empty list, if you satisfy a specific expression, you will return up to N random values in the list.
N = 900
def monte_carlo(the_list) :
    if len(the_list) > N :
        return the_list
    else :
        x = random.random()
        y = random.random()
        z = random.random()
        If p(y)/p(x) > z : # p(X) is a first-order polynomial in this case, so y/x is fine.
            The_list.append(y) # Re-run this function itself
            return monte_carlo(the_list)
        else :
            Put the_list.append(x) #x on the list,
                # Recursive
            return monte_carlo(the_list)

new_list = []
#print(monte_carlo(new_list)) 

I = 0
for i in range(N):
    I += g(monte_carlo(new_list)[i])/ N
print(I)

python

2022-09-22 15:36

1 Answers

Thank you for the explanation. Maybe it's because I'm in liberal arts, but I have a cramp in my head even if I enter math engineering <
I read Wikipedia, and so on, and I'm rewatching the entire source, and what I' I feel like I need to pick one by one instead of picking out "x values that satisfy the conditional formula" in advance. Maybe one of the reasons your computing equipment can't hold up is a memory leak. There's an array of tens to millions of elements, and there's another dynamic array that stores the results of three random turns. As you do it.

By the way, even if you read Montecarlo integral in the first place, I'm not sure if it's something like a probability distribution function that should be introduced. If you put random x between the top and bottom ends into f(x) so much that if you average the input values, then the average value multiplied by (top-bottom) is very close to the desired integral value... For example,

import random

left = 0
right = 1
aggregate = 0
pseudo_infinity = 1000000

for i in range(pseudo_infinity) :
    x = random.uniform(left, right) # Generates random mistakes repeatedly in an infinite loop
    Put aggregate += 3 * pow(x, 2) # 3x^2 into the expression you just solved

print((aggregate / pseudo_infinity) * (right - left))

I mean, it's something like this. It spins more smoothly than you think. Online IDE, once in 1 second, roughly three times

Converts to 1 as you say. Finished with homework? -_-;

Summary: Introduce probability distribution functionEven without importance sampling, it seems that somewhere you can implement what we call the "Monte Carlo method" with sufficient performance. If we need to introduce something more advanced, then we can also think of a way to keep going around infinite loops and updating the average frequently, without having to draw a random list in advance.

I don't think it's the answer you want, but I hope it helps.


2022-09-22 15:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.