我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.colors.ListedColormap()。
def saturation_index_countour(lab, elem1, elem2, Ks, labels=False): plt.figure() plt.title('Saturation index %s%s' % (elem1, elem2)) resoluion = 100 n = math.ceil(lab.time.size / resoluion) plt.xlabel('Time') z = np.log10((lab.species[elem1]['concentration'][:, ::n] + 1e-8) * ( lab.species[elem2]['concentration'][:, ::n] + 1e-8) / lab.constants[Ks]) lim = np.max(abs(z)) lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[::n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette( "RdBu_r", 101)), origin='lower', levels=lim, extend='both') if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') # cbar = plt.colorbar(CS) if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Saturation index %s%s' % (elem1, elem2)) return ax
def contour_plot_of_rates(lab, r, labels=False, last_year=False): plt.figure() plt.title('{}'.format(r)) resoluion = 100 n = math.ceil(lab.time.size / resoluion) if last_year: k = n - int(1 / lab.dt) else: k = 1 z = lab.estimated_rates[r][:, k - 1:-1:n] # lim = np.max(np.abs(z)) # lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[k::n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap( sns.color_palette("Blues", 51))) if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Rate %s [M/V/T]' % r) return ax
def contour_plot_of_delta(lab, element, labels=False, last_year=False): plt.figure() plt.title('Rate of %s consumption/production' % element) resoluion = 100 n = math.ceil(lab.time.size / resoluion) if last_year: k = n - int(1 / lab.dt) else: k = 1 z = lab.species[element]['rates'][:, k - 1:-1:n] lim = np.max(np.abs(z)) lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[k:-1:n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette( "RdBu_r", 101)), origin='lower', levels=lim, extend='both') if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Rate of %s change $[\Delta/T]$' % element) return ax
def plot_heatmaps(img_arr, img_names, titles, heatmaps, labels, out_dir): # construct cmap pal = sns.diverging_palette(240, 10, n=30, center="dark") my_cmap = ListedColormap(sns.color_palette(pal).as_hex()) min_val, max_val = np.min(heatmaps), np.max(heatmaps) for j, (img, img_name, h_map, title, y) in enumerate(zip(img_arr, img_names, heatmaps, titles, labels)): fig, ax = plt.subplots() img = np.transpose(img, (1, 2, 0)) plt.clf() plt.imshow(img, cmap='Greys', interpolation='bicubic') plt.imshow(h_map, cmap=my_cmap, alpha=0.7, interpolation='nearest') #, vmin=-.05, vmax=.05) plt.colorbar() plt.axis('off') plt.title(title) class_name = CLASSES[y] class_dir = make_sub_dir(out_dir, class_name) plt.savefig(join(class_dir, img_name), bbox_inches='tight', dpi=300)
def plot(self, size=1): """ Plot the values in the color palette as a horizontal array. See Seaborn's palplot function for inspiration. Parameters ---------- size : int scaling factor for size of the plot """ n = len(self) fig, ax = plt.subplots(1, 1, figsize=(n * size, size)) ax.imshow(np.arange(n).reshape(1,n), cmap=mpl.colors.ListedColormap(list(self)), interpolation="nearest", aspect="auto") ax.set_xticks(np.arange(n) - .5) ax.set_yticks([-.5, .5]) ax.set_xticklabels([]) ax.set_yticklabels([]) ########################################################################## ## Palette Functions ##########################################################################
def plot(X,Y,pred_func): # determine canvas borders mins = np.amin(X,0); mins = mins - 0.1*np.abs(mins); maxs = np.amax(X,0); maxs = maxs + 0.1*maxs; ## generate dense grid xs,ys = np.meshgrid(np.linspace(mins[0],maxs[0],300), np.linspace(mins[1], maxs[1], 300)); # evaluate model on the dense grid Z = pred_func(np.c_[xs.flatten(), ys.flatten()]); Z = Z.reshape(xs.shape) # Plot the contour and training examples plt.contourf(xs, ys, Z, cmap=plt.cm.Spectral) plt.scatter(X[:, 0], X[:, 1], c=Y, s=50, cmap=colors.ListedColormap(['orange', 'blue'])) plt.show()
def displayBrain(brain, res=25): mapV, mapA = mapBrain(brain, res) plt.close() plt.show() fig = plt.figure(figsize=(5,7)) fig.add_subplot(211) plt.imshow(mapV) plt.colorbar(orientation='vertical') fig.add_subplot(212) cmap = colors.ListedColormap(['yellow', 'blue', 'white', 'red']) bounds=[-1.5,-0.5,0.5,1.5,2.5] norm = colors.BoundaryNorm(bounds, cmap.N) plt.imshow(mapA, cmap=cmap, norm=norm) cb = plt.colorbar(orientation='vertical', ticks=[-1,0,1,2]) plt.pause(0.001)
def save_image(folder='images'): """ Coroutine of image saving """ from matplotlib import pyplot as plt from matplotlib import colors if folder not in os.listdir('.'): os.mkdir(folder) frame_cnt = it.count() cmap = colors.ListedColormap(['#009688', '#E0F2F1', '#004D40']) bounds = [0, 0.25, 0.75, 1] norm = colors.BoundaryNorm(bounds, cmap.N) while True: screen = (yield) shape = screen.shape plt.imshow( screen, interpolation='none', cmap=cmap, norm=norm, aspect='equal', extent=(0, shape[1], 0, shape[0])) plt.grid(True) plt.axis('off') plt.savefig('%s/frame%06i.png' % (folder, frame_cnt.next()))
def plot2d(self, title=None, domain=[-1, 1], codomain=[-1, 1], predict=True): f, ax = plt.subplots() x1 = np.linspace(*domain, 100) x2 = np.linspace(*codomain, 100) n_samples, n_features = self.X_.shape G = nx.from_scipy_sparse_matrix(self.A_) pos = {i: self.X_[i] for i in range(n_samples)} cm_sc = ListedColormap(['#AAAAAA', '#FF0000', '#0000FF']) if title is not None: ax.set_title(title) ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_xlim(domain) ax.set_ylim(codomain) nx.draw_networkx_nodes(G, pos, ax=ax, node_size=25, node_color=self.y_, cmap=cm_sc) if predict: xx1, xx2 = np.meshgrid(x1, x2) xfull = np.c_[xx1.ravel(), xx2.ravel()] z = self.predict(xfull).reshape(100, 100) levels = np.array([-1, 0, 1]) cm_cs = plt.cm.RdYlBu if self.params['gamma_i'] != 0.0: nx.draw_networkx_edges(G, pos, ax=ax, edge_color='#AAAAAA') ax.contourf(xx1, xx2, z, levels, cmap=cm_cs, alpha=0.25) return (f, ax)
def createCmap(mapname): fil = open(mapname+'.rgb') cdata = genfromtxt(fil,skip_header=2) cdata = cdata/256 cmap = cm.ListedColormap(cdata, mapname) fil.close() return cmap # function to convert x,y to lon,lat #-----------------------------------
def create_discrete_cmap(n): """Create an n-bin discrete colormap.""" if n <= len(SEABORN): colors = list(SEABORN.values())[:n] else: base = plt.cm.get_cmap('Paired') color_list = base([(i + 1) / (n + 1) for i in range(n)]) cmap_name = base.name + str(n) return clr.LinearSegmentedColormap.from_list(cmap_name, color_list, n) return clr.ListedColormap(colors)
def contour_plot(lab, element, labels=False, days=False, last_year=False): plt.figure() plt.title(element + ' concentration') resoluion = 100 n = math.ceil(lab.time.size / resoluion) if last_year: k = n - int(1 / lab.dt) else: k = 1 if days: X, Y = np.meshgrid(lab.time[k::n] * 365, -lab.x) plt.xlabel('Time') else: X, Y = np.meshgrid(lab.time[k::n], -lab.x) plt.xlabel('Time') z = lab.species[element]['concentration'][:, k - 1:-1:n] CS = plt.contourf(X, Y, z, 51, cmap=ListedColormap( sns.color_palette("Blues", 51)), origin='lower') if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('%s [M/V]' % element) if element == 'Temperature': plt.title('Temperature contour plot') cbar.ax.set_ylabel('Temperature, C') if element == 'pH': plt.title('pH contour plot') cbar.ax.set_ylabel('pH') return ax
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors, font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []): """Update the figure of the infomration plane for the movie""" #Print the line between the points cmap = ListedColormap(LAYERS_COLORS) segs = [] for i in range(0, data.shape[1]): x = data[0, i, num, :] y = data[1, i, num, :] points = np.array([x, y]).T.reshape(-1, 1, 2) segs.append(np.concatenate([points[:-1], points[1:]], axis=1)) segs = np.array(segs).reshape(-1, 2, 2) axes[0].clear() if len(axes)>1: axes[1].clear() lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6) lc.set_array(np.arange(0,5)) #Print the points for layer_num in range(data.shape[3]): axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85) axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r') title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num]) utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='$I(X;T)$', y_label='$I(T;Y)$') title_str = 'Precision as function of the epochs' utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='# Epochs', y_label='Precision')
def plot_classication_data(X, y, test_idx=None): fig, axes = plt.subplots(nrows=1, ncols=1) # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot all samples for idx, cl in enumerate(np.unique(y)): axes.scatter( x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl, edgecolors='black', alpha=0.8 ) # highlight test samples test_kwds = dict( c='', edgecolors='black', linewidths=1, label='test set' ) if test_idx is not None: X_test, y_test = X[test_idx, :], y[test_idx] axes.scatter(X_test[:, 0], X_test[:, 1], **test_kwds) return fig, axes
def _plot_decision_regions(axes, X, y, classifier, test_idx=None, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) axes.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) axes.set_xlim(xx1.min(), xx1.max()) axes.set_xlim(xx2.min(), xx2.max()) # plot all samples for idx, cl in enumerate(np.unique(y)): axes.scatter( x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl, edgecolors='black', alpha=0.8 ) # highlight test samples test_kwds = dict( c='', edgecolors='black', linewidths=1, label='test set' ) if test_idx is not None: X_test, y_test = X[test_idx, :], y[test_idx] axes.scatter(X_test[:, 0], X_test[:, 1], **test_kwds)
def _get_cmap(kwargs): """Get the colour map for plots that support it. Parameters ---------- cmap : str or colors.Colormap or list of colors A map or an instance of cmap. This can also be a seaborn palette (if seaborn is installed). Returns ------- colors.Colormap """ from matplotlib.colors import ListedColormap cmap = kwargs.pop("cmap", default_cmap) if isinstance(cmap, list): return ListedColormap(cmap) if isinstance(cmap, str): try: cmap = plt.get_cmap(cmap) except BaseException as exc: try: # Try to use seaborn palette import seaborn as sns sns_palette = sns.color_palette(cmap, n_colors=256) cmap = ListedColormap(sns_palette, name=cmap) except ImportError: raise exc return cmap
def discrete_cmap(N=8): # define individual colors as hex values cpool = [ '#000000', '#00EE00', '#0000EE', '#00EEEE', '#EE0000', '#FFFF00', '#EE00EE', '#FFFFFF'] cmap_i8 = col.ListedColormap(cpool[0:N], 'i8') cm.register_cmap(cmap=cmap_i8) # ----------------------------------------------------------------- # build a list of residual images
def discrete_cmap(N=8): # define individual colors as hex values cpool = [ '#000000', '#00EE00', '#0000EE', '#00EEEE', '#EE0000','#FFFF00', '#EE00EE', '#FFFFFF'] cmap_i8 = colors.ListedColormap(cpool[0:N], 'i8') cm.register_cmap(cmap=cmap_i8) return cmap_i8
def show_all(gt, pred): import matplotlib.pyplot as plt from matplotlib import colors from mpl_toolkits.axes_grid1 import make_axes_locatable fig, axes = plt.subplots(1, 2) ax1, ax2 = axes classes = np.array(('background', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')) colormap = [(0,0,0),(0.5,0,0),(0,0.5,0),(0.5,0.5,0),(0,0,0.5),(0.5,0,0.5),(0,0.5,0.5), (0.5,0.5,0.5),(0.25,0,0),(0.75,0,0),(0.25,0.5,0),(0.75,0.5,0),(0.25,0,0.5), (0.75,0,0.5),(0.25,0.5,0.5),(0.75,0.5,0.5),(0,0.25,0),(0.5,0.25,0),(0,0.75,0), (0.5,0.75,0),(0,0.25,0.5)] cmap = colors.ListedColormap(colormap) bounds=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] norm = colors.BoundaryNorm(bounds, cmap.N) ax1.set_title('gt') ax1.imshow(gt, cmap=cmap, norm=norm) ax2.set_title('pred') ax2.imshow(pred, cmap=cmap, norm=norm) plt.show()
def _string_to_cmap(cm_name): """Return colormap given name. Parameters: cm_name (str): Name of colormap. Returns: `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ (colormap) object """ if isinstance(cm_name, str): if 'linearlab' in cm_name: try: cmap, cmap_r = linearlab() except IOError: cmap = cm.viridis else: if '_r' in cm_name: cmap = cmap_r else: cmap = cm.get_cmap(cm_name) elif isinstance(cm_name, ListedColormap) or isinstance(cm_name, LinearSegmentedColormap): cmap = cm_name else: raise MarvinError('{} is not a valid cmap'.format(cm_name)) return cmap
def _custom_listed_color_map(self, name, N, firstBlack=False): """ add the black color in front of 'name' color """ import matplotlib.cm as cm from matplotlib import colors mp = cm.datad[name] new_mp1 = {'blue': colors.makeMappingArray(N-1, mp['blue']), 'green': colors.makeMappingArray(N-1, mp['green']), 'red': colors.makeMappingArray(N-1, mp['red'])} new_mp2 = [] new_mp2.extend(zip(new_mp1['red'], new_mp1['green'], new_mp1['blue'])) if firstBlack == True: new_mp2 = [(0,0,0)]+new_mp2 # the black color return colors.ListedColormap(new_mp2, N=N-1), new_mp2
def plot_decision(features, labels, num_neighbors=1): '''Plots decision boundary for KNN Parameters ---------- features : ndarray labels : sequence Returns ------- fig : Matplotlib Figure ax : Matplotlib Axes ''' y0, y1 = features[:, 2].min() * .9, features[:, 2].max() * 1.1 x0, x1 = features[:, 0].min() * .9, features[:, 0].max() * 1.1 X = np.linspace(x0, x1, 1000) Y = np.linspace(y0, y1, 1000) X, Y = np.meshgrid(X, Y) model = KNeighborsClassifier(num_neighbors) model.fit(features[:, (0,2)], labels) C = model.predict(np.vstack([X.ravel(), Y.ravel()]).T).reshape(X.shape) if COLOUR_FIGURE: cmap = ListedColormap([(1., .7, .7), (.7, 1., .7), (.7, .7, 1.)]) else: cmap = ListedColormap([(1., 1., 1.), (.2, .2, .2), (.6, .6, .6)]) fig,ax = plt.subplots() ax.set_xlim(x0, x1) ax.set_ylim(y0, y1) ax.set_xlabel(feature_names[0]) ax.set_ylabel(feature_names[2]) ax.pcolormesh(X, Y, C, cmap=cmap) if COLOUR_FIGURE: cmap = ListedColormap([(1., .0, .0), (.1, .6, .1), (.0, .0, 1.)]) ax.scatter(features[:, 0], features[:, 2], c=labels, cmap=cmap) else: for lab, ma in zip(range(3), "Do^"): ax.plot(features[labels == lab, 0], features[ labels == lab, 2], ma, c=(1., 1., 1.), ms=6) return fig,ax
def plot_decision(features, labels): '''Plots decision boundary for KNN Parameters ---------- features : ndarray labels : sequence Returns ------- fig : Matplotlib Figure ax : Matplotlib Axes ''' y0, y1 = features[:, 2].min() * .9, features[:, 2].max() * 1.1 x0, x1 = features[:, 0].min() * .9, features[:, 0].max() * 1.1 X = np.linspace(x0, x1, 100) Y = np.linspace(y0, y1, 100) X, Y = np.meshgrid(X, Y) model = fit_model(1, features[:, (0, 2)], np.array(labels)) C = predict( np.vstack([X.ravel(), Y.ravel()]).T, model).reshape(X.shape) if COLOUR_FIGURE: cmap = ListedColormap([(1., .6, .6), (.6, 1., .6), (.6, .6, 1.)]) else: cmap = ListedColormap([(1., 1., 1.), (.2, .2, .2), (.6, .6, .6)]) fig,ax = plt.subplots() ax.set_xlim(x0, x1) ax.set_ylim(y0, y1) ax.set_xlabel(feature_names[0]) ax.set_ylabel(feature_names[2]) ax.pcolormesh(X, Y, C, cmap=cmap) if COLOUR_FIGURE: cmap = ListedColormap([(1., .0, .0), (.0, 1., .0), (.0, .0, 1.)]) ax.scatter(features[:, 0], features[:, 2], c=labels, cmap=cmap) else: for lab, ma in zip(range(3), "Do^"): ax.plot(features[labels == lab, 0], features[ labels == lab, 2], ma, c=(1., 1., 1.)) return fig,ax
def show_data(y_test,X,y): ##There are 3 classes markers = ('s', 'x', 'o') colors = ('red', 'blue', 'green') cmap = ListedColormap(colors[:len(np.unique(y_test))]) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.show() ##Adaboost Class
def perform_adaboost(self,X_train_std,y_train,X_test_std, y_test): ##perform adaboost ada = AdaBoostClassifier(n_estimators=10) ada.fit(X_train_std, y_train) train_score=cross_val_score(ada,X_train_std, y_train) print('The training accuracy is {:.2f}%'.format(train_score.mean()*100)) test_score=cross_val_score(ada,X_test_std, y_test) print('The test accuracy is {:.2f}%'.format(test_score.mean()*100)) X=X_test_std y=y_test resolution=0.01 #Z = svm.predict(np.array([xx1.ravel(), xx2.ravel()]).T) markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'green', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y_test))]) X=X_test_std y=y_test # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = ada.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.5, c=cmap(idx), marker=markers[idx], label=cl) plt.show()
def show_data(y_test,X,y): ##There are 3 classes markers = ('s', 'x', 'o') colors = ('red', 'blue', 'green') cmap = ListedColormap(colors[:len(np.unique(y_test))]) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.show() ##Random Forest Class
def perform_random_forest(self,X_train_std,y_train,X_test_std, y_test): ## perform random forest rfc = RandomForestClassifier(n_estimators=10, max_depth=None,min_samples_split=2, random_state=0) # we create an instance of Neighbours Classifier and fit the data. rfc.fit(X_train_std, y_train) train_score=cross_val_score(rfc,X_train_std, y_train) print('The training accuracy is {:.2f}%'.format(train_score.mean()*100)) test_score=cross_val_score(rfc,X_test_std, y_test) print('The test accuracy is {:.2f}%'.format(test_score.mean()*100)) X=X_test_std y=y_test resolution=0.01 #Z = svm.predict(np.array([xx1.ravel(), xx2.ravel()]).T) markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'green', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y_test))]) X=X_test_std y=y_test # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = rfc.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.5, c=cmap(idx), marker=markers[idx], label=cl) plt.show()
def show_data(y_test,X,y): ##There are 3 classes markers = ('s', 'x', 'o') colors = ('red', 'blue', 'green') cmap = ListedColormap(colors[:len(np.unique(y_test))]) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.show() ## Logistic Regression Class
def show_data(y_test,X,y): ##There are 3 classes markers = ('s', 'x', 'o') colors = ('red', 'blue', 'green') cmap = ListedColormap(colors[:len(np.unique(y_test))]) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl) plt.show() ##SVM Class
def perform_svm(self,X_train_std,y_train,X_test_std, y_test): svm = SVC(kernel='rbf', random_state=0, gamma=.10, C=1.0) svm.fit(X_train_std, y_train) print('The training accuracy is {:.2f}%'.format(svm.score(X_train_std, y_train)*100)) print('The test accuracy is {:.2f}%'.format(svm.score(X_test_std, y_test)*100)) X=X_test_std y=y_test resolution=0.01 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = svm.predict(np.array([xx1.ravel(), xx2.ravel()]).T) markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'green', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y_test))]) X=X_test_std y=y_test # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = svm.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.5, c=cmap(idx), marker=markers[idx], label=cl) plt.show()
def main(): N = 500 K = 5 mean = np.array([[5, 0], [0, 5], [-5, 0], [0, -5], [0, 0]]) cov = np.array([[1, -1], [1, 1]]) sample = ClassificationSample(N, K, mean, cov) X = sample.X T = sample.T M = 2 classifier = SoftmaxRegression(X, T, M, K) classifier.train(tol=1e-5, max_iter=int(1e3), lr=1e-1, eta=0.95) x_min, y_min = X[:, 0].min() - 1, X[:, 1].min() - 1 x_max, y_max = X[:, 0].max() + 1, X[:, 1].max() + 1 plt.figure() color = np.array(['r', 'g', 'b', 'c', 'y']) cmap = ListedColormap(['#FFAAAA', '#AAFFAA', '#3380e6', '#00dcdc', '#fbf896']) h = 0.05 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) mesh = np.c_[xx.ravel(), yy.ravel()] pred = classifier.predict(mesh).argmax(axis=1) pred = pred.reshape(xx.shape) plt.pcolormesh(xx, yy, pred, cmap=cmap) for n in range(N): plt.scatter(X[n, 0], X[n, 1], c=color[np.argmax(T[n, :])]) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.show()
def main(): N = 4000 n_features = 2 n_classes = 4 K = n_classes mean = np.array([[5, 0], [0, 5], [-5, 8], [0, 0]]) cov = np.array([[2, -1], [1, 1]]) sample = ClassificationSample(N, K, mean, cov) X = sample.X T = sample.T classifier = SoftmaxRegression(n_features, n_classes) classifier.fit(X, T) x_min, y_min = X[0, :].min() - 1, X[1, :].min() - 1 x_max, y_max = X[0, :].max() + 1, X[1, :].max() + 1 color = np.array(['r', 'g', 'b', 'y']) cmap = ListedColormap(['#FFAAAA', '#AAFFAA', '#3380e6', '#fbf896']) plt.figure() h = 0.05 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) mesh = np.c_[xx.ravel(), yy.ravel()] predictions = classifier.predict(mesh.T) predictions = predictions.reshape(xx.shape) plt.pcolormesh(xx, yy, predictions, cmap=cmap) plt.scatter(X[0, :], X[1, :], marker='x', c=color[T]) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.show()
def TriAndPaint(img, points, outputIMG): tri = Delaunay(points) triList = points[tri.simplices] cMap = ListedColormap( np.array([ChooseColor(img, tr) for tr in triList])) # use core rgb # center = np.sum(points[tri.simplices], axis=1) / 3 # print(center) # cMap = ListedColormap( # np.array([img.getpixel((x, y)) for x, y in center]) / 256) color = np.array(range(len(triList))) # print(color) width, height = img.size plt.figure(figsize=(width, height), dpi=1) plt.tripcolor(points[:, 0], points[:, 1], tri.simplices.copy(), facecolors=color, cmap=cMap) # plt.tick_params(labelbottom='off', labelleft='off', # left='off', right='off', bottom='off', top='off') # plt.tight_layout(pad=0) plt.axis('off') plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.xlim(0, width) plt.ylim(0, height) plt.gca().invert_yaxis() plt.savefig(outputIMG) # uncomment show() if you want to view when it's done # plt.show()
def graph(self, filename): figure = plt.figure(figsize=(27, 9)) figure.max_num_figures = 5 matplotlib.figure.max_num_figures = 5 i = 0 cm = plt.cm.RdBu cm_bright = ListedColormap(['#00FF00', '#FF0000', '#0000FF']) ax = plt.subplot(1, 1, i) # Plot the training points ax.scatter(self.X_train[:, 0], self.X_train[:, 1], c=self.y_train, cmap=cm_bright) # and testing points ax.scatter(self.X_test[:, 0], self.X_test[:, 1], c=self.y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(self.xz[0].min(), self.xz[0].max()) ax.set_ylim(self.xz[1].min(), self.xz[1].max()) ax.set_xticks(()) ax.set_yticks(()) self.Z = self.clf.predict(self._input) self.Z = self.Z.reshape(self.xz[0].shape) ax.contourf(self.xz[0], self.xz[1], self.Z, cmap=cm, alpha=.8) # Plot also the training points ax.scatter(self.X_train[:, 0], self.X_train[:, 1], c=self.y_train, cmap=cm_bright) # and testing points ax.scatter(self.X_test[:, 0], self.X_test[:, 1], c=self.y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(self.xz[0].min(), self.xz[0].max()) ax.set_ylim(self.xz[1].min(), self.xz[1].max()) ax.set_xticks(()) ax.set_yticks(()) ax.set_title("(" + self.name + ")") text = ('%.2f' % self.score).lstrip('0') ax.text(self.xz[0].max() - .3, self.xz[1].min() + .3, text, size=15, horizontalalignment='right') i += 1 filepath = settings.BASE_DIR + filename figure.subplots_adjust(left=.02, right=.98) figure.savefig(filepath, dpi=100)
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): """ utility function to visualize the decision boundaries between two features :param X: 2D array of the input data to graph :param y: 1D vector of the class labels :param classifier: the trained classifier to use :param test_idx: range of indices that contain test data points :param resolution: hyper parameter :return: N/A """ # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # plot all samples for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) # highlight test samples if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, linewidth=1, marker='o', s=55, label='test set')
def show_plot(X, y, n_neighbors=10, h=0.2): # Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000',]) for weights in ['uniform', 'distance']: # we create an instance of Neighbours Classifier and fit the data. clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X, y) clf.n_neighbors = n_neighbors # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.title("3-Class classification (k = %i, weights = '%s')" % (n_neighbors, weights)) plt.show()
def adjblocks(Y, clusters=None, title=''): """ Make a colormap image of a matrix :key Y: the matrix to be used for the colormap. """ # Artefact #np.fill_diagonal(Y, 0) plt.figure() if clusters is None: plt.axis('off') cmap = 'Greys' norm = None y = Y else: plt.axis('on') y = reorder_mat(Y, clusters, reverse=True) hist, label = clusters_hist(clusters) # Colors Setup u_colors.reset() #cmap = Colors.ListedColormap(['white','black']+ u_colors.seq[:len(hist)**2]) cmap = Colors.ListedColormap(['#000000', '#FFFFFF']+ u_colors.seq[:len(hist)**2]) bounds = np.arange(len(hist)**2+2) norm = Colors.BoundaryNorm(bounds, cmap.N) # Iterate over blockmodel for k, count_k in enumerate(hist): for l, count_l in enumerate(hist): # Draw a colored square (not white and black) topleft = (hist[:k].sum(), hist[:l].sum()) w = int(0.01 * y.shape[0]) # write on place draw_square(y, k+l+2, topleft, count_k, count_l, w) implt = plt.imshow(y, cmap=cmap, norm=norm, clim=(np.amin(y), np.amax(y)), interpolation='nearest',) #origin='upper') # change shape ! #plt.colorbar() plt.title(title) #plt.savefig(filename, fig=fig, facecolor='white', edgecolor='black')
def cppn_fig(cppn, r, c): plt.figure() f = lambda *args: cppn.serial_activate(args)[0] grid = tuple( tuple( f(x / c, y / c) for x in range(-r, r + 1) ) for y in range(-r, r + 1) ) plt.imshow( grid, interpolation='none', extent=(-r, r, -r, r), cmap=ListedColormap(seaborn.color_palette('Blues')) )
def makeStateColorMap(nTrue=1, nExtra=0, nHighlight=0): ''' Returns ------- Cmap : ListedColormap object ''' from matplotlib.colors import ListedColormap C = np.asarray([ [166, 206, 227], [31, 120, 180], [178, 223, 138], [51, 160, 44], [251, 154, 153], [227, 26, 28], [254, 153, 41], [255, 127, 0], [202, 178, 214], [106, 61, 154], [223, 194, 125], [140, 81, 10], [128, 205, 193], [1, 102, 94], [241, 182, 218], [197, 27, 125], ], dtype=np.float64) C = np.vstack([C, 0.5 * C, 0.25 * C]) if nTrue > C.shape[0]: raise ValueError('Cannot display more than %d true colors!' % ( C.shape[0])) C = C[:nTrue] / 255.0 shadeVals = np.linspace(0.2, 0.95, nExtra) for shadeID in xrange(nExtra): shadeOfRed = np.asarray([shadeVals[shadeID], 0, 0]) C = np.vstack([C, shadeOfRed[np.newaxis, :]]) highVals = np.linspace(0.3, 1.0, nHighlight) for highID in xrange(nHighlight): yellowColor = np.asarray([highVals[highID], highVals[highID], 0]) C = np.vstack([C, yellowColor[np.newaxis, :]]) return ListedColormap(C)
def percolation(matrice): # methode 2 """Dessine la propagation de l'eau, et indique s'il y a percolation.""" cmap = colors.ListedColormap(couleurs) # TODO: Relève du display, à metttre ailleurs. norm = colors.BoundaryNorm(valeurs + [max(valeurs)+1], cmap.N) pyplot.matshow([valeurs], 1, cmap=cmap, norm=norm) pyplot.pause(1) eau_mouvante = initialisation_eau_mouvante(matrice) while eau_mouvante != []: pyplot.matshow(matrice, 1, cmap=cmap, norm=norm) # TODO: Séparer la logique de display de la logique de génération (threads ?) pyplot.pause(.0001) eau_mouvante = propagation(matrice,eau_mouvante) return resultat(matrice)
def assign_colors(objects, cmap=CMAP_CATEGORICAL, colors=()): """ Assign colors to objects. Arguments: objects (iterable): cmap (matplotlib.cm): colors (iterable): Returns: dict: {state: color} """ o_to_color = {} for i, o in enumerate(sorted(set(objects))): if len(colors): # Make colormap from colors cmap = ListedColormap(colors, N=len(colors)) if isinstance(o, number): object_range = max(objects) - min(objects) if object_range: o_01 = (o - min(objects)) / object_range i = int(o_01 * cmap.N) else: i = 0 c = cmap(i) o_to_color[o] = c return o_to_color
def add_interpolated_colorbar(da, colors, direction): """ Add 'rastered' colorbar to DrawingArea """ # Special case that arises due to not so useful # aesthetic mapping. if len(colors) == 1: colors = [colors[0], colors[0]] # Number of horizontal egdes(breaks) in the grid # No need to create more nbreak than colors, provided # no. of colors = no. of breaks = no. of cmap colors # the shading does a perfect interpolation nbreak = len(colors) if direction == 'vertical': mesh_width = 1 mesh_height = nbreak-1 linewidth = da.height/mesh_height # Construct rectangular meshgrid # The values(Z) at each vertex are just the # normalized (onto [0, 1]) vertical distance x = np.array([0, da.width]) y = np.arange(0, nbreak) * linewidth X, Y = np.meshgrid(x, y) Z = Y/y.max() else: mesh_width = nbreak-1 mesh_height = 1 linewidth = da.width/mesh_width x = np.arange(0, nbreak) * linewidth y = np.array([0, da.height]) X, Y = np.meshgrid(x, y) Z = X/x.max() # As a 2D coordinates array coordinates = np.zeros( ((mesh_width+1)*(mesh_height+1), 2), dtype=float) coordinates[:, 0] = X.ravel() coordinates[:, 1] = Y.ravel() cmap = ListedColormap(colors) coll = mcoll.QuadMesh(mesh_width, mesh_height, coordinates, antialiased=False, shading='gouraud', linewidth=0, cmap=cmap, array=Z.ravel()) da.add_artist(coll)
def plot_com_original(com_data,rownames,colnames): """ This function returns a plot of the community array as it is. The parameters include: com_data: A 2-dimension community array. rownames: A list of strings corresponding to the row names of com_data. colnames: A list of strings corresponding to the column names of com_data. """ # Get the basic info of the community array. com_data = com_data.astype(int) # Make sure that the communities are denoted as integers. n_row = np.shape(com_data)[0] # Number of rows. n_col = np.shape(com_data)[1] # Number of columns. data = com_data.reshape(com_data.size) # Convert to 1-dimension array. all_count = np.bincount(data) # Count frequency of each community. all_order = np.argsort(all_count)[::-1] # Generate the ranking list of communities by frequency. n_com = len(all_order) # n_com is equal to the largest integer in com_data plus 1. # Generate n_com "distinct" enough colors. HLS_color = [] i = 0 step = 0.9/n_com init = step while i < n_com: temp_hue = init temp_lig = rd.random() temp_sat = rd.random() HLS_color.append((temp_hue,temp_lig,temp_sat)) i += 1 init += step RGB_color = [cs.hls_to_rgb(a,b,c) for (a,b,c) in HLS_color] # Prepare the discrete colormap for each integer/community. cmap = colors.ListedColormap(RGB_color) # Prepare the plot. fig, ax = plt.subplots(figsize=(16,16)) xticks = np.arange(0,n_col,1)+0.5 yticks = np.arange(0,n_row,1)+0.5 ax.set_xticks(xticks, minor=False) ax.set_yticks(yticks, minor=False) ax.pcolor(com_data, cmap=cmap, alpha=0.8, edgecolors='white', linewidths=1) ax.invert_yaxis() # This will make the rows start from the top. ax.xaxis.tick_top() # This will make x labels on top. ax.set_xticklabels(colnames, minor=False) ax.set_yticklabels(rownames, minor=False) plt.savefig('original.png')
def draw_timeline(self, tobesaved=False, fname=None, y_max=20, freq='1M'): ''' Prints a user's timeline of interaction with ems, jail,and mental health from 2010 Jan to 2016 June :params DataFrame user: A DataFrame of user with personid/hash_ssn, event, begin_date and end_date. :params str fname: The file name to be saved with. :params bool tobesaved: The flag of whether to save the figure. :params int y_max: The maximum of y-axis of the figure. :return: None :rtype: None ''' user_resample = self.get_series(freq) user_m = [t.count('M') for t in user_resample] user_e = [t.count('E') for t in user_resample] user_j = [t.count('J') for t in user_resample] user_df = pd.DataFrame({'count_of_m':user_m, 'count_of_j':user_j, 'count_of_e':user_e},index=list(user_resample.index.to_period(freq))) columns = list(user_resample.index.to_period(freq)) x_max = len(columns) heat_df = pd.DataFrame(np.array([[0]*x_max]*y_max), index=range(y_max), columns=columns) for i in range(len(user_df)): temp = [] temp_df = user_df.iloc[[i]] if int(temp_df['count_of_e']) > 0: temp.extend([1]*int(temp_df['count_of_e'])) if int(temp_df['count_of_j']) > 0: temp.extend([2]*int(temp_df['count_of_j'])) if int(temp_df['count_of_m']) > 0: temp.extend([3]*int(temp_df['count_of_m'])) temp = temp + [0]*(y_max-len(temp)) heat_df[columns[i]] = temp fig = plt.figure(figsize=(30,10)) #plt.title("{}'s timeline".format(user['personid'][0])) cmap = ListedColormap(['white',(0.99,0.58,0.59),(0.59,0.59,1),(0.6,0.8,0.59)]) ax = sns.heatmap(heat_df, cmap=cmap,vmin=0,vmax=3,edgecolor='w', linewidth=1.5,cbar=False, annot=False, square=True) ax.invert_yaxis() ax.set_xticklabels(columns,rotation=90,ha='center',va='top') ax.set_yticklabels(range(y_max,0,-1), rotation=0,va='baseline') ems_patch = mpatches.Patch(color=(0.99,0.58,0.59), label='EMS') jail_patch = mpatches.Patch(color=(0.59,0.59,1), label='Jail') mh_patch = mpatches.Patch(color = (0.6,0.8,0.59), label='Mental Health') plt.legend(handles=[ems_patch,jail_patch,mh_patch], handler_map={jail_patch: HandlerSquare(), ems_patch: HandlerSquare(), mh_patch: HandlerSquare()}, bbox_to_anchor=(0.5, 1.05), loc=9, ncol=3, borderaxespad=0.3,prop={'size':25}) if tobesaved == True: if fname == None: fname = "id{}_timeline.png".format(user['personid'][0]) plt.savefig(fname) plt.show()
def draw(self): """ Draw a heat map. """ def get_crosstab(data, row_fact,col_fact, row_names, col_names): ct = pd.crosstab(data[row_fact], data[col_fact]) ct = ct.reindex_axis(row_names, axis=0).fillna(0) ct = ct.reindex_axis(col_names, axis=1).fillna(0) return ct def plot(data, color): ct = get_crosstab( data, self._groupby[0], self._groupby[1], self._levels[0], self._levels[1]) sns.heatmap(ct, robust=True, annot=True, cbar=False, cmap=cmap, fmt="g", vmax=vmax, #ax=plt.gca(), linewidths=1) if len(self._groupby) < 2: # create a dummy cross tab with one dimension containing empty # values: data_column = self._table[self._groupby[0]].reset_index(drop=True) tab = pd.crosstab( pd.Series([""] * len(data_column), name=""), data_column) plot_facet = lambda data, color: sns.heatmap( tab, robust=True, annot=True, cbar=False, cmap=cmap, fmt="g", linewidths=1) else: plot_facet = plot vmax = pd.crosstab( [self._table[x] for x in [self._row_factor, self._groupby[0]] if x != None], [self._table[x] for x in [self._col_factor, self._groupby[1]] if x != None]).values.max() cmap = ListedColormap(self.options["color_palette_values"]) self.map_data(plot_facet)
def classification(dataset=0): # generate training and test data n_train = 1000 if dataset == 0: X, Y = make_classification(n_samples=n_train, n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1) rng = np.random.RandomState(2) X += 2 * rng.uniform(size=X.shape) X_test, Y_test = make_classification(n_samples=50, n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1) X_test += 2 * rng.uniform(size=X_test.shape) elif dataset == 1: X, Y = make_moons(n_samples=n_train, noise=0.3, random_state=0) X_test, Y_test = make_moons(n_samples=50, noise=0.3, random_state=1) elif dataset == 2: X, Y = make_circles(n_samples=n_train, noise=0.2, factor=0.5, random_state=1) X_test, Y_test = make_circles(n_samples=50, noise=0.2, factor=0.5, random_state=1) else: print("dataset unknown") return # build, train, and test the model model = SupervisedNNModel(X.shape[1], 2, hunits=[100, 50], activations=[T.tanh, T.tanh, T.nnet.softmax], cost_fun='negative_log_likelihood', error_fun='zero_one_loss', learning_rate=0.01, L1_reg=0., L2_reg=0.) model.fit(X, Y) print("Test Error: %f" % model.score(X_test, Y_test)) # plot dataset + predictions plt.figure() x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) cm = plt.cm.RdBu cm_bright = ListedColormap(['#FF0000', '#0000FF']) Z = model.predict(np.c_[xx.ravel(), yy.ravel()])[:, 1] # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=cm, alpha=.8) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=cm_bright, alpha=0.6) # and testing points plt.scatter(X_test[:, 0], X_test[:, 1], c=Y_test, cmap=cm_bright) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title('Classification Problem (%i)' % dataset)