def plot_clusters(clusters: List[List[Point]], cents: List[Point]): cmap = get_cmap(10) for cluster_number, cluster in enumerate(clusters) : for point in cluster: plt.scatter( x = point.x, y = point.y, c = cmap(cluster_number)) current_cent = cents[cluster_number] plt.scatter( x = current_cent.x, y = current_cent.y, c = 'black') plt.show()
im_dim_batches = [ torch.cat((im_dim_list[i * args.batch_size:min( (i + 1) * args.batch_size, len(im_batches))])) for i in range(num_batches) ] output = [] for i, batch in enumerate(im_batches): start = time.time() with torch.no_grad(): prediction, _ = model(batch) prediction = utils.non_max_suppression(prediction, args.conf_thresh, args.nms_thresh) end = time.time() print("The inference time of batch %d is %.3f" % (i, end - start)) output.extend(prediction) colors = utils.get_cmap() for i in range(len(output)): if output[i] is not None: res = utils.recover_img_size(output[i], im_dim_list[i], args.img_size) list( map( lambda x: utils.draw_bounding_box(x, loaded_ims[i], colors, classes), res)) name = os.path.join(args.output_path, 'det_' + os.path.basename(imlist[i])) cv2.imwrite(name, loaded_ims[i])
show_title = False quiet = False for o, a in opts: if o == '-C': cmap = a elif o == '-t': ts = a.split(',') if len(ts) < 1: print("invalid timestep specification: {}".format(a)) sys.exit(-1) elif o == '-s': subplot = a elif o == '-T': show_title = True elif o == '-q': quiet = True elif o == '-h': usage() sys.exit(0) else: assert False, "unhandled option" cmap = get_cmap(cmap) for arg in args: heatmap(arg, np.array(ts, np.int32), subplot, quiet, show_title, cmap=cmap) if __name__ == '__main__': main()
sigmoidX = sigmoid(x*4) n, bins, patches = plt.hist(sigmoidX, 100, normed=1, facecolor='green', alpha=0.75) plt.xlabel('Pre-activation') plt.ylabel('Probability') plt.title('Histogram of Z - Prior Noise 4') plt.grid(True) plt.show() fig = plt.figure() ax = fig.add_subplot(111) cmap = get_cmap(10) colour_array = [] idx_array = np.zeros((10,1)) for s in xrange(10): idx_array[s,0] = s+1 colour_array.append(cmap(s+1)) plt.scatter(idx_array[:,0], idx_array[:,0], color=colour_array) # for x in idx_array[:,0]: # ax.annotate('%s'%x, x=x, textcoords='data') plt.grid() plt.show()
cmap = None # show last timestep by default ts = [-1] show_title = False quiet = False for o, a in opts: if o == '-c': cmap = a elif o == '-t': ts = a.split(',') if len(ts) < 1: print("invalid timestep specification: {}".format(a)) sys.exit(-1) elif o == '-T': show_title = True elif o == '-q': quiet = True elif o == '-h': usage() sys.exit(0) else: assert False, "unhandled option" for ddir in args: weights(ddir, np.array(ts, np.int32), quiet, show_title, get_cmap(cmap)) if __name__ == '__main__': main()
def compare_models(X, Z, K=2, figsize=(7, 12), cm="viridis"): """Run and compare diagonal EM, general EM and K-means on Iris dataset. Args: - K : number of clusters """ # Load Iris dataset N, d = X.shape true_K = len(np.unique(Z)) # Run all the models and get the plot features models = model_dict(X, Z, K) # Plot each model's results features_pairs = [(i, j) for j in range(d) for i in range(j)] fig, axes = plt.subplots( ncols=len(models), nrows=len(features_pairs), figsize=figsize ) for i, idx in enumerate(features_pairs): idx = np.array(idx) X_chosen = X[:, idx] for j, model_name in enumerate(models): if len(features_pairs) == 1: ax = axes[j] else: ax = axes[i, j] features = models[model_name] means = features["mean"][:, idx] covs = features["cov"] labels = features["labels"] K = len(np.unique(labels)) # Color for plots cmap = get_cmap(K, cm) if covs is not None: covs = covs[:, idx, :][:, :, idx] ax.scatter(*X_chosen.T, c=labels, s=10.0, edgecolors="k", lw=0.5, cmap=cm) # Set subplot title ax.set_title( "{} ({}, {})".format(model_name, idx[0], idx[1]), fontsize=10.0, y=0.96 ) ax.set_yticklabels([]) ax.set_xticklabels([]) for k in range(K): mean = means[k] # Plot the mean ax.scatter(*mean, s=70.0, edgecolors="w", c=np.array([cmap(k)])) # Plot the ellipses when possible if covs is not None: cov = covs[k] confidence_ellipse(mean, cov, ax, color=cmap(k), facecolor=cmap(k)) plt.show()
def eval_autoencoder_encode(autoencoder_name, model_weight_path, noise_flag, noise_level): print('============================') print('Initialize Model: {}_{}'.format(autoencoder_name, noise_flag)) print('============================') autoencoder = eval('{}(noise_flag={})'.format(autoencoder_name, noise_flag, noise_level)) autoencoder.load(model_weight_path) print('============================') print('Encode:') print('============================') z_test = autoencoder.encode(X_test) # the histogram of the latent representation n, bins, patches = plt.hist(z_test.flatten(), 100, normed=1, facecolor='green', alpha=0.75) plt.xlabel('Latent Variable Activation') plt.ylabel('Frequency') if noise_flag: plt.title('Histogram of Activation at Top Layer - Gaussian Noise = {}'.format(noise_level)) else: plt.title('Histogram of Activation at Top Layer - Gaussian Noise = {}'.format(noise_flag)) plt.grid(True) plt.show() z_mean = np.mean(z_test) z_median = np.median(z_test) # z_prop_high = float(np.sum(z_test>0.0))/z_test.shape[0] # z_prop_low = float(np.sum(z_test<=0.0))/z_test.shape[0] #q_array = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) #z_percentiles = np.percentile(z_test, q_array) print('Z mean: {}'.format(z_mean)) print('Z median: {}'.format(z_median)) #print('Z percentiles: {}'.format(zip(q_array, z_percentiles))) # tsne visualization of latent variables nExamples = 1000 cmap = get_cmap(10) colour_array = [] for s in xrange(nExamples): colour_array.append(cmap(y_test[s])) tsne_model = TSNE(n_components=2, perplexity=30, random_state=0) np.set_printoptions(suppress=True) tsne_vec = tsne_model.fit_transform(z_test[0:nExamples,:]) plt.scatter(tsne_vec[:,0], tsne_vec[:,1], color=colour_array, s=1) if noise_flag: plt.title('T-SNE of Activation at Top Layer - Gaussian Noise = {}'.format(noise_level)) else: plt.title('T-SNE of Activation at Top Layer - Gaussian Noise = {}'.format(noise_flag)) plt.show() cmap = get_cmap(10) colour_array = [] idx_array = np.zeros((10,1)) for s in xrange(10): idx_array[s,0] = s+1 colour_array.append(cmap(s+1)) plt.scatter(idx_array[:,0], idx_array[:,0], color=colour_array) plt.title('T-SNE of Activation at Top Layer - Colour Legend') plt.show()
cmap = a elif o == "-h": usage() sys.exit(0) elif o == "-s": subplot = a elif o == "-S": csteps = int(a) elif o == "-t": ts = a.split(",") if len(ts) < 1: print("invalid timestep specification: {}".format(a)) sys.exit(-1) elif o == "-T": show_title = True elif o == "-q": quiet = True elif o == "-w": wta = True else: assert False, "unhandled option" cmap = get_cmap(cmap, default="Blues") for ddir in args: force_fields(ddir, np.array(ts, np.int32), wta, continuous, csteps, subplot, quiet, show_title, cmap=cmap) if __name__ == "__main__": main()
except getopt.GetoptError, err: print(str(err)) usage() sys.exit(-1) if len(args) < 1: usage() sys.exit(-1) cmap = None quiet = False for o, a in opts: if o == '-C': cmap = a elif o == '-h': usage() sys.exit(0) elif o == '-q': quiet = True else: assert False, "unhandled option" cmap = get_cmap(cmap, default='Blues') for ddir in args: plot_output(ddir, quiet, cmap=cmap) if __name__ == '__main__': main()