2015-09-08 97 views
0

我想繪製一個概率密度函數z=f(x,y)。 我發現代碼中Color matplotlib plot_surface command with surface gradientPython&Matplotlib:如何創建一個meshgrid來繪製衝浪?

繪製衝浪,但我不知道該怎麼CONVER的z價值爲grid,所以我可以繪製它 示例代碼和我的修改如下。

import numpy as np 
import matplotlib.pyplot as plt 
from sklearn import mixture 
import matplotlib as mpl 
from mpl_toolkits.mplot3d import Axes3D 
from matplotlib import cm 

%matplotlib inline 

n_samples = 1000 

# generate random sample, two components 
np.random.seed(0) 
shifted_gaussian = np.random.randn(n_samples, 2) + np.array([20, 5]) 
sample = shifted_gaussian 

# fit a Gaussian Mixture Model with two components 
clf = mixture.GMM(n_components=3, covariance_type='full') 
clf.fit(sample) 

# Plot it 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
X = np.arange(-5, 5, .25) 
Y = np.arange(-5, 5, .25) 
X, Y = np.meshgrid(X, Y) 
## In example Code, the z is generate by grid 
# R = np.sqrt(X**2 + Y**2) 
# Z = np.sin(R) 

# In my case, 
# for each point [x,y], the probability value is 
# z = clf.score([x,y]) 
# but How can I generate a grid Z? 

Gx, Gy = np.gradient(Z) # gradients with respect to x and y 
G = (Gx**2+Gy**2)**.5 # gradient magnitude 
N = G/G.max() # normalize 0..1 
surf = ax.plot_surface(
    X, Y, Z, rstride=1, cstride=1, 
    facecolors=cm.jet(N), 
    linewidth=0, antialiased=False, shade=False) 
plt.show() 

劇情z的原始方法是通過網格生成。但在我的情況下,擬合的模型不能返回grid-like風格的結果,所以問題是我怎樣才能產生價值,並繪製它?

+0

什麼是混合物? – askewchan

回答

1

如果我理解正確,您基本上有一個函數z,它將列表中的兩個標量值x,y並返回另一個標量z_val。換句話說z_val = z([x,y]),對吧?

如果是這樣的情況下,你可以做以下的(注意,這是沒有考慮到效率編寫的,但重點是可讀性):

from itertools import product 

X = np.arange(15) # or whatever values for x 
Y = np.arange(5) # or whatever values for y 
N, M = len(X), len(Y) 
Z = np.zeros((N, M)) 
for i, (x,y) in enumerate(product(X,Y)): 
    Z[np.unravel_index(i, (N,M))] = z([x,y]) 

如果你想使用plot_surface,然後按照與此:

X, Y = np.meshgrid(X, Y) 
ax.plot_surface(X, Y, Z.T)