def plotdata(obsmode,spectrum,val,odict,sdict,
instr,fieldname,outdir,outname):
isetting=P.isinteractive()
P.ioff()
P.clf()
P.plot(obsmode,val,'.')
P.ylabel('(pysyn-syn)/syn')
P.xlabel('obsmode')
P.title("%s: %s"%(instr,fieldname))
P.savefig(os.path.join(outdir,outname+'_obsmode.ps'))
P.clf()
P.plot(spectrum,val,'.')
P.ylabel('(pysyn-syn)/syn')
P.xlabel('spectrum')
P.title("%s: %s"%(instr,fieldname))
P.savefig(os.path.join(outdir,outname+'_spectrum.ps'))
matplotlib.interactive(isetting)
python类title()的实例源码
def starPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
"""Star bin plot"""
mag_g = data[mag_g_dred_flag]
mag_r = data[mag_r_dred_flag]
filter = star_filter(data)
iso_filter = (iso.separation(mag_g, mag_r) < 0.1)
# projection of image
proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC'])
plt.scatter(x, y, edgecolor='none', s=3, c='black')
plt.xlim(0.2, -0.2)
plt.ylim(-0.2, 0.2)
plt.gca().set_aspect('equal')
plt.xlabel(r'$\Delta \alpha$ (deg)')
plt.ylabel(r'$\Delta \delta$ (deg)')
plt.title('Stars')
def show_particles(rbm, state, dataset, display=True, figname='PCD particles', figtitle='PCD particles',
size=None):
try:
fantasy_vis = rbm.vis_expectations(state.h)
except:
fantasy_vis = state
if size is None:
size = (dataset.num_rows, dataset.num_cols)
imgs = [fantasy_vis[j, :np.prod(size)].reshape(size).as_numpy_array()
for j in range(fantasy_vis.shape[0])]
visual = misc.norm01(misc.pack(imgs))
if display:
pylab.figure(figname)
pylab.matshow(visual, cmap='gray', fignum=False)
pylab.title(figtitle)
return visual
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True,
figname='Gibbs chains', figtitle='Gibbs chains'):
samples = gnp.zeros((num_particles, num_samples, state.v.shape[1]))
state = state[:num_particles, :, :]
for i in range(num_samples):
samples[:, i, :] = rbm.vis_expectations(state.h)
for j in range(show_every):
state = rbm.step(state)
npix = dataset.num_rows * dataset.num_cols
rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array()
for j in range(num_samples)],
normalize=False)
for i in range(num_particles)]
grid = vm.vjoin(rows, normalize=False)
if display:
pylab.figure(figname)
pylab.matshow(grid, cmap='gray', fignum=False)
pylab.title(figtitle)
pylab.gcf().canvas.draw()
return grid
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def plotstuff():
X__ = np.load("tm_X.npy")
S_pred = np.load("tm_S_pred.npy")
E_pred = np.load("tm_E_pred.npy")
M = np.load("tm_M.npy")
pl.ioff()
pl.suptitle("mode: %s (X: FM input, state pred: FM output)" % ("bluib"))
pl.subplot(511)
pl.title("X[goals]")
pl.plot(X__[10:,0:4], "-x")
pl.subplot(512)
pl.title("X[prediction error]")
pl.plot(X__[10:,4:], "-x")
pl.subplot(513)
pl.title("state pred")
pl.plot(S_pred)
pl.subplot(514)
pl.title("error state - goal")
pl.plot(E_pred)
pl.subplot(515)
pl.title("state")
pl.plot(M)
pl.show()
def rh_model_plot(self):
"""prepare and plot model outputs over input variations from sweep"""
assert hasattr(self, "X_model_sweep")
assert hasattr(self, "Y_model_sweep")
print "%s.rh_plot_model sweepsteps = %d" % (self.__class__.__name__, self.X_model_sweep.shape[0])
print "%s.rh_plot_model environment = %s" % (self.__class__.__name__, self.environment)
print "%s.rh_plot_model environment proprio dims = %d" % (self.__class__.__name__, self.environment.conf.m_ndims)
# scatter_data_raw = np.hstack((self.X_model_sweep[:,1:], self.Y_model_sweep))
# scatter_data_cols = ["X%d" % i for i in range(1, self.X_model_sweep.shape[1])]
# scatter_data_cols += ["Y%d" % i for i in range(self.Y_model_sweep.shape[1])]
# print "scatter_data_raw", scatter_data_raw.shape
# # df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
# df = pd.DataFrame(scatter_data_raw, columns=scatter_data_cols)
title = "%s, input/output sweep of model %s at time %d" % (self.mode, self.model, -1)
# plot_scattermatrix(df)
# plot_scattermatrix_reduced(df)
plot_colormeshmatrix_reduced(self.X_model_sweep, self.Y_model_sweep, ymin = -1.0, ymax = 1.0, title = title)
################################################################################
def plot_scattermatrix(df, title = "plot_scattermatrix"):
"""plot a scattermatrix of dataframe df"""
if df is None:
print "plot_scattermatrix: no data passed"
return
from pandas.tools.plotting import scatter_matrix
# df = pd.DataFrame(X, columns=['x1_t', 'x2_t', 'x1_tptau', 'x2_tptau', 'u_t'])
# scatter_data_raw = np.hstack((np.array(Xs), np.array(Ys)))
# scatter_data_raw = np.hstack((Xs, Ys))
# print "scatter_data_raw", scatter_data_raw.shape
pl.ioff()
# df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
sm = scatter_matrix(df, alpha=0.2, figsize=(10, 10), diagonal='hist')
fig = sm[0,0].get_figure()
fig.suptitle(title)
if SAVEPLOTS:
fig.savefig("fig_%03d_scattermatrix.pdf" % (fig.number), dpi=300)
fig.show()
# pl.show()
def main():
data = pd.read_table('../Real_Values.txt').get_values()
x = [float(d) for d in data]
test = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860])
n_predict = 100
extrapolation = fourierExtrapolation(x, n_predict)
pl.figure()
pl.plot(np.arange(len(x), len(extrapolation) + len(x)), extrapolation, 'r', label = 'extrapolation')
pl.plot(x, 'b', label = 'Given Data', linewidth = 3)
pl.legend()
pl.ylabel('BPM')
pl.xlabel('Sample')
pl.title('Fourier Extrapolation')
pl.savefig('FourierExtrapolation.png')
#pl.show()
with open('Fourier_PredValues.txt', 'w') as out:
out.write(str([e for e in extrapolation]).strip('[]'))
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
""" Plot multiples ROC curves as separate at the same painting area. """
pylab.clf()
pylab.title(title)
for ix, r in enumerate(rocList):
ax = pylab.subplot(4,4,ix+1)
pylab.ylim((0,1))
pylab.xlim((0,1))
ax.set_yticklabels([])
ax.set_xticklabels([])
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
if not labels:
labels = ['' for x in rocList]
pylab.text(0.2,0.1,labels[ix],fontsize=8)
pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)
pylab.show()
def plot(self,title='',include_baseline=False,equal_aspect=True):
""" Method that generates a plot of the ROC curve
Parameters:
title: Title of the chart
include_baseline: Add the baseline plot line if it's True
equal_aspect: Aspects to be equal for all plot
"""
pylab.clf()
pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
if include_baseline:
pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
pylab.ylim((0,1))
pylab.xlim((0,1))
pylab.xticks(pylab.arange(0,1.1,.1))
pylab.yticks(pylab.arange(0,1.1,.1))
pylab.grid(True)
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
pylab.xlabel('1 - Specificity')
pylab.ylabel('Sensitivity')
pylab.title(title)
pylab.show()
def plot_clusters_pca(responsibilities, color_groups):
from sklearn.decomposition import RandomizedPCA
import pylab as pl
from random import shuffle
colors = list(colors_dict.values())
shuffle(colors)
pca = RandomizedPCA(n_components=2)
X = pca.fit_transform(responsibilities)
# print >>stderr, pca.explained_variance_ratio_
pl.figure()
pl.scatter(X[:, 0], X[:, 1], c="grey", label="unknown")
for c, sub, i in zip(colors, color_groups, count(0)):
pl.scatter(X[sub, 0], X[sub, 1], c=c, label=str(i))
pl.legend()
pl.title("PCA responsibility matrix")
pl.show()
def plot(func):
random_state = check_random_state(0)
one_core = []
multi_core = []
sample_sizes = range(1000, 6000, 1000)
for n_samples in sample_sizes:
X = random_state.rand(n_samples, 300)
start = time.time()
func(X, n_jobs=1)
one_core.append(time.time() - start)
start = time.time()
func(X, n_jobs=-1)
multi_core.append(time.time() - start)
pl.figure('scikit-learn parallel %s benchmark results' % func.__name__)
pl.plot(sample_sizes, one_core, label="one core")
pl.plot(sample_sizes, multi_core, label="multi core")
pl.xlabel('n_samples')
pl.ylabel('Time (s)')
pl.title('Parallel %s' % func.__name__)
pl.legend()
def plotAccuracyGraph(X, Y, Xlabel='Variable', Ylabel='Accuracy', graphTitle="Test Accuracy Graph", filename="graph.pdf"):
""" Plots and saves accuracy graphs """
try:
timestamp = int(time.time())
fig = P.figure(figsize=(8,5))
# Set the graph's title
P.title(graphTitle, fontname='monospace')
# Set the axes labels
P.xlabel(Xlabel, fontsize=12, fontname='monospace')
P.ylabel(Ylabel, fontsize=12, fontname='monospace')
# Add horizontal and vertical lines to the graph
P.grid(color='DarkGray', linestyle='--', linewidth=0.1, axis='both')
# Add the data to the graph
P.plot(X, Y, 'r-*', linewidth=1.0)
# Save figure
prettyPrint("Saving figure to ./%s" % filename)#(graphTitle.replace(" ","_"), timestamp))
P.tight_layout()
fig.savefig("./%s" % filename)#(graphTitle.replace(" ", "_"), timestamp))
except Exception as e:
prettyPrint("Error encountered in \"plotAccuracyGraph\": %s" % e, "error")
return False
return True
def ansQuest(maxTime,numTrials):
means=[]
distLists=performSim(maxTime,numTrials)
for t in range(maxTime+1):
tot=0.0
for distL in distLists:
tot+=distL[t]
means.append(tot/len(distL))
pylab.figure()
pylab.plot(means)
pylab.xlabel('distance')
pylab.ylabel('time')
pylab.title('Average Distance vs. Time ('+str(len(distLists))+'trials)')
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
# Receptive Fields Summary
try:
W = layer.W
except:
W = layer
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fig = mpl.figure(figOffset); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,np.shape(fields)[0]):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
try:
W = layer.output
except:
W = layer
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
# Receptive Fields Summary
W = layer.W
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
fieldsN = min(fields.shape[0],maxFields)
perRow = int(math.floor(math.sqrt(fieldsN)))
perColumn = int(math.ceil(fieldsN/float(perRow)))
fig = mpl.figure(figName); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,fieldsN):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
W = layer.output
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();