问题
How can I fill a 3D grid in the order specified by a given probability density function?
Using python, I'd like to lay down points in a random order, but according to some specified probability distribution over that region, with no repeated points.
Sequentially:
- create a discrete 3D grid
- specify a probability density function for every grid point, pdf(x,y,z)
- lay down a point (x0,y0,z0) whose random location is proportional to the pdf(x,y,z)
- continue adding points (without repeating) until all locations are filled
The desired result is a list of all points (no repeats) of all the points in the grid, in order that they were filled.
回答1:
The below does not implement drawing from a multivariate gaussian:
xi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())
yi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())
zi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())
That is because p(x)*p(y)*p(z) != p(x,y,z)
unless the three variables are independent. You can consider something like a Gibbs sampler to draw from the joint distribution by sequentially drawing from univariate distributions.
In the specific case of the multivariate normal, you can use (full example)
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
from math import *
num_points = 4000
sigma = .5;
mean = [0, 0, 0]
cov = [[sigma**2,0,0],[0,sigma**2,0],[0,0,sigma**2]]
x,y,z = np.random.multivariate_normal(mean,cov,num_points).T
svals = 16
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d',aspect='equal')
ax.scatter(x,y,z, s=svals, alpha=.1,cmap=cm.gray)
回答2:
Here's an example, using a gaussian pdf (see plot). This code is easily adapted to any specified pdf:
%matplotlib qt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#number of points to lay down:
n = 4000;
#create meshgrid:
min, max, L = -5, 5, 91;
[x_grid,y_grid,z_grid] = np.meshgrid(np.linspace(min,max,L),np.linspace(min,max,L),np.linspace(min,max,L))
xi,yi,zi = x_grid.ravel(),y_grid.ravel(),z_grid.ravel()
#create normalized pdf (gaussian here):
pdf = np.exp(-(x_grid**2 + y_grid**2 + z_grid**2));
pdf = pdf/np.sum(pdf);
#obtain indices of randomly selected points, as specified by pdf:
randices = np.random.choice(np.arange(x_grid.ravel().shape[0]), n, replace = False,p = pdf.ravel())
#random positions:
x_rand = xi[randices]
y_rand = yi[randices]
z_rand = zi[randices]
fig = plt.figure();
ax = fig.add_subplot(111, projection='3d',aspect='equal')
svals = 16;
ax.scatter(x_rand, y_rand, z_rand, s=svals, alpha=.1)
来源:https://stackoverflow.com/questions/32725710/randomly-fill-a-3d-grid-according-to-a-probability-density-function-px-y-z