Basically, I am trying to sample x and y from a proposal distribution function and then find the weights for the sample, and create 10 different sets of n = 10,000 samples. I was given an array of 55 values for radius and mu and sigma, and I have 10,000 values of x and y as samples.
here is my code:
import numpy as np
import matplotlib.pyplot as plt
GN = 4.302**-6
A = 8445.264
mu = np.array([1,1])
C = [[1,0],[0,1]]
num = 10**4
def chi_sq(x,y):
r = np.zeros(len(radius))
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
return r
def P(x,y):
return A*np.exp(-0.5*chi_sq(x,y))
for i in range(10):
def chi_sq(x,y):
r = np.zeros(len(radius))
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
return r
def P(x,y):
return A*np.exp(-0.5*chi_sq(x,y))
detC = np.linalg.det(C)
Cinv = np.linalg.inv(C)
def Q(x,y):
r = np.array([x,y]) - mu
prefactor = 1/(2*np.pi*np.sqrt(detC))
exponent = 0.5*(r @ Cinv @ r)
return prefactor*np.exp(-exponent)
r_samples = np.random.multivariate_normal(mu,C,num)
x_samples = r_samples[:,0]
y_samples = r_samples[:,1]
w = np.zeros(num)
for j in range(num):
x, y = r_samples[j]
w[j] = P(x,y)/Q(x,y)
Here is the error I am getting:
IndexError Traceback (most recent call last)
<ipython-input-114-638cc1a1b2e2> in <module>()
41 x, y = r_samples[j]
42
---> 43 w[j] = P(x,y)/Q(x,y)
1 frames
<ipython-input-114-638cc1a1b2e2> in chi_sq(x, y)
22 for s in range(len(radius)):
23 f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
---> 24 chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
25 r += chi_sqtotal
26 return r
IndexError: index 2 is out of bounds for axis 0 with size 2
The error is very descriptive:
IndexError: index 2 is out of bounds for axis 0 with size 2
If I have a numpy.ndarray
, let's call it x
, then the axes are as follows:
x[axis_0][axis_1]...
They are saying that the size of the axis is 2, and you're indexing it with 2, which is out of bounds. Notice
mu = np.array([1,1])
and the line with mu
has the error. In this chunk:
for s in range(len(radius)):
f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
r += chi_sqtotal
s
goes above 1, causing the error. You need to make a correction somewhere and not loop as high as len(radius)
, because mu
only has 2 elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.