def plot_covariances(X, Theta, Y=None): if Y is None: eigvals, eigvecs = scipy.linalg.eigh(Theta) Y = eigvecs.dot(np.diag(1 / np.sqrt(eigvals))).dot(eigvecs.T) plt.figure() plt.subplot(221) plt.matshow(Theta, cmap=plt.cm.RdBu_r, fignum=False) plt.clim((-1, 1)) plt.title('population precision matrix') plt.colorbar() plt.subplot(222) sample_prec = scipy.linalg.inv(cov2corr(X.T.dot(X))) plt.matshow(sample_prec, cmap=plt.cm.RdBu_r, fignum=False) max_plot = np.max(np.abs(sample_prec)) / 5. plt.clim((-max_plot, max_plot)) plt.title('sample (n={}) precision matrix'.format(X.shape[0])) plt.colorbar() plt.subplot(223) plt.matshow(cov2corr(Y.T.dot(Y)), cmap=plt.cm.RdBu_r, fignum=False) plt.clim((-1, 1)) plt.title('population correlation matrix') plt.colorbar() plt.subplot(224) plt.matshow(cov2corr(X.T.dot(X)), cmap=plt.cm.RdBu_r, fignum=False) plt.clim((-1, 1)) plt.title('sample correlation matrix') plt.colorbar() plt.show()
def plot_covariance(cov, scaled=True, aux=None, diag=True, grid=True): cov_ = cov.copy() if scaled: from covariance_learn import _cov_2_corr as cov2corr cov_ = cov2corr(cov_) if not diag: cov_.flat[::cov_.shape[0] + 1] = 0. plt.figure() ax = plt.gca() if aux is None: aux = np.ones(cov_.shape) im = plt.matshow(np.ma.masked_equal(aux, 0) * cov_, cmap=plt.cm.RdBu_r, fignum=False) ax.set_axis_bgcolor('.4') ax.set_xticklabels([]) ax.set_yticklabels([]) divider = make_axes_locatable(ax) if cov_.shape[0] == 16 and grid: for k in np.arange(4 - 1): plt.plot([-.5, 15.5], [4 * (k + 1) - .5, 4 * (k + 1) - .5], linewidth=2, color='black') plt.plot([4 * (k + 1) - .5, 4 * (k + 1) - .5], [-.5, 15.5], linewidth=2, color='black') plt.xlim((-.5, 15.5)) plt.ylim((15.5, -.5)) elif cov_.shape[0] == 512 and grid: for k in np.arange(64 - 1): plt.plot([-.5, 512.5], [8 * (k + 1) - .5, 8 * (k + 1) - .5], linewidth=1 + int(not((k + 1) % 8)), color='black') plt.plot([8 * (k + 1) - .5, 8 * (k + 1) - .5], [-.5, 512.5], linewidth=1 + int(not((k + 1) % 8)), color='black') plt.xlim((-.5, 512.5)) plt.ylim((512.5, -.5)) m = np.max(np.abs(cov_)) plt.clim((-m, m)) cax = divider.append_axes('right', size='5%', pad=.05) cb = plt.colorbar(im, cax=cax) cb.ax.tick_params(labelsize=18)