绘制等高线

import numpy as np
import matplotlib.pyplot as plt
 
num = 200
l = np.linspace(-5,5,num)
X, Y =np.meshgrid(l, l)

def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)

Z = f(X, Y)
 
cs = plt.contour(X,Y,Z)
plt.clabel(cs)

# 自定义的高维高斯分布概率密度函数
def gaussian(x,mean,cov):    
    dim = np.shape(cov)[0] #维度
    covdet = np.linalg.det(cov+np.eye(dim)*0.01) #协方差矩阵的秩
    covinv = np.linalg.inv(cov+np.eye(dim)*0.01) #协方差矩阵的逆
    xdiff = x - mean
    #概率密度
    prob = 1.0/np.power(2*np.pi,1.0*2/2)/np.sqrt(np.abs(covdet))*np.exp(-1.0/2*np.dot(np.dot(xdiff,covinv),xdiff))

    return prob


#作二维高斯概率密度函数的热力图
mean = [0,0]
cov = [[2.18794147,1.16576957],
 [1.16576957,2.31865957]]
n=200
x = np.linspace(-6,6,n)
y = np.linspace(-6,6,n)
xx,yy = np.meshgrid(x, y)
zz = np.zeros((n,n))

for i in range(n):
    for j in range(n):
        zz[i][j] = gaussian(np.array([xx[i][j],yy[i][j]]),mean,cov)

gci = plt.imshow(zz,origin='lower') # 选项origin='lower' 防止tuixan图像颠倒
plt.xticks([5,100,195],[-5,0,5])
plt.yticks([5,100,195],[-5,0,5])
plt.title('gaussian',{'fontname':'STFangsong','fontsize':18})

posted @ 2018-09-26 20:22:25
评论加载中...

发表评论