def ezrc(fontSize=22., lineWidth=2., labelSize=None, tickmajorsize=10,
tickminorsize=5, figsize=(8, 6)):
"""
slides - Define params to make pretty fig for slides
"""
from pylab import rc, rcParams
if labelSize is None:
labelSize = fontSize + 5
rc('figure', figsize=figsize)
rc('lines', linewidth=lineWidth)
rcParams['grid.linewidth'] = lineWidth
rcParams['font.sans-serif'] = ['Helvetica']
rcParams['font.serif'] = ['Helvetica']
rcParams['font.family'] = ['Times New Roman']
rc('font', size=fontSize, family='serif', weight='bold')
rc('axes', linewidth=lineWidth, labelsize=labelSize)
rc('legend', borderpad=0.1, markerscale=1., fancybox=False)
rc('text', usetex=True)
rc('image', aspect='auto')
rc('ps', useafm=True, fonttype=3)
rcParams['xtick.major.size'] = tickmajorsize
rcParams['xtick.minor.size'] = tickminorsize
rcParams['ytick.major.size'] = tickmajorsize
rcParams['ytick.minor.size'] = tickminorsize
rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
python类rcParams()的实例源码
def get_rcParams(self):
"""Get an rcParams dict for this theme.
Notes
-----
Subclasses should not need to override this method method as long as
self._rcParams is constructed properly.
rcParams are used during plotting. Sometimes the same theme can be
achieved by setting rcParams before plotting or a post_plot_callback
after plotting. The choice of how to implement it is is a matter of
convenience in that case.
There are certain things can only be themed after plotting. There
may not be an rcParam to control the theme or the act of plotting
may cause an entity to come into existence before it can be themed.
"""
rcParams = deepcopy(self._rcParams)
return rcParams
def plot_pairplots(data, labels, alpha, mis, column_label, topk=5, prefix='', focus=''):
cmap = sns.cubehelix_palette(as_cmap=True, light=.9)
plt.rcParams.update({'font.size': 32})
m, nv = mis.shape
for j in range(m):
inds = np.where(np.logical_and(alpha[j] > 0, mis[j] > 0.))[0]
inds = inds[np.argsort(- alpha[j, inds] * mis[j, inds])][:topk]
if focus in column_label:
ifocus = column_label.index(focus)
if not ifocus in inds:
inds = np.insert(inds, 0, ifocus)
if len(inds) >= 2:
plt.clf()
subdata = data[:, inds]
columns = [column_label[i] for i in inds]
subdata = pd.DataFrame(data=subdata, columns=columns)
try:
sns.pairplot(subdata, kind="reg", diag_kind="kde", size=5, dropna=True)
filename = '{}/pairplots_regress/group_num={}.pdf'.format(prefix, j)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
plt.suptitle("Latent factor {}".format(j), y=1.01)
plt.savefig(filename, bbox_inches='tight')
plt.clf()
except:
pass
subdata['Latent factor'] = labels[:,j]
try:
sns.pairplot(subdata, kind="scatter", dropna=True, vars=subdata.columns.drop('Latent factor'), hue="Latent factor", diag_kind="kde", size=5)
filename = '{}/pairplots/group_num={}.pdf'.format(prefix, j)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
plt.suptitle("Latent factor {}".format(j), y=1.01)
plt.savefig(filename, bbox_inches='tight')
plt.close('all')
except:
pass
def show_annotations(self, pic_path, annotations):
if self.are_legal_anotations(annotations):
pylab.rcParams['figure.figsize'] = (10.0, 8.0)
read_img = io.imread(pic_path)
plt.figure()
plt.imshow(read_img)
self.coco.showAnns(annotations)
else:
print 'cannot show invalid annotation'
def theme(ax=None, minorticks=False):
""" update plot to make it nice and uniform """
from matplotlib.ticker import AutoMinorLocator
from pylab import rcParams, gca, tick_params
if minorticks:
if ax is None:
ax = gca()
ax.yaxis.set_minor_locator(AutoMinorLocator())
ax.xaxis.set_minor_locator(AutoMinorLocator())
tick_params(which='both', width=rcParams['lines.linewidth'])
def apply(self):
self._rcstate = deepcopy(plt.rcParams)
plt.rcParams.update(**self.get_rcParams())
def restore(self):
plt.rcParams.update(self._rcstate)
def __exit__(self, *args, **kwargs):
self.post_callback()
plt.rcParams.update(self._rcstate)
def __init__(self, fontSize=16., lineWidth=1., labelSize=None,
tickmajorsize=10, tickminorsize=5, figsize=(8, 6)):
if labelSize is None:
labelSize = fontSize + 2
rcParams = {}
rcParams['figure.figsize'] = figsize
rcParams['lines.linewidth'] = lineWidth
rcParams['grid.linewidth'] = lineWidth
rcParams['font.sans-serif'] = ['Helvetica']
rcParams['font.serif'] = ['Helvetica']
rcParams['font.family'] = ['Times New Roman']
rcParams['font.size'] = fontSize
rcParams['font.family'] = 'serif'
rcParams['font.weight'] = 'bold'
rcParams['axes.linewidth'] = lineWidth
rcParams['axes.labelsize'] = labelSize
rcParams['legend.borderpad'] = 0.1
rcParams['legend.markerscale'] = 1.
rcParams['legend.fancybox'] = False
rcParams['text.usetex'] = True
rcParams['image.aspect'] = 'auto'
rcParams['ps.useafm'] = True
rcParams['ps.fonttype'] = 3
rcParams['xtick.major.size'] = tickmajorsize
rcParams['xtick.minor.size'] = tickminorsize
rcParams['ytick.major.size'] = tickmajorsize
rcParams['ytick.minor.size'] = tickminorsize
rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
super(self.__class__, self).__init__(**rcParams)
plt.ion()
def __init__(self, fontSize=None, labelSize=None):
rcParams = {}
if fontSize is not None:
if labelSize is None:
labelSize = fontSize
rcParams['font.sans-serif'] = ['Helvetica']
rcParams['font.serif'] = ['Helvetica']
rcParams['font.family'] = ['Times New Roman']
rcParams['font.size'] = fontSize
rcParams["axes.labelsize"] = labelSize
rcParams["axes.titlesize"] = labelSize
rcParams["xtick.labelsize"] = labelSize
rcParams["ytick.labelsize"] = labelSize
rcParams["legend.fontsize"] = fontSize
rcParams['font.family'] = 'serif'
rcParams['font.weight'] = 'bold'
rcParams['axes.labelsize'] = labelSize
rcParams['text.usetex'] = True
rcParams['ps.useafm'] = True
rcParams['ps.fonttype'] = 3
rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
super(self.__class__, self).__init__(**rcParams)
plt.ion()
def main():
HASH_IMG_NAME = True
pylab.rcParams['figure.figsize'] = (10.0, 8.0)
json.encoder.FLOAT_REPR = lambda o: format(o, '.3f')
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inputfile", type=str, required=True,
help='File containing model-generated/hypothesis sentences.')
parser.add_argument("-r", "--references", type=str, required=True,
help='JSON File containing references/groundtruth sentences.')
args = parser.parse_args()
prediction_file = args.inputfile
reference_file = args.references
json_predictions_file = '{0}.json'.format(prediction_file)
crf = CocoResFormat()
crf.read_file(prediction_file, HASH_IMG_NAME)
crf.dump_json(json_predictions_file)
# create coco object and cocoRes object.
coco = COCO(reference_file)
cocoRes = coco.loadRes(json_predictions_file)
# create cocoEval object.
cocoEval = COCOEvalCap(coco, cocoRes)
# evaluate results
cocoEval.evaluate()
# print output evaluation scores
for metric, score in cocoEval.eval.items():
print '%s: %.3f'%(metric, score)
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8, title=''):
ns, n = data.shape
if labels is None:
labels = map(str, range(n))
ncol = 5
nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))
fig, axs = pylab.subplots(nrow, ncol)
fig.set_size_inches(5 * ncol, 5 * nrow)
pairs = list(combinations(range(n), 2))
if colors is not None:
colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors))
for ax, pair in zip(axs.flat, pairs):
diff_x = max(data[:, pair[0]]) - min(data[:, pair[0]])
diff_y = max(data[:, pair[1]]) - min(data[:, pair[1]])
ax.set_xlim([min(data[:, pair[0]]) - 0.05 * diff_x, max(data[:, pair[0]]) + 0.05 * diff_x])
ax.set_ylim([min(data[:, pair[1]]) - 0.05 * diff_y, max(data[:, pair[1]]) + 0.05 * diff_y])
ax.scatter(data[:, pair[0]], data[:, pair[1]], c=colors, cmap=pylab.get_cmap("jet"),
marker='.', alpha=alpha, edgecolors='none', vmin=0, vmax=1)
ax.set_xlabel(shorten(labels[pair[0]]))
ax.set_ylabel(shorten(labels[pair[1]]))
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.scatter(data[:, 0], data[:, 1], marker='.')
fig.suptitle(title, fontsize=16)
pylab.rcParams['font.size'] = 12 #6
# pylab.draw()
# fig.set_tight_layout(True)
pylab.tight_layout()
pylab.subplots_adjust(top=0.95)
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.set_visible(False)
filename = outfile + '.png'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
fig.savefig(outfile + '.png')
pylab.close('all')
return True
# Hierarchical graph visualization utilities
def __init__(self, filename, remove_bkg='constant', bkg_box_size=50,
contour_threshold=3., min_points=10, shape_cut=0.2,
area_cut=10., radius_dev_cut=0.5, connectivity_angle=3.,
output_path=None):
hdulist = fits.open(filename)
raw_image = hdulist[0].data.astype(np.float64)
hdulist.close()
# Raw image.
self.raw_image = raw_image
# Background structure and background map
self._bkg = None
self.background_map = None
# Background removed image.
self.image = None
# Raw edges
self.raw_borders = None
# Filtered edges, so streak, by their morphologies and
# also connected (i.e. linked) by their slope.
self.streaks = None
# Statistics for the image data.
self._med = None
self._std = None
# Other variables.
remove_bkg_options = ('constant', 'map')
if remove_bkg not in remove_bkg_options:
raise RuntimeError('"remove_bkg" must be the one among: %s' %
', '.join(remove_bkg_options))
self.remove_bkg = remove_bkg
self.bkg_box_size = bkg_box_size
self.contour_threshold = contour_threshold
# These variables for the edge detections and linking.
self.min_points = min_points
self.shape_cut = shape_cut
self.area_cut = area_cut
self.radius_dev_cut = radius_dev_cut
self.connectivity_angle = connectivity_angle
# Set output path.
if output_path is None:
output_path = './%s/' % \
('.'.join(os.path.basename(filename).split('.')[:-1]))
if output_path[-1] != '/':
output_path += '/'
self.output_path = output_path
# For plotting.
pl.rcParams['figure.figsize'] = [12, 9]
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8):
ns, n = data.shape
if labels is None:
labels = list(map(str, range(n)))
ncol = 5
# ncol = 4
nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))
#nrow=1
#pylab.rcParams.update({'figure.autolayout': True})
fig, axs = pylab.subplots(nrow, ncol)
fig.set_size_inches(5 * ncol, 5 * nrow)
#fig.set_canvas(pylab.gcf().canvas)
pairs = list(combinations(range(n), 2)) #[:4]
pairs = sorted(pairs, key=lambda q: q[0]**2+q[1]**2) # Puts stronger relationships first
if colors is not None:
colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors)).clip(1e-7)
for ax, pair in zip(axs.flat, pairs):
if latent is None:
ax.scatter(data[:, pair[0]], data[:, pair[1]], marker='.', edgecolors='none', alpha=alpha)
else:
# cs = 'rgbcmykrgbcmyk'
markers = 'x+.o,<>^^<>,+x.'
for j, ind in enumerate(np.unique(latent)):
inds = (latent == ind)
ax.scatter(data[inds, pair[0]], data[inds, pair[1]], c=colors[inds], cmap=pylab.get_cmap("jet"),
marker=markers[j], alpha=0.5, edgecolors='none', vmin=0, vmax=1)
ax.set_xlabel(shorten(labels[pair[0]]))
ax.set_ylabel(shorten(labels[pair[1]]))
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.scatter(data[:, 0], data[:, 1], marker='.')
pylab.rcParams['font.size'] = 12 #6
pylab.draw()
#fig.set_tight_layout(True)
fig.tight_layout()
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.set_visible(False)
filename = outfile + '.png'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
fig.savefig(outfile + '.png') #df')
pylab.close('all')
return True