def print_save_all_mean_faces(x_class_mean, global_mean, show, save): rows = 4 cols = 14 index = 1 font_size = 10 plt.figure(figsize=(20, 10)) plt.subplot(rows, cols, index), plt.imshow(np.reshape(global_mean, (46, 56)).T, cmap='gist_gray') title = str("Global Mean") plt.title(title, fontsize=font_size).set_position([0.5, 0.95]), plt.xticks( []), plt.yticks([]) index = index + 1 for i in range(0, x_class_mean.shape[1]): title = str("Class Mean " + str(i + 1)) plt.subplot(rows, cols, index), plt.imshow(np.reshape(x_class_mean[:, i], (46, 56)).T, cmap='gist_gray') plt.title(title, fontsize=font_size).set_position( [0.5, 0.95]), plt.xticks([]), plt.yticks([]) index = index + 1 if show == 'yes': plt.show() if save == 'yes': plt.savefig('Global and Class Mean') plt.close()
def plot_sleep(label, pred, file_time, kfold, name): x = range(0, len(label)) y = np.arange(5) y_stage = ["W", "REM", "N1", "N2", "N3"] plt.figure(figsize=(24, 8)) plt.ylabel("Sleep Stage") plt.xlabel("Sleep Time") time_choice = np.array([ s.decode('UTF-8') for s in file_time[0:len(file_time):int(len(file_time) / 10)] ]) plt.xticks(range(0, len(file_time), int(len(file_time) / 10)), time_choice) ##为了将坐标刻度设为字 plt.yticks(y, y_stage) ##为了将坐标刻度设为字 # plot中参数的含义分别是横轴值,纵轴值,线的形状,颜色,透明度,线的宽度和标签 plt.plot(x, pred, 'r-', color='blue', alpha=1, linewidth=1, label='predict') plt.plot(x, label, 'r-', color='red', alpha=1, linewidth=1, label='label') plt.legend(loc='best') plt.savefig(sleepPicture_path + str(kfold) + "sdt" + str(name) + ".svg") ##保存睡眠模型图文件 plt.close()
def chartData(data, keyword): #Takes input of the results of the fts search and the phrase that was searched for #and creates bar chart of occurences by book for the phrase from matplotlib import pyplot as plt import numpy as np import math data = sorted(data, key=lambda x: x[1], reverse=True) info = []#number of occurences books = []#list of books for d in data: info.append(d[1]) b = d[0] books.append(b[b.find('LIBER'):])#Use only book number for label since name is the same for all books #create chart plt.close() fig = plt.figure() width = 0.4 ind = np.arange(len(books)) plt.bar(ind, info, width=width) plt.xticks(ind + width/2., books) plt.yticks(np.arange(0,max(info)*2,math.ceil(max(info)/5))) plt.ylabel('Number of Occurences') plt.xlabel('Books') plt.title('Occurences of "' + keyword + '" by book in Curtius Rufus (Latin)') fig.autofmt_xdate() plt.show(block=False)#display plot, and continue with program
def shist(self,data,sflag,spath,sname,pflag): g.tprinter('Running sist',pflag) xdata=data[:,0] ydata=data[:,1] plt.plot(xdata,ydata,'ro') plt.savefig(os.path.join(spath,str(sname))+'.pdf') plt.close()
def plotConfusionMatrix(lbllist, predlist, classes, type): confusionMatrix = confusion_matrix(lbllist, predlist) # print(confusionMatrix) plt.imshow(confusionMatrix, interpolation="nearest", cmap=plt.cm.Blues) if type == 'train': plt.title("Confusion matrix training") elif type == 'test': plt.title("Confusion matrix testing") plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = "d" thresh = confusionMatrix.max() / 2. for i, j in itertools.product(range(confusionMatrix.shape[0]), range(confusionMatrix.shape[1])): plt.text(j, i, format(confusionMatrix[i, j], fmt), horizontalalignment="center", color="white" if confusionMatrix[i, j] > thresh else "black") plt.tight_layout() plt.ylabel("True label") plt.xlabel("Predicted label") # plt.show() if type == 'train': plt.savefig(LOG_PATH + 'Confusion matrix training.png') elif type == 'test': plt.savefig(LOG_PATH + 'Confusion matrix testing.png') plt.close()
def plot_stacked_barchart(self, dataframe, sort, title, xlable, ylable, kurs): x = [] tutor = [] y = [] for i in dataframe['tutor']: if i not in tutor: tutor.append(i) y.append([]) for i, elem in enumerate(dataframe[sort]): print(y, elem) if elem in x: y[tutor.index(dataframe['tutor'][i])][x.index(elem)] += 1 else: x.append(elem) for j, elem2 in enumerate(tutor): y[j].append(0) y[tutor.index(dataframe['tutor'][i])][x.index(elem)] += 1 for i, elem in enumerate(y): plt.bar(range(len(elem)), elem, label=tutor[i]) plt.xlabel(xlable) plt.ylabel(ylable) plt.legend(loc="best") plt.savefig('./PDFcreater/Plots/{}/{}.png'.format(kurs, title)) #plt.show() # loescht den Plot fuer den Naechsten Plot plt.clf() plt.cla() plt.close()
def print_path_prob_figure(filename, bins, histo, dx, path_prob, smooth_path_prob, cutoff=200): assert isinstance(filename, str), 'filename must be a string' filename = os.path.splitext(filename)[0] + '.png' matplotlib = try_import_matplotlib() if matplotlib is None: return else: from matplotlib import pyplot as plt figure = plt.figure(figsize=(7, 7)) s = np.sum(histo, axis=0) v1 = np.where(s >= cutoff, path_prob, 0) v2 = np.where(s < cutoff, path_prob, 0) v3 = np.where(s >= cutoff, smooth_path_prob, 0.) plt.bar(bins[:-1], v1, width=dx, align='edge', color='red', alpha=1) plt.bar(bins[:-1], v2, width=dx, align='edge', color='red', alpha=0.7) plt.plot(bins[:-1] + dx / 2, v3, color='orange') plt.ylabel('pathogenicity prob.') plt.xlabel('predicted score') plt.ylim((0, 1)) figure.savefig(filename, format='png', bbox_inches='tight') plt.close() plt.rcParams.update(plt.rcParamsDefault) LOGGER.info(f'Pathogenicity plot saved to {filename}')
def plot_projected_3faces_onto_fisherspace(Wopt,X_train,Y_train,Mpca,mode): if mode == 'none': return None projected = np.dot(Wopt.T,X_train.T) projected = projected.T fig = plt.figure() ax = fig.add_subplot(111, projection='3d') label = 0 for i in range(0,24): Label = Y_train[(label)*8+i] x_train = projected[(label)*8+i][0] y_train = projected[(label)*8+i][1] z_train = projected[(label)*8+i][2] ax.text(x_train,y_train,z_train,str(Label), color="black", fontsize=12) if i == 0: ax.scatter(x_train,y_train,z_train, c='black', marker='o', s=5, label='Training Data') else: ax.scatter(x_train,y_train,z_train, c='black', marker='o', s=5) ax.legend(loc = 'lower right') title = str("Projection of first 3 Classes with Mpca="+str(Mpca)+" into best 3 Principal Components") plt.title(title) if mode == 'show': plt.show() plt.close() if mode == 'save': plt.savefig(title) plt.close()
def plot_df( df1, df2, plot_title, x_axis, y_axis, plot, save ): # function for plotting high-dimension and low-dimension eigenvalues y1 = df1[df1.columns[1]] x1 = df1['M'] y2 = df2[df2.columns[1]] x2 = df2['M'] plt.figure(figsize=(8, 8)) plt.plot(x1, y1, color='red') plt.plot(x2, y2, color='blue') plt.grid(color='black', linestyle='-', linewidth=0.1) # parameters for plot grid plt.xticks(np.arange(0, max(x1) * 1.1, int(max(x1) / 10))) # adjusting the intervals to 250 plt.yticks(np.arange(0, max(y1) * 1.1, int(max(y1) / 10))) plt.title(plot_title).set_position([0.5, 1.05]) plt.xlabel(x_axis) plt.ylabel(y_axis) plt.legend(loc='best') # creating legend and placing in at the top right if save == 'yes': plt.savefig(plot_title) if plot == 'yes': plt.show() plt.close()
def fnctn(a,c): df2 = pd.DataFrame(data.groupby(a)[c].count()) df2=df2.astype(float) plot1 = plt.bar(x=df2.index,y=df2.iloc[:,0]) plot1.set_xticklabels(plot1.get_xticklabels(), rotation=30, fontsize=6) plot1.figure.savefig("./static/q18.jpg") plt.close()
def forward(self, x): # polar plot dic = creatRealDictionary(self.T, self.rr, self.theta, self.gid) sparsecode = fista(dic, x, self.lam, 100, self.gid) if random.randint(1, 20) == 1: plt.figure() plt.pcolormesh(sparsecode[0, :, :].data.cpu().detach().numpy(), cmap='RdBu') plt.colorbar() plt.savefig('C_evolution_subsIni.png') #, dpi=200 # plt.show() plt.close() rr = self.rr.data.cpu().detach().numpy() theta = self.theta.data.cpu().detach().numpy() ax = plt.subplot(1, 1, 1, projection='polar') ax.scatter(0, 1, c='black') # unactive poles ax.scatter(theta, rr) ax.scatter(-theta, rr) ax.scatter(np.pi - theta, rr) ax.scatter(theta - np.pi, rr) # ax.set_rmax(1.2) ax.set_title("Dictionary", va='bottom') plt.savefig('usedPolesDCT.png') # plt.show() plt.close() return Variable(sparsecode)
def print_pred_distrib_figure(filename, bins, histo, dx, J_opt): assert isinstance(filename, str), 'filename must be a string' filename = os.path.splitext(filename)[0] + '.png' matplotlib = _try_import_matplotlib() if matplotlib is None: return else: from matplotlib import pyplot as plt figure = plt.figure(figsize=(7, 7)) plt.bar(bins[:-1], histo[0], width=dx, align='edge', color='blue', alpha=0.7, label='neutral') plt.bar(bins[:-1], histo[1], width=dx, align='edge', color='red', alpha=0.7, label='deleterious') plt.axvline(x=J_opt, color='k', ls='--', lw=1) plt.ylabel('distribution') plt.xlabel('predicted score') plt.legend() figure.savefig(filename, format='png', bbox_inches='tight') plt.close() plt.rcParams.update(plt.rcParamsDefault) LOGGER.info(f'Predictions distribution saved to {filename}')
def plotFeatImportance(pathOut, imp, oob, oos, method, tag=0, simNum=0, **kargs): # plot mean imp bars with std mpl.figure(figsize=(10, imp.shape[0] / 5.)) imp = imp.sort_values('mean', ascending=True) ax = imp['mean'].plot(kind='barh', color='b', alpha=0.25, xerr=imp['std'], error_kw={'ecolor': 'r'}) if method == 'MDI': mpl.xlim([0, imp.sum(axis=1).max()]) mpl.axvline(1. / imp.shape[0], lw=1., color='r', ls='dotted') ax.get_yaxis().set_visible(False) for i, j in zip(ax.patches, imp.index): ax.text(i.get_width() / 2, i.get_y() + i.get_height() / 2, j, ha='center', va='center', color='k') mpl.title('tag=' + tag + ' | simNUm=' + str(simNum) + ' | oob=' + str(round(oob, 4)) + ' | oos=' + str(round(oos, 4))) mpl.savefig(pathOut + 'featImportance_' + str(simNum) + '.png', dpi=100) mpl.clf() mpl.close() return
def print_ROC_figure(filename, fpr, tpr, auc_stat): assert isinstance(filename, str), 'filename must be a string' filename = os.path.splitext(filename)[0] + '.png' matplotlib = _try_import_matplotlib() if matplotlib is None: return else: from matplotlib import pyplot as plt fig = plt.figure(figsize=(7, 7)) plt.plot([0, 1], [0, 1], linestyle='--', lw=1, color='k') plt.plot(fpr, tpr, linestyle='-', lw=2, color='r', label='AUROC = {:.3f} +/- {:.3f}'.format(*auc_stat)) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('mean ROC curve from cross-validation') plt.legend(loc="lower right") fig.savefig(filename, format='png', bbox_inches='tight') plt.close() plt.rcParams.update(plt.rcParamsDefault) LOGGER.info(f'ROC plot saved to {filename}')
def plot_3df( df, plot_title, x_axis, y_axis, plot, save ): # function for plotting high-dimension and low-dimension eigenvalues x1 = df[df.columns[0]] y1 = df[df.columns[1]] y2 = df[df.columns[2]] y3 = df[df.columns[3]] min1 = df[df.columns[1]].min() min2 = df[df.columns[2]].min() min3 = df[df.columns[3]].min() df_min = min(min1, min2, min3) plt.figure(figsize=(8, 8)) plt.plot(x1, y1, color='red') plt.plot(x1, y2, color='blue') plt.plot(x1, y3, color='green') plt.grid(color='black', linestyle='-', linewidth=0.1) # parameters for plot grid plt.xticks(np.arange(0, max(x1) * 1.1, int(max(x1) / 10))) # adjusting the intervals to 250 plt.yticks(np.arange(df_min * 0.9, 100, int(max(y1) / 10))) plt.title(plot_title).set_position([0.5, 1.05]) plt.xlabel(x_axis) plt.ylabel(y_axis) plt.legend(loc='best') # creating legend and placing in at the top right if save == 'yes': plt.savefig(plot_title) if plot == 'yes': plt.show() plt.close()
def plotTrainingAccuracy(trainAccuracyPerIteration): dataFrame, fullAccuracyList, finalAccuracyList = getOptimizerLists( trainAccuracyPerIteration) styles = [] colors = [] for i in range(0, len(trainAccuracyPerIteration)): styles.append('.--') colors.append('grey') styles[finalAccuracyList.index(max(finalAccuracyList))] = '.-' colors[finalAccuracyList.index(max(finalAccuracyList))] = 'green' styles[finalAccuracyList.index(min(finalAccuracyList))] = '.-' colors[finalAccuracyList.index(min(finalAccuracyList))] = 'red' dataFrame.plot(x='Epoch', y=fullAccuracyList, style=styles, color=colors, legend=False) # plt.xticks(rotation=45) plt.title("Accuracy performance training") plt.xlabel("Epoch") plt.ylabel("Accuracy (batch)") # plt.show() plt.savefig(LOG_PATH + 'Training accuracy.png') plt.close()
def plotPC(PC1, PC2, labelList): """Plots a scatter plot of the any 2 specified dimensions after running PCA.""" pc1 = [[], [], [], [], [], [], [], [], [], []] pc2 = [[], [], [], [], [], [], [], [], [], []] for l in range(len(labelList)): # l returns a number within a numpy array actualNum = labelList[l][0] pc1[actualNum].append(PC1[l]) pc2[actualNum].append(PC2[l]) fig = plt.figure() ax = fig.add_subplot(111) colorList = [ "red", "green", "blue", "black", "gray", "yellow", "cyan", "magenta", "burlywood", "purple" ] for count in range(10): plt.scatter(pc1[count], pc2[count], c=colorList[count], lw=0, label=str(count)) plt.legend(scatterpoints=1) ax.set_xlabel("PC1") ax.set_ylabel("PC2") fig.savefig("2D_10MNistGraph.png") plt.close()
def write_pc_hist(df, p, args): # Pivot, and then drop the "cycles" level of the multi-index. df = pd.pivot_table(df, index=["pc"], columns="operation") df = df.fillna(0) df = df.droplevel(level=0, axis="columns") # Use the colors key order above to stack the bars, # but first we have to pick stalls that are actually IN the CSV (not all are printed) cols = [k for k in colors.keys() if k in df.columns] df = df[cols] # Remove all PCs that were specified using the without flag filts = {int(pc, 16) for pc in args.without} fi = [pc for pc in df.index if int(pc, 16) not in filts] removed = [pc for pc in df.index if int(pc, 16) in filts] df = df.loc[fi] print(f"Removed PCs: {removed}") height = df.shape[0] * (labelsize + 4) / 72 ax = df.plot.barh(stacked=True, figsize=(11, height), color=colors) ax.set_ylabel("Program Counter") ax.set_xlabel(f"Cycles * 10^{math.floor(math.log10(ax.get_xlim()[1]))}") ax.set_title(f"HammerBlade Program Counter Cycles Histogram") ax.tick_params(labelsize=labelsize) fig = ax.get_figure() plt.gca().invert_yaxis() plt.legend(loc="upper left") plt.tight_layout() fig.savefig(p / "pc_hist.pdf") plt.close(fig)
def generate_hashtag_top_five_piechart(self): #This function generates pie chart for different attributs of tweets that we collected. tweet_attribute = tweets_by_hashtag(self.tweet_frame) fig = tweet_attribute[0:5].plot.pie(figsize=(10, 10)) fig.set_title('Pie chart of Top 5 ' + str(self.input_string)) plt.savefig('Pie chart of Top 5 ' + str(self.input_string) + '.pdf') plt.show() plt.close()
def fnctn(a,c): df2 = pd.DataFrame(data.groupby(a)[c].count()) df2=df2.astype(float) plot = df2.plot.pie(y=c, figsize=(20, 20), autopct='%1.0f%%', pctdistance=1.1, labeldistance=1.2, textprops={'fontsize': 18}) print "xyz" plt.show() plot.figure.savefig("./static/q18.jpg") plt.close()
def write_bb_hist(df, p, args): # Pivot, and then drop the "cycles" level of the multi-index. df = pd.pivot_table(df, index=["pc"], columns="operation") df = df.fillna(0) df = df.droplevel(level=0, axis="columns") # Group together floating point and regular instructionos tot_instrs = df.Instruction + df["FPU Instruction"] # Group together PCs that have the same number of executions bb_ranges = (tot_instrs != tot_instrs.shift()).cumsum() df = df.groupby(bb_ranges).sum() # Get the new grouped index bb_tups = [(bb_ranges[bb_ranges == x].index.min(), bb_ranges[bb_ranges == x].index.max()) for x in df.index] bb_ranges = [range(int(x, 16), int(y, 16) + 1) for (x, y) in bb_tups] # Filter BBs that include PCs that were specified with --without filts = {int(pc, 16) for pc in args.without} df.index = [x + "-" + y for (x, y) in bb_tups] fi = [ x + "-" + y for (x, y) in bb_tups if (all(e not in range(int(x, 16), int(y, 16) + 1) for e in filts)) ] removed = [ x + "-" + y for (x, y) in bb_tups if (any(e in range(int(x, 16), int(y, 16) + 1) for e in filts)) ] # TODO: Print filtered BBs on graph? print(f"Removed Basic Blocks: {removed}") df = df.loc[fi] ipc = (df.Instruction + df["FPU Instruction"]) / df.sum(axis=1) pct = 100.0 * df.sum(axis=1) / df.sum(axis=1).sum() idx = df.index.to_series() idx = idx.combine(pct, lambda i, pct: f"{i} ({pct:.0f}%".rjust(10)) idx = idx.combine(ipc, (lambda i, ipc: f"{i} @ {ipc:1.3f})")) df.index = idx # Use the colors key order above to stack the bars, # but first we have to pick stalls that are actually IN the CSV (not all are printed) cols = [k for k in colors.keys() if k in df.columns] height = df.shape[0] * (labelsize + 4) / 72 ax = df[cols].plot.barh(stacked=True, figsize=(11, height), color=colors) ax.set_ylabel("Basic Block Range (% Cycles @ IPC)") ax.set_xlabel(f"Cycles * 10^{math.floor(math.log10(ax.get_xlim()[1]))}") ax.set_title(f"HammerBlade Basic Block Cycles Histogram") ax.tick_params(labelsize=labelsize) fig = ax.get_figure() plt.gca().invert_yaxis() plt.legend(loc="upper right") plt.tight_layout() fig.savefig(p / "bb_hist.pdf") plt.close(fig)
def Histogram(filename): volume = ReadInAttributeFromCSV(filename, 'Personal Injury') plt.title('Annual Personal Injury') plt.hist(volume, color='black') plt.ylabel('Number of') plt.xlabel('Seasons') plt.savefig('visual') plt.close()
def fnctn(a,c): #os.remove(filename) df2 = pd.DataFrame(data.groupby(a)[c].sum()) df2=df2.astype(float) plot1 = plt.plot(df2.index,df2[c]) plt.xticks(fontsize=10, rotation=30) #plt.set_size_inches(8, 6) plt.savefig("./static/q18.jpg") plt.close() plt.show()
def plot_pie(self, nx_dataframe, topic, se_title, kurs): gender = self.sort_column(nx_dataframe[topic]) labels = [gender[0][i] for i,elem in enumerate(gender[0])] fracs = [gender[1][i] for i,elem in enumerate(gender[1])] explode = [0.05 for i,elem in enumerate(gender[1])] plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) plt.savefig('./PDFcreater/Plots/{}/1{}.png'.format(kurs,se_title)) plt.clf() plt.cla() plt.close()
def plot_boring_barchart(self,dataframe,x,y,title,xlable,ylable, kurs): plt.bar(x, y, color='blue') #plt.title(title) plt.xlabel(xlable) plt.ylabel(ylable) plt.savefig('./PDFcreater/Plots/{}/{}.png'.format(kurs,title)) #loescht den Plot fuer den Naechsten Plot plt.clf() plt.cla() plt.close()
def feature_summary(x_col, y_col, show_r2=False): """Gives a summary of a feature :return: """ # Preparation x_name = x_col.name y_name = y_col.name df = pd.concat([x_col, y_col], axis=1).sort_index() plt.rcParams["figure.figsize"] = (10, 7) breaks(1) print("%s" % x_name) print('Quantile:\n', x_col.quantile([0.0, 0.1, 0.25, 0.5, 0.75, 1.0])) # Histogram plt.subplot(221) try: plt.hist(x_col, bins=30) plt.xlabel(x_name) plt.title('Histogram (CF GHP): %s' % x_name) except ValueError: print("No histogram for %s available" % x_name) # Correlation if y_name != x_name: df = df.sort_values(x_name) # df[x_name + "_2"] = df[x_name] * df[x_name] # df[x_name + "_3"] = df[x_name] * df[x_name] * df[x_name] x = df.drop(y_name, 1) reg = linear_model.LinearRegression(normalize=True) reg.fit(x, df[y_name]) # Plot plt.subplot(222) plt.scatter(df[x_name], df[y_name]) plt.plot(df[x_name], reg.predict(x), color='g') plt.xlabel(x_name) plt.xlim([df[x_name].min(), df[x_name].max()]) plt.title('x:%s / y:%s ' % (x_name, y_name)) plt.ylabel("Target function: %s" % y_name) if show_r2: print("R²:", r2_score(df[y_name], reg.predict(x))) print(feature_importance(x, reg.coef_)) # Show plots plt.show() # Timeline x_col.rolling(window=10, center=False).mean().plot(title='%s: Timeline' % x_name, figsize=(10, 2), xlim=(170000, 175000)) plt.show() plt.close('all') return " "
def draw_boxes_on_image(image_path: str, boxes: np.ndarray, scores: np.ndarray, labels: np.ndarray, label_names: List[str], score_thresh: float = 0.5, save_path: str = 'result'): """Draw boxes on images.""" image = np.array(PIL.Image.open(image_path)) plt.figure() _, ax = plt.subplots(1) ax.imshow(image) image_name = image_path.split('/')[-1] print("Image {} detect: ".format(image_name)) colors = {} for box, score, label in zip(boxes, scores, labels): if score < score_thresh: continue if box[2] <= box[0] or box[3] <= box[1]: continue label = int(label) if label not in colors: colors[label] = plt.get_cmap('hsv')(label / len(label_names)) x1, y1, x2, y2 = box[0], box[1], box[2], box[3] rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, linewidth=2.0, edgecolor=colors[label]) ax.add_patch(rect) ax.text(x1, y1, '{} {:.4f}'.format(label_names[label], score), verticalalignment='bottom', horizontalalignment='left', bbox={ 'facecolor': colors[label], 'alpha': 0.5, 'pad': 0 }, fontsize=8, color='white') print("\t {:15s} at {:25} score: {:.5f}".format( label_names[int(label)], str(list(map(int, list(box)))), score)) image_name = image_name.replace('jpg', 'png') plt.axis('off') plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig("{}/{}".format(save_path, image_name), bbox_inches='tight', pad_inches=0.0) plt.cla() plt.close('all')
def imgOut(epoch, generator): rand_nums = np.random.randint(0, x_test_hr.shape[0], size=1) image_batch_hr = denormalize(x_test_hr[rand_nums]) image_batch_lr = x_test_lr[rand_nums] gen_img = generator.predict(image_batch_lr) generated_image = denormalize(gen_img) image_batch_lr = denormalize(image_batch_lr) image_batch_bc = upsample(image_batch_lr, 4) plt.figure(figsize=(15, 5)) dim = (1, 4) # 4 wide # lowres plt.subplot(dim[0], dim[1], 1) plt.title('Low Res') plt.imshow(image_batch_lr[0], interpolation='nearest') plt.axis('off') # naive resize plt.subplot(dim[0], dim[1], 2) plt.title('Naive Resize') plt.imshow(image_batch_bc[0], interpolation='nearest') plt.axis('off') # generated plt.subplot(dim[0], dim[1], 3) plt.title('Generated SR') plt.imshow(generated_image[0], interpolation='nearest') plt.axis('off') # truth plt.subplot(dim[0], dim[1], 4) plt.title('Truth') plt.imshow(image_batch_hr[0], interpolation='nearest') plt.axis('off') # save file plt.tight_layout() plt.savefig(imgSav % epoch) plt.close('all') # learning gif images me_dir = os.path.join('C:\\', 'Users', 'cruze', 'Documents', 'CS767', 'finalProj--') me_path = os.path.join(me_dir, 'lowresme.jpg') me = Image.open(me_path) me = np.expand_dims(me, axis=0) me_lr = np.array(me) me_lr_norm = normalize(me_lr) gen_img = generator.predict(me_lr_norm) generated_image = denormalize(gen_img) plt.imshow(generated_image[0]) plt.savefig(imgMeSav % epoch) plt.close('all')
def cm_plot(original_label, predict_label, kunm, pic=None): prec_score = precision_score(original_label, predict_label, average=None) recall = recall_score(original_label, predict_label, average=None) f1 = f1_score(original_label, predict_label, average=None) cm = confusion_matrix(original_label, predict_label) cm_new = np.empty(shape=[5, 5]) for x in range(5): t = cm.sum(axis=1)[x] for y in range(5): cm_new[x][y] = round(cm[x][y] / t * 100, 2) plt.figure() plt.matshow(cm_new, cmap=plt.cm.Blues) plt.colorbar() x_numbers = [] y_numbers = [] cm_percent = [] for x in range(5): y_numbers.append(cm.sum(axis=1)[x]) x_numbers.append(cm.sum(axis=0)[x]) for y in range(5): percent = format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f") cm_percent.append(str(percent)) plt.annotate(format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f"), xy=(y, x), horizontalalignment='center', verticalalignment='center', fontsize=10) plt.ylabel('True label') plt.xlabel('Predicted label') plt.title('confusion matrix') y_stage = [ "W\n(" + str(y_numbers[0]) + ")", "N1\n(" + str(y_numbers[1]) + ")", "N2\n(" + str(y_numbers[2]) + ")", "N3\n(" + str(y_numbers[3]) + ")", "REM\n(" + str(y_numbers[4]) + ")" ] x_stage = [ "W\n(" + str(x_numbers[0]) + ")", "N1\n(" + str(x_numbers[1]) + ")", "N2\n(" + str(x_numbers[2]) + ")", "N3\n(" + str(x_numbers[3]) + ")", "REM\n(" + str(x_numbers[4]) + ")" ] y = [0, 1, 2, 3, 4] plt.xticks(y, x_stage) plt.yticks(y, y_stage) #sns.heatmap(cm_percent, fmt='g', cmap="Blues", annot=True, cbar=False, xticklabels=x_stage, yticklabels=y_stage) # 画热力图,annot=True 代表 在图上显示 对应的值, fmt 属性 代表输出值的格式,cbar=False, 不显示 热力棒 plt.savefig(savepath + "matrix" + str(kunm) + ".svg") #plt.show() plt.show() plt.close() # plt.savefig("/home/data_new/zhangyongqing/flx/pythoncode/"+str(knum)+"matrix.jpg") return kappa(cm), classification_report(original_label, predict_label)
def plot_summary_to_pdf(outfile, spath='./*.sum'): files = glob.glob(spath) with PdfPages(outfile) as pdf: for f in files: print(f) sum_f = Summary() sum_f.read(f) sum_f.data.plot(subplots=True, figsize=(10, 10), title=str(f)) pdf.savefig() # saves the current figure into a pdf page plt.close()
def _render_to_rgb(self): """ convert the output of render_to_figure to a rgb_array """ self._render_to_figure() self._figure.canvas.draw() buf = self._figure.canvas.tostring_rgb() num_cols, num_rows = self._figure.canvas.get_width_height() plt.close(self._figure) self._figure = None result = np.fromstring(buf, dtype=np.uint8).reshape(num_rows, num_cols, 3) return result
def print_scatter_data(): import matplotlib.pylab as plt filename = Par.dirname + ('/Scatter.dat') fitnesses = [] self_reliences = [] life_times = [] self_reliences_dead = [] for Agent in Par.Agents: if Agent.dead != True: fitnesses.append(Agent.fitness) Needs = Agent.needs Production = Agent.production selfReli = [0.0]*Par.num_resources for i in range(Par.num_resources): selfReli[i] = Production[i]*Needs[i] self_reliences.append(abs(sum(selfReli))) else: life_time = Agent.t_death - Agent.t_discovery life_times.append(life_time) Needs = Agent.needs Production = Agent.production selfReli = [0.0]*Par.num_resources for i in range(Par.num_resources): selfReli[i] = Production[i]*Needs[i] self_reliences_dead.append(abs(sum(selfReli))) file =open(filename, 'w') for i in range(len(fitnesses)): s= str(fitnesses[i]) +' '+ str(self_reliences[i]) file.write(s) file.write('\n') file.close() plt.scatter(self_reliences, fitnesses) plt.ylabel('Fitness') plt.xlabel('self_reliences') plt.savefig('FitnessVSR.png') plt.close() plt.scatter(self_reliences_dead, life_times) plt.ylabel('LifeTimes') plt.xlabel('self_reliences') plt.savefig('LifeTimeVSR.png') plt.close()
def plot_data(): import matplotlib.pylab as plt t, suffering = np.loadtxt('suffering.dat', unpack= True, usecols = (0,1)) t, fitness = np.loadtxt('fitness.dat', unpack = True, usecols = (0,1)) plt.plot(t, suffering) plt.xlabel('t') plt.ylabel('suffering') plt.savefig('suffering.png') plt.close() plt.plot(t, fitness) plt.xlabel('t') plt.ylabel('fitness') plt.savefig('fitness.png') plt.close()
def __save(self,n,plot,sfile): p.figure(figsize=sfile) p.xlabel(plot.xlabel) p.ylabel(plot.ylabel) p.xscale(plot.xscale) p.yscale(plot.yscale) p.grid() for curve in plot.curves: if curve[1] == None: p.plot(curve[0],curve[2], label=curve[3]) else: p.plot(curve[0], curve[1], curve[2], label=curve[3]) p.rc('legend', fontsize='small') p.legend(shadow=0, loc='best') p.axes().set_aspect(plot.aspect) if not plot.dir: plot.dir = './plots/' if not plot.name: plot.name = self.__global_name+'_%0*i'%(2,n) if not os.path.isdir(plot.dir): os.mkdir(plot.dir) if plot.pgf: p.savefig(plot.dir+plot.name+'.pgf') else: p.savefig(plot.dir+plot.name+'.pdf', bbox_inches='tight') p.close()