Python matplotlib.pylab.tight_layout() Examples
The following are 30
code examples of matplotlib.pylab.tight_layout().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pylab
, or try the search function
.
Example #1
Source File: plot_errors_boxplot.py From MDI with MIT License | 7 votes |
def plot(params_dir): model_dirs = [name for name in os.listdir(params_dir) if os.path.isdir(os.path.join(params_dir, name))] df = defaultdict(list) for model_dir in model_dirs: df[re.sub('_bin_scaled_mono_True_ratio', '', model_dir)] = [ dd.io.load(path)['best_epoch']['validate_objective'] for path in glob.glob(os.path.join( params_dir, model_dir) + '/*.h5')] df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in df.iteritems()])) df.to_csv(os.path.basename(os.path.normpath(params_dir))) plt.figure(figsize=(16, 4), dpi=300) g = sns.boxplot(df) g.set_xticklabels(df.columns, rotation=45) plt.tight_layout() plt.savefig('{}_errors_box_plot.png'.format( os.path.join(IMAGES_DIRECTORY, os.path.basename(os.path.normpath(params_dir)))))
Example #2
Source File: resnet_wgan_gp_cifar10_train.py From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License | 6 votes |
def plot_losses(losses_d, losses_g, filename): losses_d = np.array(losses_d) fig, axes = plt.subplots(3, 2, figsize=(8, 8)) axes = axes.flatten() axes[0].plot(losses_d[:, 0]) axes[1].plot(losses_d[:, 1]) axes[2].plot(losses_d[:, 2]) axes[3].plot(losses_d[:, 3]) axes[4].plot(losses_g) axes[0].set_title("losses_d") axes[1].set_title("losses_d_real") axes[2].set_title("losses_d_fake") axes[3].set_title("losses_d_gp") axes[4].set_title("losses_g") plt.tight_layout() plt.savefig(filename) plt.close()
Example #3
Source File: utils.py From ndvr-dml with Apache License 2.0 | 6 votes |
def plot_pr_curve(pr_curve_dml, pr_curve_base, title): """ Function that plots the PR-curve. Args: pr_curve: the values of precision for each recall value title: the title of the plot """ plt.figure(figsize=(16, 9)) plt.plot(np.arange(0.0, 1.05, 0.05), pr_curve_base, color='r', marker='o', linewidth=3, markersize=10) plt.plot(np.arange(0.0, 1.05, 0.05), pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10) plt.grid(True, linestyle='dotted') plt.xlabel('Recall', color='k', fontsize=27) plt.ylabel('Precision', color='k', fontsize=27) plt.yticks(color='k', fontsize=20) plt.xticks(color='k', fontsize=20) plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title(title, color='k', fontsize=27) plt.tight_layout() plt.show()
Example #4
Source File: audio.py From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License | 6 votes |
def plot_spectrogram_to_numpy(spectrogram): spectrogram = spectrogram.transpose(1, 0) fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = _save_figure_to_numpy(fig) plt.close() return data #################### # PLOT SPECTROGRAM # ####################
Example #5
Source File: plotting_utils.py From nonparaSeq2seqVC_code with MIT License | 6 votes |
def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #6
Source File: plotting_utils.py From fac-via-ppg with Apache License 2.0 | 6 votes |
def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #7
Source File: plot.py From Tacotron2-PyTorch with MIT License | 6 votes |
def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #8
Source File: plotting_utils.py From nonparaSeq2seqVC_code with MIT License | 6 votes |
def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #9
Source File: helpers.py From NeMo with Apache License 2.0 | 6 votes |
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs): fig, ax = plt.subplots(figsize=(12, 3)) ax.scatter( range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target', ) ax.scatter( range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted', ) plt.xlabel("Frames (Green target, Red predicted)") plt.ylabel("Gate State") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #10
Source File: dataset.py From Image-Restoration with MIT License | 6 votes |
def show_pred(images, predictions, ground_truth): # choose 10 indice from images and visualize them indice = [np.random.randint(0, len(images)) for i in range(40)] for i in range(0, 40): plt.figure() plt.subplot(1, 3, 1) plt.tight_layout() plt.title('deformed image') plt.imshow(images[indice[i]]) plt.subplot(1, 3, 2) plt.tight_layout() plt.title('predicted mask') plt.imshow(predictions[indice[i]]) plt.subplot(1, 3, 3) plt.tight_layout() plt.title('ground truth label') plt.imshow(ground_truth[indice[i]]) plt.show() # Load Data Science Bowl 2018 training dataset
Example #11
Source File: resnet_wgan_cifar10_train.py From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License | 5 votes |
def plot_losses(losses_d, losses_g, filename): losses_d = np.array(losses_d) fig, axes = plt.subplots(2, 2, figsize=(8, 8)) axes = axes.flatten() axes[0].plot(losses_d[:, 0]) axes[1].plot(losses_d[:, 1]) axes[2].plot(losses_d[:, 2]) axes[3].plot(losses_g) axes[0].set_title("losses_d") axes[1].set_title("losses_d_real") axes[2].set_title("losses_d_fake") axes[3].set_title("losses_g") plt.tight_layout() plt.savefig(filename) plt.close()
Example #12
Source File: plot.py From Tacotron2-PyTorch with MIT License | 5 votes |
def plot_spectrogram_to_numpy(spectrogram): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #13
Source File: dcgan_cifar10_train.py From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License | 5 votes |
def plot_losses(losses_d, losses_g, filename): fig, axes = plt.subplots(1, 2, figsize=(8, 2)) axes[0].plot(losses_d) axes[1].plot(losses_g) axes[0].set_title("losses_d") axes[1].set_title("losses_g") plt.tight_layout() plt.savefig(filename) plt.close()
Example #14
Source File: plotting_utils.py From fac-via-ppg with Apache License 2.0 | 5 votes |
def plot_spectrogram_to_numpy(spectrogram): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #15
Source File: plotting_utils.py From fac-via-ppg with Apache License 2.0 | 5 votes |
def plot_ppg_to_numpy(ppg): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(ppg, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Phonemes") plt.ylabel("Time") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #16
Source File: plotting_utils.py From fac-via-ppg with Apache License 2.0 | 5 votes |
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs): fig, ax = plt.subplots(figsize=(12, 3)) ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target') ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted') plt.xlabel("Frames (Green target, Red predicted)") plt.ylabel("Gate State") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #17
Source File: general_utils.py From DeepLearningImplementations with MIT License | 5 votes |
def plot_batch(color_model, q_ab, X_batch_black, X_batch_color, batch_size, h, w, nb_q, epoch): # Format X_colorized X_colorized = color_model.predict(X_batch_black / 100.)[:, :, :, :-1] X_colorized = X_colorized.reshape((batch_size * h * w, nb_q)) X_colorized = q_ab[np.argmax(X_colorized, 1)] X_a = X_colorized[:, 0].reshape((batch_size, 1, h, w)) X_b = X_colorized[:, 1].reshape((batch_size, 1, h, w)) X_colorized = np.concatenate((X_batch_black, X_a, X_b), axis=1).transpose(0, 2, 3, 1) X_colorized = [np.expand_dims(color.lab2rgb(im), 0) for im in X_colorized] X_colorized = np.concatenate(X_colorized, 0).transpose(0, 3, 1, 2) X_batch_color = [np.expand_dims(color.lab2rgb(im.transpose(1, 2, 0)), 0) for im in X_batch_color] X_batch_color = np.concatenate(X_batch_color, 0).transpose(0, 3, 1, 2) list_img = [] for i, img in enumerate(X_colorized[:min(32, batch_size)]): arr = np.concatenate([X_batch_color[i], np.repeat(X_batch_black[i] / 100., 3, axis=0), img], axis=2) list_img.append(arr) plt.figure(figsize=(20,20)) list_img = [np.concatenate(list_img[4 * i: 4 * (i + 1)], axis=2) for i in range(len(list_img) // 4)] arr = np.concatenate(list_img, axis=1) plt.imshow(arr.transpose(1,2,0)) ax = plt.gca() ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) plt.tight_layout() plt.savefig("../../figures/fig_epoch%s.png" % epoch) plt.clf() plt.close()
Example #18
Source File: general_utils.py From DeepLearningImplementations with MIT License | 5 votes |
def plot_batch_eval(color_model, q_ab, X_batch_black, X_batch_color, batch_size, h, w, nb_q, T): # Format X_colorized X_colorized = color_model.predict(X_batch_black / 100.)[:, :, :, :-1] X_colorized = X_colorized.reshape((batch_size * h * w, nb_q)) # Reweight probas X_colorized = np.exp(np.log(X_colorized) / T) X_colorized = X_colorized / np.sum(X_colorized, 1)[:, np.newaxis] # Reweighted q_a = q_ab[:, 0].reshape((1, 313)) q_b = q_ab[:, 1].reshape((1, 313)) X_a = np.sum(X_colorized * q_a, 1).reshape((batch_size, 1, h, w)) X_b = np.sum(X_colorized * q_b, 1).reshape((batch_size, 1, h, w)) X_colorized = np.concatenate((X_batch_black, X_a, X_b), axis=1).transpose(0, 2, 3, 1) X_colorized = [np.expand_dims(color.lab2rgb(im), 0) for im in X_colorized] X_colorized = np.concatenate(X_colorized, 0).transpose(0, 3, 1, 2) X_batch_color = [np.expand_dims(color.lab2rgb(im.transpose(1, 2, 0)), 0) for im in X_batch_color] X_batch_color = np.concatenate(X_batch_color, 0).transpose(0, 3, 1, 2) list_img = [] for i, img in enumerate(X_colorized[:min(32, batch_size)]): arr = np.concatenate([X_batch_color[i], np.repeat(X_batch_black[i] / 100., 3, axis=0), img], axis=2) list_img.append(arr) plt.figure(figsize=(20,20)) list_img = [np.concatenate(list_img[4 * i: 4 * (i + 1)], axis=2) for i in range(len(list_img) // 4)] arr = np.concatenate(list_img, axis=1) plt.imshow(arr.transpose(1,2,0)) ax = plt.gca() ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) plt.tight_layout() plt.show()
Example #19
Source File: eval.py From DeepLearningImplementations with MIT License | 5 votes |
def plot_results(list_log, to_plot="losses"): list_color = [u'#E24A33', u'#348ABD', u'#FBC15E', u'#777777', u'#988ED5', u'#8EBA42', u'#FFB5B8'] plt.figure() for idx, log in enumerate(list_log): with open(log, "r") as f: d = json.load(f) experiment_name = d["experiment_name"] color = list_color[idx] plt.plot(d["train_%s" % to_plot], color=color, linewidth=3, label="Train %s" % experiment_name) plt.plot(d["val_%s" % to_plot], color=color, linestyle="--", linewidth=3,) plt.ylabel(to_plot, fontsize=20) if to_plot == "losses": plt.yscale("log") if to_plot == "accs": plt.ylim([0, 1.1]) plt.xlabel("Number of epochs", fontsize=20) plt.title("%s experiment" % dataset, fontsize=22) plt.legend(loc="best") plt.tight_layout() plt.savefig("./figures/%s_results_%s.png" % (dataset, to_plot)) plt.show()
Example #20
Source File: Time Series Analysis.py From python-urbanPlanning with MIT License | 5 votes |
def plotModelResults(model, X_train, X_test,y_train,y_test, plot_intervals=False, plot_anomalies=False, scale=1.96): """ Plots modelled vs fact values, prediction intervals and anomalies """ prediction = model.predict(X_test) plt.figure(figsize=(15, 7)) plt.plot(prediction, "g", label="prediction", linewidth=2.0) plt.plot(y_test.values, label="actual", linewidth=2.0) if plot_intervals: cv = cross_val_score(model, X_train, y_train, cv=tscv, scoring="neg_mean_squared_error") #mae = cv.mean() * (-1) deviation = np.sqrt(cv.std()) lower = prediction - (scale * deviation) upper = prediction + (scale * deviation) plt.plot(lower, "r--", label="upper bond / lower bond", alpha=0.5) plt.plot(upper, "r--", alpha=0.5) if plot_anomalies: anomalies = np.array([np.NaN]*len(y_test)) anomalies[y_test<lower] = y_test[y_test<lower] anomalies[y_test>upper] = y_test[y_test>upper] plt.plot(anomalies, "o", markersize=10, label = "Anomalies") error = mean_absolute_percentage_error(prediction, y_test) plt.title("Mean absolute percentage error {0:.2f}%".format(error)) plt.legend(loc="best") plt.tight_layout() plt.grid(True);
Example #21
Source File: monitor.py From cortex_old with GNU General Public License v3.0 | 5 votes |
def save(self, out_path): '''Saves a figure for the monitor Args: out_path: str ''' plt.clf() np.set_printoptions(precision=4) font = { 'size': 7 } matplotlib.rc('font', **font) y = 2 x = ((len(self.d) - 1) // y) + 1 fig, axes = plt.subplots(y, x) fig.set_size_inches(20, 8) for j, (k, v) in enumerate(self.d.iteritems()): ax = axes[j // x, j % x] ax.plot(v, label=k) if k in self.d_valid.keys(): ax.plot(self.d_valid[k], label=k + '(valid)') ax.set_title(k) ax.legend() plt.tight_layout() plt.savefig(out_path, facecolor=(1, 1, 1)) plt.close()
Example #22
Source File: evaluation.py From deepecg with MIT License | 5 votes |
def plot_confusion_matrix(y_true, y_pred, classes, figure_size=(8, 8)): """This function plots a confusion matrix.""" # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100 # Build Laussen Labs colormap cmap = LinearSegmentedColormap.from_list('laussen_labs_green', ['w', '#43BB9B'], N=256) # Setup plot plt.figure(figsize=figure_size) # Plot confusion matrix plt.imshow(cm, interpolation='nearest', cmap=cmap) # Modify axes tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) thresh = cm.max() / 1.5 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, str(np.round(cm[i, j], 2)) + ' %', horizontalalignment="center", color="white" if cm[i, j] > thresh else "black", fontsize=20) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.tight_layout() plt.ylabel('True Label', fontsize=25) plt.xlabel('Predicted Label', fontsize=25) plt.show()
Example #23
Source File: audio.py From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License | 5 votes |
def plot_spectrogram(spec, path): spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len) plt.gcf().clear() plt.figure(figsize=(12, 3)) plt.imshow(spec, aspect="auto", origin="lower") plt.colorbar() plt.tight_layout() plt.savefig(path, dpi=300, format="png") plt.close() #################### # PLOT EMBEDDING # ####################
Example #24
Source File: audio.py From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License | 5 votes |
def plot_embedding(spec, path): spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len) plt.gcf().clear() plt.figure(figsize=(12, 3)) plt.pcolormesh(spec, norm=SymLogNorm(linthresh=1e-3)) plt.colorbar() plt.tight_layout() plt.savefig(path, dpi=300, format="png") plt.close()
Example #25
Source File: resnet_rgan_cifar10_train.py From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License | 5 votes |
def plot_losses(losses_d, losses_g, filename): losses_d = np.array(losses_d) fig, axes = plt.subplots(1, 2, figsize=(8, 4)) axes = axes.flatten() axes[0].plot(losses_d) axes[1].plot(losses_g) axes[0].set_title("losses_d") axes[1].set_title("losses_g") plt.tight_layout() plt.savefig(filename) plt.close()
Example #26
Source File: utils.py From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License | 5 votes |
def plot_losses(losses_d, losses_g, filename): losses_d = np.array(losses_d) fig, axes = plt.subplots(2, 2, figsize=(8, 8)) axes = axes.flatten() axes[0].plot(losses_d[:, 0]) axes[1].plot(losses_d[:, 1]) axes[2].plot(losses_d[:, 2]) axes[3].plot(losses_g) axes[0].set_title("losses_d") axes[1].set_title("losses_d_real") axes[2].set_title("losses_d_fake") axes[3].set_title("losses_g") plt.tight_layout() plt.savefig(filename) plt.close()
Example #27
Source File: helpers.py From NeMo with Apache License 2.0 | 5 votes |
def plot_spectrogram_to_numpy(spectrogram): fig, ax = plt.subplots(figsize=(12, 3)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) plt.xlabel("Frames") plt.ylabel("Channels") plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #28
Source File: helpers.py From NeMo with Apache License 2.0 | 5 votes |
def plot_alignment_to_numpy(alignment, info=None): fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if info is not None: xlabel += '\n\n' + info plt.xlabel(xlabel) plt.ylabel('Encoder timestep') plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data
Example #29
Source File: dataset.py From UNet-pytorch with MIT License | 5 votes |
def show_batch(sample_batched): """Show image with landmarks for a batch of samples.""" images_batch, masks_batch = sample_batched['image'].numpy().astype(np.uint8), sample_batched['mask'].numpy().astype(np.bool) batch_size = len(images_batch) for i in range(batch_size): plt.figure() plt.subplot(1, 2, 1) plt.tight_layout() plt.imshow(images_batch[i].transpose((1, 2, 0))) plt.subplot(1, 2, 2) plt.tight_layout() plt.imshow(np.squeeze(masks_batch[i].transpose((1, 2, 0)))) # Load Data Science Bowl 2018 training dataset
Example #30
Source File: plotting.py From melgan with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_waveform_to_numpy(waveform): fig, ax = plt.subplots(figsize=(12, 3)) ax.plot() ax.plot(range(len(waveform)), waveform, linewidth=0.1, alpha=0.7, color='blue') plt.xlabel("Samples") plt.ylabel("Amplitude") plt.ylim(-1, 1) plt.tight_layout() fig.canvas.draw() data = save_figure_to_numpy(fig) plt.close() return data