def plot_gaussians(xs, ps, x_range, y_range, N): """ given a list of 2d states (x,y) and 2x2 covariance matrices, produce a surface plot showing all of the gaussians""" xs = np.asarray(xs) x = np.linspace(x_range[0], x_range[1], N) y = np.linspace(y_range[0], y_range[1], N) xx, yy = np.meshgrid(x, y) zv = np.zeros((N, N)) for mean, cov in zip(xs, ps): zs = np.array([ multivariate_gaussian(np.array([i, j]), mean, cov) for i, j in zip(np.ravel(xx), np.ravel(yy)) ]) zv += zs.reshape(xx.shape) ax = plt.figure().add_subplot(111, projection='3d') ax.plot_surface(xx, yy, zv, rstride=1, cstride=1, lw=.5, edgecolors='#191919', antialiased=True, shade=True, cmap=cm.autumn) ax.view_init(elev=40., azim=230)
def run(self): np.random.seed(13) x = [2.5, 7.3] mu = [2.0, 7.0] P = [[8., 0], [0, 3.]] mg = multivariate_gaussian(x, mu, P) print(mg)
def test_multivariate_gaussian(): # test that we treat lists and arrays the same mean= (0, 0) cov=[[1, .5], [.5, 1]] a = [[multivariate_gaussian((i, j), mean, cov) for i in (-1, 0, 1)] for j in (-1, 0, 1)] b = [[multivariate_gaussian((i, j), mean, np.asarray(cov)) for i in (-1, 0, 1)] for j in (-1, 0, 1)] assert np.allclose(a, b) a = [[multivariate_gaussian((i, j), np.asarray(mean), cov) for i in (-1, 0, 1)] for j in (-1, 0, 1)] assert np.allclose(a, b)
def test_multivariate_gaussian(): # test that we treat lists and arrays the same mean = (0, 0) cov = [[1, .5], [.5, 1]] a = [[multivariate_gaussian((i, j), mean, cov) for i in (-1, 0, 1)] for j in (-1, 0, 1)] b = [[ multivariate_gaussian((i, j), mean, np.asarray(cov)) for i in (-1, 0, 1) ] for j in (-1, 0, 1)] assert np.allclose(a, b) a = [[ multivariate_gaussian((i, j), np.asarray(mean), cov) for i in (-1, 0, 1) ] for j in (-1, 0, 1)] assert np.allclose(a, b)
def plot_3d_sampled_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o,w,h = stats.covariance_ellipse(cov,3) # rotate width and height to x,y axis wx = abs(w*np.cos(o) + h*np.sin(o))*1.2 wy = abs(h*np.cos(o) - w*np.sin(o))*1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w count = 1000 x,y = multivariate_normal(mean=mean, cov=cov, size=count).T xs = np.arange(minx, maxx, (maxx-minx)/40.) ys = np.arange(miny, maxy, (maxy-miny)/40.) xv, yv = np.meshgrid (xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \ for xx,yy in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) ax = plt.figure().add_subplot(111, projection='3d') ax.scatter(x,y, [0]*count, marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn) ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)
def test_multivariate_gaussian(): # test that we treat lists and arrays the same mean= (0, 0) cov=[[1, .5], [.5, 1]] a = [[multivariate_gaussian((i, j), mean, cov) for i in (-1, 0, 1)] for j in (-1, 0, 1)] b = [[multivariate_gaussian((i, j), mean, np.asarray(cov)) for i in (-1, 0, 1)] for j in (-1, 0, 1)] assert np.allclose(a, b) a = [[multivariate_gaussian((i, j), np.asarray(mean), cov) for i in (-1, 0, 1)] for j in (-1, 0, 1)] assert np.allclose(a, b) try: multivariate_gaussian(1, 1, -1) except: pass else: assert False, "negative variances are meaningless" # test that we get the same results as scipy.stats.multivariate_normal xs = np.random.randn(1000) mean = np.random.randn(1000) var = np.random.random(1000) * 5 for x, m, v in zip(xs, mean, var): assert abs(multivariate_gaussian(x, m, v) - scipy.stats.multivariate_normal(m, v).pdf(x)) < 1.e-12
def plot_gaussians(xs, ps, x_range, y_range, N): """ given a list of 2d states (x,y) and 2x2 covariance matrices, produce a surface plot showing all of the gaussians""" xs = np.asarray(xs) x = np.linspace (x_range[0], x_range[1], N) y = np.linspace (y_range[0], y_range[1], N) xx, yy = np.meshgrid(x, y) zv = np.zeros((N, N)) for mean, cov in zip(xs, ps): zs = np.array([multivariate_gaussian(np.array([i ,j]), mean, cov) for i, j in zip(np.ravel(xx), np.ravel(yy))]) zv += zs.reshape(xx.shape) ax = plt.figure().add_subplot(111, projection='3d') ax.plot_surface(xx, yy, zv, rstride=1, cstride=1, lw=.5, edgecolors='#191919', antialiased=True, shade=True, cmap=cm.autumn) ax.view_init(elev=40., azim=230)
def plot_3d_sampled_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o, w, h = stats.covariance_ellipse(cov, 3) # rotate width and height to x,y axis wx = abs(w * np.cos(o) + h * np.sin(o)) * 1.2 wy = abs(h * np.cos(o) - w * np.sin(o)) * 1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w count = 1000 x, y = multivariate_normal(mean=mean, cov=cov, size=count).T xs = np.arange(minx, maxx, (maxx - minx) / 40.) ys = np.arange(miny, maxy, (maxy - miny) / 40.) xv, yv = np.meshgrid(xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \ for xx,yy in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) ax = plt.gcf().add_subplot(111, projection='3d') ax.scatter(x, y, [0] * count, marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') x = mean[0] zs = np.array([ 100. * stats.multivariate_gaussian(np.array([x, y]), mean, cov) for _, y in zip(np.ravel(xv), np.ravel(yv)) ]) zv = zs.reshape(xv.shape) ax.contour(xv, yv, zv, zdir='x', offset=minx - 1, cmap=cm.binary) y = mean[1] zs = np.array([ 100. * stats.multivariate_gaussian(np.array([x, y]), mean, cov) for x, _ in zip(np.ravel(xv), np.ravel(yv)) ]) zv = zs.reshape(xv.shape) ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.binary)
def plot_3d_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o,w,h = stats.covariance_ellipse(cov,3) # rotate width and height to x,y axis wx = abs(w*np.cos(o) + h*np.sin(o))*1.2 wy = abs(h*np.cos(o) - w*np.sin(o))*1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w xs = np.arange(minx, maxx, (maxx-minx)/40.) ys = np.arange(miny, maxy, (maxy-miny)/40.) xv, yv = np.meshgrid(xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([x,y]),mean,cov) \ for x, y in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) maxz = np.max(zs) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #ax = plt.gca(projection='3d') ax.plot_surface(xv, yv, zv, rstride=1, cstride=1, cmap=cm.autumn) ax.set_xlabel('X') ax.set_ylabel('Y') # For unknown reasons this started failing in Jupyter notebook when # using `%matplotlib inline` magic. Still works fine in IPython or when # `%matplotlib notebook` magic is used. x = mean[0] zs = np.array([100.* stats.multivariate_gaussian(np.array([x, y]),mean,cov) for _, y in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) try: pass #ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.binary) except: pass y = mean[1] zs = np.array([100.* stats.multivariate_gaussian(np.array([x, y]),mean,cov) for x, _ in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) try: pass #ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.binary) except: pass