我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用matplotlib.pyplot.NullLocator()。
def saveHintonPlot(self, matrix, num_tests, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" fig,ax = plt.subplots(1,1) if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(0.5*w/num_tests)) # Need to scale so that it is between 0 and 0.5 rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() plt.savefig(self.figures_path + self.save_prefix + '-Hinton.eps') plt.close()
def _setup_figure(bg_img, bg_extent, scale=1.0): plt.rc('figure', autolayout=False) # turn off tight_layout dpi = plt.rcParams.get('figure.dpi', 100.0) fig = plt.figure(dpi=dpi, frameon=False) # scale the figure to fit the bg image bg_height, bg_width = bg_img.shape[:2] fig.set_size_inches(bg_width / dpi * scale, bg_height / dpi * scale) ax = fig.add_axes([0, 0, 1, 1]) ax.set_axis_off() ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) ax.imshow(bg_img, zorder=0, extent=bg_extent, cmap='Greys_r', aspect='auto') ax.autoscale(False) ax.margins(0, 0) return fig, ax
def plot_heater(ax, data): """ plots deiced heater status i.e. ON/OFF """ if not 'PRTAFT_deiced_temp_flag' in data: return ax.text(0.05, 0.98,'Heater', axes_title_style, transform=ax.transAxes) ax.grid(False) ax.set_ylim(0,1) ax.yaxis.set_major_locator(plt.NullLocator()) plt.setp(ax.get_xticklabels(), visible=False) heater_status=np.array(data['PRTAFT_deiced_temp_flag'], dtype=np.int8) toggle=np.diff(heater_status.ravel()) time_periods=zip(list(np.where(toggle == 1)[0]), list(np.where(toggle == -1)[0])) for t in time_periods: #plt.barh(0, data['mpl_timestamp'][0,1], left=data['mpl_timestamp'][0,0]) width=data['mpl_timestamp'][t[1],0]-data['mpl_timestamp'][t[0],0] ax.add_patch(patches.Rectangle((data['mpl_timestamp'][t[0],0], 0), width, 1, alpha=0.8, color='#ffaf4d')) return ax
def hinton(matrix, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis()
def draw_label(label, img, label_names, colormap=None): plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) if colormap is None: colormap = label_colormap(len(label_names)) label_viz = label2rgb(label, img, n_labels=len(label_names)) plt.imshow(label_viz) plt.axis('off') plt_handlers = [] plt_titles = [] for label_value, label_name in enumerate(label_names): fc = colormap[label_value] p = plt.Rectangle((0, 0), 1, 1, fc=fc) plt_handlers.append(p) plt_titles.append(label_name) plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5) f = io.BytesIO() plt.savefig(f, bbox_inches='tight', pad_inches=0) plt.cla() plt.close() out = np.array(PIL.Image.open(f))[:, :, :3] out = scipy.misc.imresize(out, img.shape[:2]) return out
def hinton(matrix, max_weight=None, ax=None, xtick=None, ytick=None, inverted_color=False): """Draw Hinton diagram for visualizing a weight matrix. Copied from: http://matplotlib.org/examples/specialty_plots/hinton_demo.html """ ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): if inverted_color: color = 'black' if w > 0 else 'white' else: color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w)) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() if xtick: ax.set_xticks(np.arange(matrix.shape[0])) ax.set_xticklabels(xtick) if ytick: ax.set_yticks(np.arange(matrix.shape[1])) ax.set_yticklabels(ytick) return ax
def plot_hinton(matrix, max_weight=None, ax=None): ''' Hinton diagrams are useful for visualizing the values of a 2D array (e.g. a weight matrix): Positive: white Negative: black squares, and the size of each square represents the magnitude of each value. * Note: performance significant decrease as array size > 50*50 Example: W = np.random.rand(10,10) hinton_plot(W) ''' from matplotlib import pyplot as plt """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max()) / np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w)) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() return ax # =========================================================================== # Helper methods # ===========================================================================
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836): """Display a frame(image). Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. name : a string A name to save the image, if saveable is True. cmap : None or string 'gray' for greyscale, None for default, etc. fig_idx : int matplotlib figure index. Examples -------- >>> env = gym.make("Pong-v0") >>> observation = env.reset() >>> tl.visualize.frame(observation) """ if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images if len(I.shape) and I.shape[-1]==1: # (10,10,1) --> (10,10) I = I[:,:,0] plt.imshow(I, cmap) plt.title(name) # plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick # plt.gca().yaxis.set_major_locator(plt.NullLocator()) if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def visualize_CNN(CNN, second=10, saveable=True, name='cnn1_', fig_idx=39362): n_feature = CNN.shape[0] n_color = CNN.shape[1] n_row = CNN.shape[2] n_col = CNN.shape[3] row = int(np.sqrt(n_feature)) col = int(np.ceil(n_feature/row)) plt.ion() # active mode fig = plt.figure(fig_idx) count = 1 for ir in range(1, row+1): for ic in range(1, col+1): if count > n_feature: break a = fig.add_subplot(col, row, count) plt.imshow( np.reshape(CNN[count-1,:,:,:], (n_row, n_col)), cmap='gray', interpolation="nearest") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # ?????(tick) plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def draw_density_estimation(self, axis, title, samples, cmap): axis.clear() axis.set_xlabel(title) density_estimation = numpy.zeros((self.l_kde, self.l_kde)) for x, y in samples: if 0 < x < 1 and 0 < y < 1: density_estimation[int((1-y) / self.resolution)][int(x / self.resolution)] += 1 density_estimation = filters.gaussian(density_estimation, self.bw_kde_) axis.imshow(density_estimation, cmap=cmap) axis.xaxis.set_major_locator(pyplot.NullLocator()) axis.yaxis.set_major_locator(pyplot.NullLocator())
def remove_y_axis(): plt.tick_params(axis='y', labelbottom='off') # plt.gca().yaxis.set_major_locator(plt.NullLocator())
def frame(I=None, second=5, saveable=True, name='frame', fig_idx=12836): """Display a frame(image). Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image second : int The display second(s) for the image(s), if saveable is False. saveable : boolen Save or plot the figure. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> env = gym.make("Pong-v0") >>> observation = env.reset() >>> tl.visualize.frame(observation) """ if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images plt.imshow(I) # plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick # plt.gca().yaxis.set_major_locator(plt.NullLocator()) if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def W(W=None, second=10, saveable=True, shape=[28,28], name='mnist', fig_idx=2396512): """Visualize every columns of the weight matrix to a group of Greyscale img. Parameters ---------- W : numpy.array The weight matrix second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. shape : a list with 2 int The shape of feature image, MNIST is [28, 80]. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.W(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012) """ if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images size = W.shape[0] n_units = W.shape[1] num_r = int(np.sqrt(n_units)) # ??????? ?25?hidden unit -> ????5? num_c = int(np.ceil(n_units/num_r)) count = int(1) for row in range(1, num_r+1): for col in range(1, num_c+1): if count > n_units: break a = fig.add_subplot(num_r, num_c, count) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray') # ------------------------------------------------------------ feature = W[:,count-1] / np.sqrt( (W[:,count-1]**2).sum()) # feature[feature<0.0001] = 0 # value threshold # if count == 1 or count == 2: # print(np.mean(feature)) # if np.std(feature) < 0.03: # condition threshold # feature = np.zeros_like(feature) # if np.mean(feature) < -0.015: # condition threshold # feature = np.zeros_like(feature) plt.imshow(np.reshape(feature ,(shape[0],shape[1])), cmap='gray', interpolation="nearest")#, vmin=np.min(feature), vmax=np.max(feature)) # plt.title(name) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362): """Display a group of RGB or Greyscale CNN masks. Parameters ---------- CNN : numpy.array The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64). second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012) """ # print(CNN.shape) # (5, 5, 3, 64) # exit() n_mask = CNN.shape[3] n_row = CNN.shape[0] n_col = CNN.shape[1] n_color = CNN.shape[2] row = int(np.sqrt(n_mask)) col = int(np.ceil(n_mask/row)) plt.ion() # active mode fig = plt.figure(fig_idx) count = 1 for ir in range(1, row+1): for ic in range(1, col+1): if count > n_mask: break a = fig.add_subplot(col, row, count) # print(CNN[:,:,:,count-1].shape, n_row, n_col) # (5, 1, 32) 5 5 # exit() # plt.imshow( # np.reshape(CNN[count-1,:,:,:], (n_row, n_col)), # cmap='gray', interpolation="nearest") # theano if n_color == 1: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col)), cmap='gray', interpolation="nearest") elif n_color == 3: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col, n_color)), cmap='gray', interpolation="nearest") else: raise Exception("Unknown n_color") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def __init__(self, reward_fn=None, mu=0., std=1.0): super(DriveEnv_1D, self).__init__(reward_fn, mu, std) # Load in trajectory data from NGSIM self.j = j = julia.Julia() j.using("NGSIM") j.using("AutomotiveDrivingModels") j.add_module_functions("NGSIM") print 'Loading NGSIM data...' self.trajdata = j.eval("load_trajdata(1)") self.ids = self.j.get_ids(self.trajdata) print 'Done.' # Graphics if GRAPHICS: _, self.ax = plt.subplots(1, 1) drawParams = {} drawParams['xBottom'] = -50 drawParams['yTop'] = 10.0 drawParams['xTop'] = 10.0 drawParams['carlength'] = carlength = 5 drawParams['carheight'] = carheight = 2 drawParams['txtDist'] = plt.text( 0.5, 0.9, '', ha='center', va='center', transform=self.ax.transAxes) drawParams['txtS_ego'] = plt.text( 0.3, 0.5, '', ha='center', va='center', transform=self.ax.transAxes) drawParams['txtS_lead'] = plt.text( 0.7, 0.5, '', ha='center', va='center', transform=self.ax.transAxes) self.ax.set_xlim((drawParams['xBottom'], drawParams['xTop'])) self.ax.set_ylim((0, drawParams['yTop'])) self.ax.xaxis.set_major_locator(plt.NullLocator()) self.ax.yaxis.set_major_locator(plt.NullLocator()) self.ax.set_aspect(1) drawParams['ego'] = ego = mpl.patches.Rectangle( (0 - carlength, 0), carlength, carheight, color='b') drawParams['lead'] = lead = mpl.patches.Rectangle( (0, 0), carlength, carheight, color='r') self.drawParams = drawParams self.ax.add_patch(ego) self.ax.add_patch(lead)
def W(W=None, second=10, saveable=True, shape=[28,28], name='mnist', fig_idx=2396512): """Visualize every columns of the weight matrix to a group of Greyscale img. Parameters ---------- W : numpy.array The weight matrix second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. shape : a list with 2 int The shape of feature image, MNIST is [28, 80]. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.W(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012) """ import matplotlib.pyplot as plt if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images size = W.shape[0] n_units = W.shape[1] num_r = int(np.sqrt(n_units)) # ??????? ?25?hidden unit -> ????5? num_c = int(np.ceil(n_units/num_r)) count = int(1) for row in range(1, num_r+1): for col in range(1, num_c+1): if count > n_units: break a = fig.add_subplot(num_r, num_c, count) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray') # ------------------------------------------------------------ feature = W[:,count-1] / np.sqrt( (W[:,count-1]**2).sum()) # feature[feature<0.0001] = 0 # value threshold # if count == 1 or count == 2: # print(np.mean(feature)) # if np.std(feature) < 0.03: # condition threshold # feature = np.zeros_like(feature) # if np.mean(feature) < -0.015: # condition threshold # feature = np.zeros_like(feature) plt.imshow(np.reshape(feature ,(shape[0],shape[1])), cmap='gray', interpolation="nearest")#, vmin=np.min(feature), vmax=np.max(feature)) # plt.title(name) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836): """Display a frame(image). Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. name : a string A name to save the image, if saveable is True. cmap : None or string 'gray' for greyscale, None for default, etc. fig_idx : int matplotlib figure index. Examples -------- >>> env = gym.make("Pong-v0") >>> observation = env.reset() >>> tl.visualize.frame(observation) """ import matplotlib.pyplot as plt if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images if len(I.shape) and I.shape[-1]==1: # (10,10,1) --> (10,10) I = I[:,:,0] plt.imshow(I, cmap) plt.title(name) # plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick # plt.gca().yaxis.set_major_locator(plt.NullLocator()) if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362): """Display a group of RGB or Greyscale CNN masks. Parameters ---------- CNN : numpy.array The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64). second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012) """ import matplotlib.pyplot as plt # print(CNN.shape) # (5, 5, 3, 64) # exit() n_mask = CNN.shape[3] n_row = CNN.shape[0] n_col = CNN.shape[1] n_color = CNN.shape[2] row = int(np.sqrt(n_mask)) col = int(np.ceil(n_mask/row)) plt.ion() # active mode fig = plt.figure(fig_idx) count = 1 for ir in range(1, row+1): for ic in range(1, col+1): if count > n_mask: break a = fig.add_subplot(col, row, count) # print(CNN[:,:,:,count-1].shape, n_row, n_col) # (5, 1, 32) 5 5 # exit() # plt.imshow( # np.reshape(CNN[count-1,:,:,:], (n_row, n_col)), # cmap='gray', interpolation="nearest") # theano if n_color == 1: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col)), cmap='gray', interpolation="nearest") elif n_color == 3: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col, n_color)), cmap='gray', interpolation="nearest") else: raise Exception("Unknown n_color") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def draw_label(label, img, n_class, label_titles, bg_label=0): """Convert label to rgb with label titles. @param label_title: label title for each labels. @type label_title: dict """ from PIL import Image from scipy.misc import fromimage from skimage.color import label2rgb from skimage.transform import resize colors = labelcolormap(n_class) label_viz = label2rgb(label, img, colors=colors[1:], bg_label=bg_label) # label 0 color: (0, 0, 0, 0) -> (0, 0, 0, 255) label_viz[label == 0] = 0 # plot label titles on image using matplotlib plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.axis('off') # plot image plt.imshow(label_viz) # plot legend plt_handlers = [] plt_titles = [] for label_value in np.unique(label): if label_value not in label_titles: continue fc = colors[label_value] p = plt.Rectangle((0, 0), 1, 1, fc=fc) plt_handlers.append(p) plt_titles.append(label_titles[label_value]) plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=0.5) # convert plotted figure to np.ndarray f = StringIO.StringIO() plt.savefig(f, bbox_inches='tight', pad_inches=0) result_img_pil = Image.open(f) result_img = fromimage(result_img_pil, mode='RGB') result_img = resize(result_img, img.shape, preserve_range=True) result_img = result_img.astype(img.dtype) return result_img
def hinton(weight_matrix, intensity_matrix, cmap, vmin, vmax, max_weight=None, ax=None): """ Draw Hinton diagram for visualizing a weight matrix. Args ---- weight_matrix: np.array intensity_matrix: np.array cmap: string Identifier of colormap being used for plotting (e.g. "PRGn") vmin: float Minimal value to be displayed in intensity matrix vmax: float Maximal value to be displayed in intensity matrix max_weight: int Force maximal weight of weight matrix ax: matplotlib.axes.Axes instance """ ax = ax if ax is not None else plt.gca() # Set colors for intensity matrix cm = plt.get_cmap(cmap) cNorm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=cm) intensity_colors = scalarMap.to_rgba(intensity_matrix) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x,y),w in np.ndenumerate(weight_matrix): color = intensity_colors[x][y] size = 0. if(not(w==0)): size = calculateRootedSize(float(w), float(weight_matrix.max())) if(not(max_weight == None)): size = 0. if(not(w==0)): size = calculateRootedSize(float(w), float(max_weight)) rect = plt.Rectangle([(3-y) - size / 2, x - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) plt.ylim([-1,4]) plt.xlim(-1,4) ax.invert_xaxis() ax.invert_yaxis()
def hintonLegend(weight_matrix, intensity_matrix, text_matrix, cmap, vmin, vmax, max_weight=None, ax=None): """ Draw Hinton diagram for visualizing a legend describing the number of mutations corresponding to sizes of squares. Args ---- weight_matrix: np.array intensity_matrix: np.array text_matrix: np.array cmap: string Identifier of colormap being used for plotting (e.g. "PRGn") vmin: float Minimal value to be displayed in intensity matrix vmax: float Maximal value to be displayed in intensity matrix max_weight: int Force maximal weight of weight matrix ax: matplotlib.axes.Axes instance """ ax = ax if ax is not None else plt.gca() # Set colors for intensity matrix cm = plt.get_cmap(cmap) cNorm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=cm) intensity_colors = scalarMap.to_rgba(intensity_matrix) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x,y),w in np.ndenumerate(weight_matrix): color = intensity_colors[x][y] size = 0. if(not(w==0)): size = calculateRootedSize(float(w), float(weight_matrix.max())) if(not(max_weight == None)): size = 0. if(not(w==0)): size = calculateRootedSize(float(w), float(max_weight)) rect = plt.Rectangle([(3-y) - size / 2, x - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) for (x,y),w in np.ndenumerate(text_matrix): ax.add_patch(rect) plt.text(3-y, x, w) plt.ylim([-1,4]) plt.xlim(-1,4) ax.invert_xaxis() ax.invert_yaxis()
def W(W=None, second=10, saveable=True, shape=[28,28], name='mnist', fig_idx=2396512): """Visualize every columns of the weight matrix to a group of Greyscale img. Parameters ---------- W : numpy.array The weight matrix second : int The display second(s) for the image(s), if saveable is False. saveable : boolen Save or plot the figure. shape : a list with 2 int The shape of feature image, MNIST is [28, 80]. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.W(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012) """ if saveable is False: plt.ion() fig = plt.figure(fig_idx) # show all feature images size = W.shape[0] n_units = W.shape[1] num_r = int(np.sqrt(n_units)) # ??????? ?25?hidden unit -> ????5? num_c = int(np.ceil(n_units/num_r)) count = int(1) for row in range(1, num_r+1): for col in range(1, num_c+1): if count > n_units: break a = fig.add_subplot(num_r, num_c, count) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray') # ------------------------------------------------------------ feature = W[:,count-1] / np.sqrt( (W[:,count-1]**2).sum()) # feature[feature<0.0001] = 0 # value threshold # if count == 1 or count == 2: # print(np.mean(feature)) # if np.std(feature) < 0.03: # condition threshold # feature = np.zeros_like(feature) # if np.mean(feature) < -0.015: # condition threshold # feature = np.zeros_like(feature) plt.imshow(np.reshape(feature ,(shape[0],shape[1])), cmap='gray', interpolation="nearest")#, vmin=np.min(feature), vmax=np.max(feature)) # ------------------------------------------------------------ # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362): """Display a group of RGB or Greyscale CNN masks. Parameters ---------- CNN : numpy.array The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64). second : int The display second(s) for the image(s), if saveable is False. saveable : boolen Save or plot the figure. name : a string A name to save the image, if saveable is True. fig_idx : int matplotlib figure index. Examples -------- >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012) """ # print(CNN.shape) # (5, 5, 3, 64) # exit() n_mask = CNN.shape[3] n_row = CNN.shape[0] n_col = CNN.shape[1] n_color = CNN.shape[2] row = int(np.sqrt(n_mask)) col = int(np.ceil(n_mask/row)) plt.ion() # active mode fig = plt.figure(fig_idx) count = 1 for ir in range(1, row+1): for ic in range(1, col+1): if count > n_mask: break a = fig.add_subplot(col, row, count) # print(CNN[:,:,:,count-1].shape, n_row, n_col) # (5, 1, 32) 5 5 # exit() # plt.imshow( # np.reshape(CNN[count-1,:,:,:], (n_row, n_col)), # cmap='gray', interpolation="nearest") # theano if n_color == 1: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col)), cmap='gray', interpolation="nearest") elif n_color == 3: plt.imshow( np.reshape(CNN[:,:,:,count-1], (n_row, n_col, n_color)), cmap='gray', interpolation="nearest") else: raise Exception("Unknown n_color") plt.gca().xaxis.set_major_locator(plt.NullLocator()) # distable tick plt.gca().yaxis.set_major_locator(plt.NullLocator()) count = count + 1 if saveable: plt.savefig(name+'.pdf',format='pdf') else: plt.draw() plt.pause(second)