def plot_components_2(X_projected, Y_projected, which_dimensions_to_plot, images=None, ax=None, image_scale=1, markersize=10, thumb_frac=0.05, cmap='gray'): # https://jakevdp.github.io/PythonDataScienceHandbook/05.10-manifold-learning.html # X_projected: rows are features and columns are samples # which_dimensions_to_plot: a list of two integers, index starting from 0 X_projected = np.vstack((X_projected[which_dimensions_to_plot[0], :], X_projected[which_dimensions_to_plot[1], :])) #--> only take two dimensions to plot X_projected = X_projected.T ax = ax or plt.gca() Y_projected = Y_projected.ravel() ax.plot(X_projected[Y_projected == 0, 0], X_projected[Y_projected == 0, 1], '.k', markersize=markersize) ax.plot(X_projected[Y_projected == 1, 0], X_projected[Y_projected == 1, 1], '.r', markersize=markersize) images = resize(images, (images.shape[0], images.shape[1]*image_scale, images.shape[2]*image_scale), order=5, preserve_range=True, mode="constant") if images is not None: min_dist_2 = (thumb_frac * max(X_projected.max(0) - X_projected.min(0))) ** 2 shown_images = np.array([2 * X_projected.max(0)]) for i in range(X_projected.shape[0]): dist = np.sum((X_projected[i] - shown_images) ** 2, 1) if np.min(dist) < min_dist_2: # don't show points that are too close continue shown_images = np.vstack([shown_images, X_projected[i]]) if Y_projected[i] == 0: imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(images[i], cmap=cmap), X_projected[i]) else: imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(images[i], cmap=cmap), X_projected[i], bboxprops =dict(edgecolor='red', lw=3)) ax.add_artist(imagebox) # # plot the first (original) image once more to be on top of other images: # # change color of frame (I googled: python OffsetImage highlight frame): https://stackoverflow.com/questions/40342379/show-images-in-a-plot-using-matplotlib-with-a-coloured-frame # imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(images[0], cmap=cmap), X_projected[0], bboxprops =dict(edgecolor='red')) # ax.add_artist(imagebox) plt.xlabel("dimension " + str(which_dimensions_to_plot[0] + 1), fontsize=13) plt.ylabel("dimension " + str(which_dimensions_to_plot[1] + 1), fontsize=13) plt.show()
def standardizePlot(ax, title, xlab, ylab, xlim=None, ylim=None, hline=True, legend=True, lblpressure=True, putimg=True, compliance=False): ax.axhline(linewidth=1, color='k', zorder=1) ax.set_xlabel(xlab) ax.set_ylabel(ylab) ax.set_title(title) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if legend: ax.legend(prop={'size': 8}) if lblpressure: ax.text(.15, -.2, "(ME Pressure)", ha='center', transform=axs.transAxes) ax.text(.85, -.2, "(IE Pressure)", ha='center', transform=axs.transAxes) if putimg: if compliance: MEy = 0.26 IEy = 0.26 else: MEy = 0.56 IEy = 0.44 arr_img = plt.imread(pjoin(Base_Folder, "MembraneForPressureME.png"), format='png') imagebox = mplob.OffsetImage(arr_img, zoom=0.08) imagebox.image.axes = ax ab = mplob.AnnotationBbox(imagebox, (0.15, MEy), xycoords='axes fraction', pad=0.5, frameon=False) ax.add_artist(ab) arr_img = plt.imread(pjoin(Base_Folder, "MembraneForPressureIE.png"), format='png') imagebox = mplob.OffsetImage(arr_img, zoom=0.08) imagebox.image.axes = ax ab = mplob.AnnotationBbox(imagebox, (0.85, IEy), xycoords='axes fraction', pad=0.5, frameon=False) ax.add_artist(ab)
def plot_embedding(X, imagepaths, collection_size, title=None, test_image=False, image_size=42): ''' Plots the images in the embedding space. The test image has red border. X: ndarray of float The distance matrix (2x2 for the 2D visualization). imagepaths: list of str A list containing all paths to the images. collection_size: int The number of images inside the collection. test_image: bool, default False If True, then we assume that the last vector in X corresponds to a test image, so we annotate it with a red box and the others with a black one. Otherwise, we annotate all images with a black box. image_size: int, default 42 The final size of the thumbnails to be shown in the plot will be (image_size, image_size). Kudos to georgeretsi for the code. ''' x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) #for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(names[i]),fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): #dist = np.sum((X[i] - shown_images) ** 2, 1) #if np.min(dist) < 4e-3: # don't show points that are too close # continue shown_images = np.r_[shown_images, [X[i]]] timg = cv2.imread(imagepaths[i]) timg = timg[:, :, ::-1] # BGR -> RGB timg = cv2.resize(timg, dsize=(image_size, image_size)) if (i == X.shape[0] - 1) and (test_image == True): imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(timg, cmap=plt.cm.gray_r), X[i], bboxprops=dict(edgecolor='red')) else: imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(timg, cmap=plt.cm.gray_r), X[i], bboxprops=dict(edgecolor='black')) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) plt.show(block=True)
def plot_embedding_annotation(emb, digits, threshold, ax=None, rescale=True): """ This function is used to visualize the learned low-d features We intend to see if we learn to disentangle factors of variations @emb : the input low-d feature @digits : the immage annotation of emb @threshold: minimal distances between two points """ # Rescaling if rescale: x_min, x_max = np.min(emb, 0), np.max(emb, 0) emb = (emb - x_min) / (x_max - x_min) _, ax = plt.subplots() if hasattr(offsetbox, 'AnnotationBbox'): mycanvas = np.array([[1., 1.]]) for i in range(digits.shape[0]): dist = np.sum((emb[i] - mycanvas)**2, 1) if np.min(dist) < threshold: # don't show points that are too close # You may try different threshold continue mycanvas = np.r_[mycanvas, [emb[i]]] imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage( digits[i], cmap=plt.cm.gray_r), emb[i], frameon=False) ax.add_artist(imagebox) ax.set_xticks([]) ax.set_yticks([]) return 0
def visualize(embed, x_test, y_test): feat = embed ax_min = np.min(embed, 0) ax_max = np.max(embed, 0) ax_dist_sq = np.sum((ax_max - ax_min)**2) plt.figure() ax = plt.gca() ax.grid(False) ax = plt.subplot(111) colormap = plt.get_cmap('tab10') shown_images = np.array([[1., 1.]]) for i in range(feat.shape[0]): dist = np.sum((feat[i] - shown_images)**2, 1) if np.min( dist ) < 3e-4 * ax_dist_sq: # don't show points that are too close continue shown_images = np.r_[shown_images, [feat[i]]] patch_to_color = np.expand_dims(x_test[i], -1) patch_to_color = np.tile(patch_to_color, (1, 1, 3)) patch_to_color = (1 - patch_to_color) * ( 1, 1, 1) + patch_to_color * colormap(y_test[i] / 10.)[:3] imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage( patch_to_color, zoom=0.5, cmap=plt.cm.gray_r), xy=feat[i], frameon=False) ax.add_artist(imagebox) plt.axis([ax_min[0], ax_max[0], ax_min[1], ax_max[1]]) plt.title('Embedding from the last layer of the network') plt.show()
def visualize(embed, x_test): # two ways of visualization: scale to fit [0,1] scale # feat = embed - np.min(embed, 0) # feat /= np.max(feat, 0) # two ways of visualization: leave with original scale feat = embed print('embed:',embed) ax_min = np.min(embed,0) ax_max = np.max(embed,0) print("max and min:",ax_max,ax_min ) ax_dist_sq = np.sum((ax_max-ax_min)**2) plt.figure() ax = plt.subplot(111) shown_images = np.array([[1., 1.]]) for i in range(feat.shape[0]): dist = np.sum((feat[i] - shown_images)**2, 1) if np.min(dist) < 3e-4*ax_dist_sq: # don't show points that are too close continue shown_images = np.r_[shown_images, [feat[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(x_test[i], zoom=0.6, cmap=plt.cm.gray_r), xy=feat[i], frameon=False ) ax.add_artist(imagebox) plt.axis([ax_min[0], ax_max[0], ax_min[1], ax_max[1]]) # plt.xticks([]), plt.yticks([]) plt.title('Embedding from the last layer of the network') plt.show()
def acquire_playerPic(player_id, zoom, offset=(250, 370)): try: img_path = os.getcwd() + '/' + str(player_id) + '.png' player_pic = plt.imread(img_path) except (ValueError, IOError): try: pic = urllib.urlretrieve( "http://stats.nba.com/media/players/230x185/" + str(player_id) + ".png", str(player_id) + ".png") player_pic = plt.imread(pic[0]) except (ValueError, IOError): try: pic = urllib.urlretrieve( "https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/" + str(player_id) + ".png", str(player_id) + ".png") player_pic = plt.imread(pic[0]) except (ValueError, IOError): img_path = os.getcwd() + '/chart_icon.png' player_pic = plt.imread(img_path) img = osb.OffsetImage(player_pic, zoom) img = osb.AnnotationBbox(img, offset, xycoords='data', pad=0.0, box_alignment=(1, 0), frameon=False) return img
def plot_embedding(Xp, y, imgs, title=None, figsize=(12, 4)): x_min, x_max = numpy.min(Xp, 0), numpy.max(Xp, 0) X = (Xp - x_min) / (x_max - x_min) fig, ax = plt.subplots(1, 2, figsize=figsize) for i in range(X.shape[0]): ax[0].text(X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={ 'weight': 'bold', 'size': 9 }) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = numpy.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = numpy.sum((X[i] - shown_images)**2, 1) if numpy.min(dist) < 4e-3: # don't show points that are too close continue shown_images = numpy.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(imgs[i], cmap=plt.cm.gray_r), X[i]) ax[0].add_artist(imagebox) ax[0].set_xticks([]), ax[0].set_yticks([]) ax[1].plot(Xp[:, 0], Xp[:, 1], '.') if title is not None: ax[0].set_title(title) return ax
def plot_mnist(X, y, X_embedded, name, min_dist=10.0): fig = figure(figsize=(10, 10)) ax = axes(frameon=False) title("\\textbf{MNIST dataset} -- Two-dimensional " "embedding of 70,000 handwritten digits with %s" % name) setp(ax, xticks=(), yticks=()) subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=0.9, wspace=0.0, hspace=0.0) scatter(X_embedded[:, 0], X_embedded[:, 1], c=y, marker="x") if min_dist is not None: from matplotlib import offsetbox shown_images = array([[15., 15.]]) indices = arange(X_embedded.shape[0]) random.shuffle(indices) for i in indices[:5000]: dist = sum((X_embedded[i] - shown_images)**2, 1) if min(dist) < min_dist: continue shown_images = np.r_[shown_images, [X_embedded[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(X[i].reshape(28, 28), cmap=cm.gray_r), X_embedded[i]) ax.add_artist(imagebox)
def plot_tsne_3D(X_tsne, images, labels, azim=120, distance=70000): fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111, projection=Axes3D.name) ax2d = fig.add_subplot(111, frame_on=False) ax2d.axis("off") ax.view_init(elev=30., azim=azim) for i in range(X_tsne.shape[0]): ax.scatter(X_tsne[i, 0], X_tsne[i, 1], X_tsne[i, 2], c=plt.cm.Set1(labels[i] / 10.), s=100) if hasattr(offsetbox, 'AnnotationBbox'): shown_images = np.array([[1., 1., 1.]]) for i in range(images.shape[0]): dist = np.sum((X_tsne[i] - shown_images)**2, 1) if np.min(dist) < distance: # don't show points that are too close continue shown_images = np.r_[shown_images, [X_tsne[i]]] image = Image.fromarray(images[i].reshape(28, 28), 'L') #inverted_image = PIL.ImageOps.invert(image) image.thumbnail((40, 40), Image.ANTIALIAS) imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(image), proj(X_tsne[i], ax, ax2d)) ax2d.add_artist(imagebox) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.title('t-SNE over the Fashion-MNIST') plt.savefig("/tmp/fashion/movie%d.png" % azim)
def plot_embedding(X,y,images, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) ly = float(len(set(y))) for i in range(X.shape[0]): circle = plt.Circle((X[i,0],X[i,1]),0.001,color=plt.cm.Set1(y[i]/ly)) ax.add_artist(circle) # plt.text(X[i, 0], X[i, 1], str(y[i]), # color=plt.cm.Set1(y[i] / 10.), # fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-4: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(st.resize(plt.imread(os.path.join(args.image_root,images[i])),(64,32)), cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def plot_components(data, model, images=None, ax=None, thumb_frac=0.05, cmap='gray'): ax = ax or plt.gca() proj = model.fit_transform(data) ax.plot(proj[:, 0], proj[:, 1], '.k') if images is not None: min_dist_2 = (thumb_frac * max(proj.max(0) - proj.min(0)))**2 shown_images = np.array([2 * proj.max(0)]) for i in range(0, data.shape[0]): dist = np.sum((proj[i] - shown_images)**2, 1) if np.min(dist) < min_dist_2: # dont show points that are too close continue shown_images = np.vstack([shown_images, proj[i]]) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(images[i], cmap=cmap), proj[i]) ax.add_artist(imagebox)
def plotScatter(X, title,minD): cm = plt.cm.get_cmap('RdYlBu') plt.scatter(X[:, 0], X[:, 1], c=trainLabel, s=3,cmap=cm) plt.colorbar() plt.title(title) plt.show() plt.figure() ax = plt.subplot(111) cm = plt.cm.get_cmap('RdYlBu') plt.scatter(X[:, 0], X[:, 1], c=trainLabel, s=3,cmap=cm) plt.colorbar() shown_images = np.array([[1., 1.]]) for i in range(trainImages.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < minD: continue shown_images = np.r_[shown_images, [X[i]]] if(trainLabel[i]==2): imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(trainImages[i].reshape(28, 28)),X[i]) ax.add_artist(imagebox) plt.title(title) plt.show()
def plot_embedding(X, labs, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], ('x' if labs[i] == 0 else 'o'), color=('green' if labs[i] == 0 else 'red'), fontdict={ 'weight': 'bold', 'size': 9 }) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(digits.data.shape[0]): dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i], bboxprops={'edgecolor': ('green' if labs[i] == 0 else 'red')}) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def plot_embedding_v2(X, X_origin, title=None, dims=[None, 28, 28]): dims[0] = X.shape[0] X_origin = X_origin.values.astype(np.float).reshape(dims) x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(y_train.values[i]), color=plt.cm.Set1(y_train.values.astype(np.int)[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 3e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(X_origin[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) plt.show()
def plot_embedding(X, y, images, title=None, figsize=(20, 20), img_size=(65, 65)): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure(figsize=figsize) ax = plt.subplot(111) colormap = plt.cm.gist_ncar colors = [colormap(i) for i in np.linspace(0, 1, len(set(y)))] for i in range(X.shape[0]): plt.scatter(X[i, 0], X[i, 1], color=colors[y[i]]) if hasattr(offsetbox, 'AnnotationBbox'): shown_images = np.array([[1., 1.]]) # just something big for i in range(images.shape[0]): dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 6e-3: ## don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] img = resize(images[i], img_size) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(img, cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def plot_embedding(X, label, origin_img, show_origin_image=False): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(label[i]), color=plt.cm.Set1(label[i] / 10.), fontdict={ 'weight': 'bold', 'size': 9 }) if show_origin_image and hasattr(offsetbox, 'AnnotationBbox'): shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 4e-3: continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(origin_img[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([])
def plot_components(data, proj, images=None, ax=None, thumb_frac=0.05, cmap='copper'): # scaler = MinMaxScaler(feature_range=(0,255)) ax = ax or plt.gca() ax.plot(proj[:, 0], proj[:, 1], '.k') if images is not None: min_dist_2 = (thumb_frac * max(proj.max(0) - proj.min(0)))**2 shown_images = np.array([2 * proj.max(0)]) for i in range(data.shape[0]): dist = np.sum((proj[i] - shown_images)**2, 1) if np.min(dist) < min_dist_2: # don't show points that are too close continue shown_images = np.vstack([shown_images, proj[i]]) # #Rescale images to be 0 to 255 # for channel in range(0,images.shape[1]): # scaler.fit(images[i,channel]) # scaler.fit_transform(images[i,channel]) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(images[i], zoom=.2, cmap=cmap), proj[i]) ax.add_artist(imagebox)
def plot_digits(X, digits, title=None, plot_box=True): colorlist = get_colors(10) # Scale and visualize the embedding vectors x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(digits.target[i]), color=colorlist[digits.target[i]], fontdict={'weight': 'medium', 'size': 'smaller'}) if plot_box and hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(digits.data.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-2: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) if title is not None: plt.title(title)
def plot_embedding(X, y, digits, title=None, annotation=True): """ :param X: [b, features] :param title: :return: """ x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) # for each point for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={'weight': 'normal', 'size': 10}) if hasattr(offsetbox, 'AnnotationBbox') and annotation: # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.plot(X[i, 0], X[i, 1]) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(digits.data.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) #if np.min(dist) < 4e-3: # # don't show points that are too close # continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(Y[i]), color=plt.cm.Set1(Y[i] / 10.), fontdict={ 'weight': 'bold', 'size': 9 }) if hasattr(offsetbox, 'AnnotationBbox'): shown_images = np.array([[1., 1.]]) for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 4e-3: continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]) plt.yticks([]) if title is not None: plt.title(title) plt.show()
def plot_embedding(X, imgnames, title=None): #K = 35 #rn_values = range(len(imgnames)) #shuffle(rn_values) #sample = rn_values[:K] #X = X[sample,:] #imgnames = imgnames[sample] x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) #for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(imgnames[i]),fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): #dist = np.sum((X[i] - shown_images) ** 2, 1) #if np.min(dist) < 4e-3: # don't show points that are too close # continue shown_images = np.r_[shown_images, [X[i]]] timg = misc.imread(imgnames[i]) timg = np.array(misc.imresize(timg, (70, 70, 3))) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(timg, cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) plt.show(block=True)
def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(train_target[i]), color=plt.cm.Set1(train_target[i] / 2.), fontdict={ 'weight': 'bold', 'size': 9 }) if hasattr(offsetbox, 'AnnotationBbox'): shown_images = np.array([[1., 1.]]) # just something big for i in range(show_instancees): dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] auctionbox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(images[train_target[i]], cmap=plt.cm.gray_r), X[i]) ax.add_artist(auctionbox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def acquire_teamPic(season_id, team_title, team_id, zoom, offset=(250, 370)): abb_file = os.getcwd() + "/../csvs/team_abbreviations.csv" abb_list = {} with open(abb_file, 'rU') as f: mycsv = csv.reader(f) for row in mycsv: team, abb, imgurl = row abb_list[team] = [abb, imgurl] img_url = abb_list.get(team_title)[1] try: img_path = os.getcwd() + '/' + str(team_id) + '.png' team_pic = plt.imread(img_path) except IOError: try: pic = urllib.urlretrieve(img_url, str(team_id) + '.png') team_pic = plt.imread(pic[0]) except (ValueError, IOError): img_path = os.getcwd() + '/nba_logo.png' player_pic = plt.imread(img_path) img = osb.OffsetImage(team_pic, zoom) img = osb.AnnotationBbox(img, offset, xycoords='data', pad=0.0, box_alignment=(1, 0), frameon=False) return img
def plot_embedding(X, title, ax): X = MinMaxScaler().fit_transform(X) for digit in digits.target_names: ax.scatter( *X[y == digit].T, marker=f"${digit}$", s=60, color=plt.cm.Dark2(digit), alpha=0.425, zorder=2, ) shown_images = np.array([[1.0, 1.0]]) # just something big for i in range(X.shape[0]): # plot every digit on the embedding # show an annotation box for a group of digits dist = np.sum((X[i] - shown_images)**2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.concatenate([shown_images, [X[i]]], axis=0) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) imagebox.set(zorder=1) ax.add_artist(imagebox) ax.set_title(title) ax.axis("off")
def plot_embedding(X, title, ax): X = MinMaxScaler().fit_transform(X) shown_images = np.array([[1.0, 1.0]]) # just something big for i in range(X.shape[0]): # plot every digit on the embedding ax.text( X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Dark2(y[i]), fontdict={"weight": "bold", "size": 9}, ) # show an annotation box for a group of digits dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.concatenate([shown_images, [X[i]]], axis=0) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i] ) ax.add_artist(imagebox) ax.set_title(title) ax.axis("off")
def plot_components(X_projected, images=None, ax=None, image_scale=1.0, markersize=10, thumb_frac=0.05, cmap='gray'): # https://jakevdp.github.io/PythonDataScienceHandbook/05.10-manifold-learning.html ax = ax or plt.gca() ax.plot(X_projected[:, 0], X_projected[:, 1], '.k', markersize=markersize) # images = images[:, ::image_scale, ::image_scale] # downsample the images # images = imresize(images, (images.shape[0], images.shape[1]*image_scale, images.shape[2]*image_scale)) # downsample the images images = resize(images, (images.shape[0], images.shape[1] * image_scale, images.shape[2] * image_scale), order=5, preserve_range=True) if images is not None: min_dist_2 = (thumb_frac * max(X_projected.max(0) - X_projected.min(0)))**2 shown_images = np.array([2 * X_projected.max(0)]) for i in range(X_projected.shape[0]): dist = np.sum((X_projected[i] - shown_images)**2, 1) if np.min(dist) < min_dist_2: # don't show points that are too close continue shown_images = np.vstack([shown_images, X_projected[i]]) imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(images[i], cmap=cmap), X_projected[i]) ax.add_artist(imagebox) #plt.show() #TODO: Add desired location/path + <name>.png to save plot plt.savefig('')
def plot_embedding(X, y, title=None): from matplotlib import offsetbox x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(y[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(y[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title)
def visualize(embed, x_test): # two ways of visualization: scale to fit [0,1] scale # feat = embed - np.min(embed, 0) # feat /= np.max(feat, 0) # two ways of visualization: leave with original scale feat = embed ax_min = np.min(embed, 0) # [-11.579187 -9.2086525] 0 means col, 1 means row ax_max = np.max(embed, 0) # [7.0608773 5.296893 ] ax_dist_sq = np.sum((ax_max - ax_min)**2) # 557.86285 plt.figure() ax = plt.subplot(111) shown_images = np.array([[1., 1.]]) for i in range(feat.shape[0]): dist = np.sum((feat[i] - shown_images)**2, 1) # 0-x axis project, 1-y axis if np.min( dist ) < 3e-4 * ax_dist_sq: # don't show points that are too close continue shown_images = np.r_[shown_images, [feat[i]]] # concatenate mat imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage( x_test[i], zoom=0.6, cmap=plt.cm.gray_r), xy=feat[i], frameon=False) ax.add_artist(imagebox) plt.axis([ax_min[0], ax_max[0], ax_min[1], ax_max[1]]) # plt.xticks([]), plt.yticks([]) plt.title('Embedding from the last layer of the network') plt.show()