def animate_plotting(subdir_path,): average_filename = 'averaged_out.txt' if os.path.exists( os.path.join(subdir_path,average_filename) ): print(subdir_path+average_filename+' already exists please use hotPlot.py') #import existing data for average at the end # data_out = numpy.genfromtxt(os.path.join(subdir_path,average_filename)) # averaged_data = numpy.array(data_out[:,1]) # angles = data_out[:,0] #os.remove( os.path.join(subdir_path,average_filename)) else: files = os.listdir(subdir_path) #files = [d for d in os.listdir(subdir_path) if os.path.isdir(os.path.join(subdir_path, d))] onlyfiles_path = [os.path.join(subdir_path,f) for f in files if os.path.isfile(os.path.join(subdir_path,f))] onlyfiles_path = natsort.natsorted(onlyfiles_path) averaged_data = [] angles = [] for f in onlyfiles_path: data = numpy.genfromtxt(f,delimiter = ',') #data = pandas.read_csv(f) averaged_data.append(numpy.mean(data)) angle = os.path.basename(f).split('_')[0] angles.append(float(angle)) fig = plt.plot(angles, averaged_data,'o') plt.yscale('log') plt.xscale('log') plt.legend(loc='upper right') plt.title(base_path) plt.grid(True) plt.xlabel(r'$\theta$ $[deg.]}$') #plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$') plt.ylabel(r'I($\theta$) $[a.u.]$')
def genCurve(dataSet, tree): x = [] # stores the x axis of the graph trainList = [] # the list of accuracies derived from training data valList = [] # the list of accuracies derived from validation data i = 0 while i < 1: i = i+0.1 a = 0 b = 0 for trial in range(3): newData = sortData(dataSet, i) # MAKE THIS tree = getTree(newData) # NEED TO GET THIS FUNCTION WHEN TREEGEN WORKS a = a + model_validation.validateTree(tree, newData) b = b + model_validation.validateTree(tree, newData) a = float(a)/3 b = float(b)/3 trainList.append(a) valList.append(b) x.append(i) plt.plot(x, trainList) plt.plot(x, valList) plt.xlabel('percent training used') plt.ylabel('percent accuracy') plt.title('learning curve') plt.show()
def plotColorCodedNetworkSpikes(network): assert network is not None, "Network is not initialised! Visualising failed." import matplotlib as plt from NetworkBuilder import sameDisparityInd cellsOutSortedByDisp = [] spikes = [] for disp in range(0, maxDisparity+1): cellsOutSortedByDisp.append([network[x][2] for x in sameDisparityInd[disp]]) spikes.append([x.getSpikes() for x in cellsOutSortedByDisp[disp]]) sortedSpikes = sortSpikesByColor(spikes) print sortedSpikes framesOfSpikes = generateColoredFrames(sortedSpikes) print framesOfSpikes fig = plt.figure() initialData = createInitialisingDataColoredPlot() imNet = plt.imshow(initialData[0], c=initialData[1], cmap=plt.cm.coolwarm, interpolation='none', origin='upper') plt.xticks(range(0, dimensionRetinaX)) plt.yticks(range(0, dimensionRetinaY)) plt.title("Disparity Map {0}".format(disparity)) args = (framesOfSpikes, imNet) anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30) plt.show()
def main(): #Before anything happens, number of command-line arguments is checked and appropriate action taken. argumnumber() if (len(sys.argv) < 2): file = raw_input("Please provide a sorted_models file: ") else: file = sys.argv[1] #Prompts user to provide maxtot and maxinter before progam continues. global maxtot maxtot = float(raw_input("Please enter maximum total_score: ")) global maxinter maxinter = float(raw_input("Please enter maximum interface_delta_X: ")) #Imports DataFrame and filters based on max values provided. models_raw = pd.read_csv( file, sep=' ', names=['model', 'total_score', 'interface_delta_X']) models = models_raw.loc[(models_raw['total_score'] <= maxtot) & (models_raw['interface_delta_X'] <= maxinter)] sumavrg = ( (np.sum(models['total_score']) + np.sum(models['interface_delta_X'])) / (len(models['total_score']))) #Appends a column to models that contains the sum of total_score and interface_delta_X sumarr = (models['total_score'] + models['interface_delta_X']) models['add'] = sumarr #Finds values with lowest sum modhi = models.loc[models['add'] > sumavrg] modlo = models.loc[models['add'] <= sumavrg] minidx = models['add'].idxmin() xmin = models.iloc[minidx]['total_score'] ymin = models.iloc[minidx]['interface_delta_X'] #Creates the plot. x1 = modlo['total_score'] y1 = modlo['interface_delta_X'] x2 = modhi['total_score'] y2 = modhi['interface_delta_X'] plt.figure(figsize=[16, 9]) plot1 = plt.scatter(x1, y1, s=2, c='Green', marker='.') plot2 = plt.scatter(x2, y2, s=2, c='Red', marker='.') plt.tick_params(axis='both', direction='inout', width=1, length=6, labelsize=13, pad=4) plt.title('interface_delta_x vs total_score', size=16) plt.xlabel("total_score", fontsize=13) plt.ylabel("interface_delta_X", fontsize=13) plt.legend(['Sum <= average', 'Sum > average'], markerscale=7, fontsize=12) plt.annotate(xy=(xmin, ymin), s="Lowest sum: total_score: " + str(xmin) + "; interface_delta_X: " + str(ymin), textcoords='axes fraction', xytext=(0.6, 0.05)) printtofile() plt.show()
def log_transform(data, columns, plot=True, figsize=(12, 6)): ''' Nomralizes the dataset to be as close to the gaussian distribution. Parameter: ----------------------------------------- data: DataFrame, Series. Data to Log transform. columns: List, Series Columns to be transformed to normality using log transformation plot: bool, default True Plots a before and after log transformation plot Returns: Log-transformed dataframe ''' if data is None: raise ValueError( "data: Expecting a DataFrame/ numpy2d array, got 'None'") if columns is None: raise ValueError( "columns: Expecting at least a column in the list of columns but got 'None'" ) df = data.copy() for col in columns: df[col] = np.log1p(df[col]) if plot: for col in columns: _ = plt.figure(figsize=figsize) plt.subplot(1, 2, 1) sns.distplot(data[col], color="m", label="Skewness : %.2f" % (df[col].skew())) plt.title('Distribution of ' + col + " before Log transformation") plt.legend(loc='best') plt.subplot(1, 2, 2) sns.distplot(df[col], color="m", label="Skewness : %.2f" % (df[col].skew())) plt.title('Distribution of ' + col + " after Log transformation") plt.legend(loc='best') plt.tight_layout(2) plt.show() return df
def histogram(df, nbin, name, k): plt.figure() n, bins, patches = plt.hist(df['Mean_' + name], nbin, density=True, facecolor='g', alpha=0.75) plt.title('Histogram of ' + name + ' ' + k + 's') plt.grid(True) plt.show()
def histo(column): mpg = pandas.read_csv("mpg.csv") plt.clf() if column in list(mpg.column): plt.hist(column) plt.title(column) plt.savefig("static/histo.png") else: print("There is no such an attribute in the given data.") return app.send_static_file("static/histo.png")
def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" pl.figure(figsize=(1.8 * n_col, 2.4 * n_row)) pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): pl.subplot(n_row, n_col, i + 1) pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray) pl.title(titles[i], size=12) pl.xticks(()) pl.yticks(())
def draw_image(byte_array, img_title): img_byte_array_len = len(np.ravel(byte_array)) dim = int(np.sqrt(img_byte_array_len)) if not ENABLE_IMAGE_SHOW: return plt.imshow(byte_array.reshape(dim, dim), interpolation='None', cmap=cm.gray) plt.title(img_title) show()
def makeFig(): plt.ylim(0, 40) # Set y min and max values plt.title('Reading Sensor Data') # Plot title plt.grid(True) # Turn grid on plt.ylabel('Temp C') # Set y-label plt.xlabel('Reading count') plt.plot(temp_c, 'ro-', label='C`') # plot temperature plt.legend(loc='upper left') # plot egend plt.autoscale()
def plotNNFilter(units): filters = 3 fig = plt.figure(1, figsize=(20, 20)) n_columns = 6 n_rows = math.ceil(filters / n_columns) + 1 for i in range(filters): plt.subplot(n_rows, n_columns, i + 1) plt.title('Filter ' + str(i)) plt.imshow(units[0, :, :, i], interpolation="nearest", cmap="gray") plt.savefig('/Users/raghav/Documents/Uni/oc-nn/models/representation_sigmoid_dog.png')
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 train_model(result_path): X, gd = load_data(result_path) model = vgg_16(800, 800) plot_model(model, to_file='./model.png') Y_train = np.ones(X.shape[0] * 0.8) Y_test = np.ones(X.shape[0] * 0.2) sgd = SGD(lr=0.001, decay=1e-10, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='mean_squared_error', metrics=['accuracy']) model.summary() with open("./record.json", "w") as dump_f: json.dump(model.to_json(), dump_f) # split train and test data X_train, X_test, gd_train, gd_test = train_test_split(X, gd, test_size=0.2, random_state=2) # input data to model and train history = model.fit([X_train, gd_train], Y_train, batch_size=2, epochs=10, validation_data=([X_test, gd_test], Y_test), verbose=1, shuffle=True) # evaluate the model loss, acc = model.evaluate(X_test, Y_test, verbose=0) print('Test loss:', loss) print('Test accuracy:', acc) model.save_weights("./my_model.h5") file = open('./history.pkl', 'wb') pickle.dump(history.history, file) file.close() fig = plt.figure() # 新建一张图 plt.plot(history.history['acc'], label='training acc') plt.plot(history.history['val_acc'], label='val acc') plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(loc='lower right') fig.savefig('./VGG16+Unet_acc.png') fig = plt.figure() plt.plot(history.history['loss'], label='training loss') plt.plot(history.history['val_loss'], label='val loss') plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(loc='upper right') fig.savefig('./VGG16+Unet_loss.png')
def basisplot(self): """ Plots all the basis functions """ for i in range(len(self.N)): for j in range(len(self.N[i])): if self.N[i][j] != 0: x = linspace(self.points[i + j], self.points[i + j + 1], 50) y = self.coeff[i] * self.N[i][j](x) plt.plot(x, y) plt.title("Plot of the basic functions for the splines") plt.show()
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 save(self, path, show=False): if not os.path.exists(path): os.makedirs(path) plt.plot(self.x, self.y) plt.title(self.title) plt.ylabel(self.ylabel) plt.xlabel(self.xlabel) plt.legend() plt.savefig(path) if show: plt.show()
def plot_f_score(self, disag_filename): plt.figure() from nilmtk.metrics import f1_score disag = DataSet(disag_filename) disag_elec = disag.buildings[building].elec f1 = f1_score(disag_elec, test_elec) f1.index = disag_elec.get_labels(f1.index) f1.plot(kind='barh') plt.ylabel('appliance'); plt.xlabel('f-score'); plt.title(type(self.model).__name__);
def plot_f_score(self, disag_filename): plt.figure() from nilmtk.metrics import f1_score disag = DataSet(disag_filename) disag_elec = disag.buildings[building].elec f1 = f1_score(disag_elec, test_elec) f1.index = disag_elec.get_labels(f1.index) f1.plot(kind='barh') plt.ylabel('appliance') plt.xlabel('f-score') plt.title(type(self.model).__name__)
def plot_sample(x, title="", width=28, fName=None): fig = plt.figure() sample = x.reshape(width, width) # interploation can be 'nearest' to put grid at the center the pixels plt.imshow(sample, interpolation='None', cmap='gray') plt.title(title) plt.xticks([]) plt.yticks([]) if fName != None: savefig(fName, bbox_inches='tight') plt.show()
def plot_training_val_accuracy(history, epochs): plt.clf() acc = history.history['acc'] val_acc = history.history['val_acc'] plt.plot(epochs, acc, 'g', label='Training acc') plt.plot(epochs, val_acc, 'y', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
def generate_plot(array, vmin, vmax, figNumber=1): plt.figure(figNumber) plt.subplot(2,3,i) print i plt.imshow(array, vmin = vmin, vmax= vmax, interpolation = None) plt.xlabel('Sample') plt.ylabel('Line') plt.title(row[0]) cb = plt.colorbar(orientation='hor', spacing='prop',ticks = [vmin,vmax],format = '%.2f') cb.set_label('Reflectance / cos({0:.2f})'.format(incAnglerad*180.0/math.pi)) plt.grid(True)
def createPlot(): plt.title("Robot Speed") plt.ylim(0, 200) plt.ylabel("Speed (cm/s)") plt.grid(True) plt.plot(Left_Speed, 'ro-', label="Left Speed") plt.legend(loc='upper left') plt2 = plt.twinx() plt.ylim(0, 200) plt2.plot(Right_Speed, 'bo-', label="Right Speed") plt2.legend(loc='upper right')
def plot_importances(): model = TaskTrain().output().load() df_train = TaskPreprocess().output().load() df_importance = pd.Series(model.feature_importances_, index=df_train.iloc[:,:-1].columns) import matplotlib.pyplot as plt df_importance.sort_values(ascending=False).plot.bar() plt.xlabel('feature') plt.ylabel('importance') plt.title('') plt.tight_layout() plt.savefig('plot.png')
def getCommentLengthsDistribution(comments): commentsList = [] for i in range(0, len(comments)): commentsList.append(len(comments[i])) #fig, ax = plt.subplots() plt.hist(commentsList, bins=np.arange(0, 500, 10)) plt.xlabel('Number of Words in Comment') plt.ylabel('Comment Counts') plt.title('Histogram of Word Counts in Comments') plt.axvline(x=200, color='r', linestyle='dashed', linewidth=2) plt.show()
def getHistogramPGN(df): y = df.iloc[:, -1] perc_win = y.sum() / y.count() height = [1 - perc_win, perc_win] bars = ('win=0 (%)', 'win=1 (%)') y_pos = np.arange(len(bars)) plt.bar(y_pos, height) plt.xticks(y_pos, bars) plt.title("labels histogram") path = WORKING_PATH + "/___histogram.png" plt.savefig(path) return path
def print_mislabeled_images(classes, X, y, p): a = p + y mislabeled_indices = np.asarray(np.where(a == 1)) plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots num_images = len(mislabeled_indices[0]) for i in range(num_images): index = mislabeled_indices[1][i] plt.subplot(2, num_images, i + 1) plt.imshow(X[:, index].reshape(64, 64, 3), interpolation='nearest') plt.axis('off') plt.title("Prediction: " + classes[int(p[0, index])].decode("utf-8") + " \n Class: " + classes[y[0, index]].decode("utf-8"))
def plot_training_validation_loss(history): plt.clf() loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'g', label='Training loss') plt.plot(epochs, val_loss, 'y', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
def histogram_chart(plt, col, Ylabel="Frequency", Xlabel=None, Title="Histogram"): col.dropna(inplace=True) plt.hist(col) if Ylabel: plt.ylabel(Ylabel) if Xlabel: plt.xlabel(Xlabel) plt.title(Title)
def plot(self, output): plt.figure(figsize=output.fsize, dpi=output.dpi) for ii in range(0, len(self.v)): imsize = [self.t[0], self.t[-1], self.x[ii][-1], self.x[ii][0]] lim = amax(absolute(self.v[ii])) / output.scale_sat plt.imshow(self.v[ii], extent=imsize, vmin=-lim, vmax=lim, cmap=cm.gray, origin='upper', aspect='auto') plt.title("%s-Velocity for Trace #%i" % (self.comp.upper(), ii)) plt.xlabel('Time (s)') plt.ylabel('Offset (km)') #plt.colorbar() plt.savefig("Trace_%i_v%s.pdf" % (ii, self.comp)) plt.clf()
def dataset_visualisation() : groups=[1,2,3,4,5] groups_name = ["average_house_prices", "mortgage_interest_rate", "consumer_price_index", "yearly_GDP", "household_income"] i=1 #plot each column pyplot.figure() for group in groups : pyplot.subplot(len(groups),1,i) pyplot.plot(df.iloc[:,group]) pyplot.title(groups_name[i-1],y=0.5,loc='right') i += 1 pyplot.show()
def imshow(tensor, title=None): # To reconvert the tensor back to an image at the end unloader = transforms.ToPILImage() # clones the tensor so it doesn't make changes on the original image image = tensor.cpu().clone() image = image.squeeze(0) image = unloader(image) plt.imshow(image) if title is not None: plt.title(title) plt.pause(0.0001)
def train_dense(dir_train_file, dir_model_save): t = time.time() train_files = file_name(dir_train_file) for f in [16000]: for hop_len in [256.0, 512.0, 1024.0, 2048.0]: window_time = hop_len/f print(window_time) if window_time < 0.05 or window_time > 0.4: print('Skip:', f, hop_len, window_time) continue print('FREQ:', f, hop_len) t = time.time() X, Y = generateDatasets(train_files, True, 1, 1, hop_len=hop_len, freq=f,dir = dir_train_file, model="CNN") rand = np.random.permutation(np.arange(len(Y))) X = X[rand] Y = Y[rand] X = X - np.mean(X, axis=0) if X.shape[1] == 0: print("NEXT\n") continue input_shape = (X.shape[1], 1) model = model_dense(input_shape) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001), metrics=['accuracy']) earlyStopping = EarlyStopping(monitor='val_loss', min_delta=0.00001, verbose=0, mode='min', patience=15) filename = dir_model_save + '/model_CNN_' + str(f) + '_' + str(1) + '_' + str(1) + '_' + str(hop_len) + '.hdf5' checkpoint = ModelCheckpoint(filepath=filename, monitor='val_loss', verbose=0, save_best_only=True) callbacks_list = [earlyStopping, checkpoint] hist = model.fit(X, Y, epochs=100, batch_size=32, shuffle=True, validation_split=0.2, verbose=0, callbacks=callbacks_list) model.summary() print('accuracy:', max(hist.history['accuracy'])) print('val_accuracy:', max(hist.history['val_accuracy'])) plt.plot(hist.history['accuracy']) plt.plot(hist.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper left') plt.show() print('loss:', min(hist.history['loss'])); print('val_loss:', min(hist.history['val_loss'])) plt.plot(hist.history['loss']) plt.plot(hist.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper left') plt.show() print("Total training time:", (time.time()-t)/60) print("-----------------------------") print("-----------------------------") print("-----------------------------") print("-----------------------------\n\n\n")
def Plot3Data(x_data, y_data, z_data, ylabel, zlabel, plottitle, savename, LOGFILE, participant, section, savepath, verticallineindices=[0], grid=1, xlabel='Time (in Seconds)'): if DEBUG == 1: print("Plotting function called for : ", ylabel) try: #starting the plot fig = plt.figure() fig.tight_layout() plt.title(plottitle) plt.plot(x_data, y_data, 'r-', label=ylabel, linewidth=0.1) plt.plot(x_data, z_data, 'g--', label=zlabel) if DEBUG == 1: print("First few elements of the x,y and z data are : ", x_data[0:3], '\n', y_data[0:3], '\n', z_data[0:3]) if len(verticallineindices ) > 1: #Meaning the verticallineindices array is not empty for i in range(len(verticallineindices)): if verticallineindices[i] == 1: plt.axvline(x=x_data[i], linewidth='1') plt.xlabel(xlabel) plt.ylabel(str(ylabel) + ' and ' + str(zlabel)) plt.legend(loc='upper right') if grid == 1: plt.grid(color='b', linestyle='-.', linewidth=0.1) #plt.show() plt.savefig(savepath + savename, bbox_inches='tight', dpi=900, quality=100) plt.close() except Exception as e: print("Exception at the plotting function in PlottingFunctions.py : ", e) file = open(LOGFILE, 'a') writer = csv.writer(file) writer.writerow([ ' Exception in the plotting function ', ' Participant: ', participant, ' Section : ', section, ' ', ' Exception: ', e ]) file.close()
def viz_losses(filename, losses): if '.' not in filename: filename += '.png' x = history['epoch'] legend = losses.keys for v in losses.values: plt.plot(np.arange(len(v)) + 1, v, marker='.') plt.title('Loss over epochs') plt.xlabel('Epochs') plt.xticks(history['epoch'], history['epoch']) plt.legend(legend, loc = 'upper right') plt.savefig(filename)
def plotLoss(train, test): import matplotlib as plt plt.plot(train) plt.plot(test) plt.title('Model loss') plt.ylabel('Loss') plt.ylim(10**-1.5, 10**3) plt.yscale('log') plt.xlabel('Epoch') plt.legend(['Train', 'Validation'], loc='upper left') plt.savefig('data/loss.png') # Change later to Files plt.show()
def plot(x, y, **kwargs): """can only do 2D plot right now""" assert (x.shape[-1] == 2) color = (y + 2) / 5 if 'accuracy' in kwargs: accuracy = kwargs['accuracy'] plt.figure() plt.scatter(x[:, 0], x[:, 1], c=color) if 'title' in kwargs: plt.suptitle(kwargs['title']) if 'accuracy' in kwargs: plt.title("Accuracy: %.1f%%" % (kwargs['accuracy'] * 100), fontsize=10) plt.show()
def plot_confusion_matrix(cm, labels, title='Confusion matrix', cmap=plt.cm.Blues, save=False): plt.figure() plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(labels)) plt.xticks(tick_marks, labels, rotation=45) plt.yticks(tick_marks, labels) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() if save: plt.savefig(save)
def plot_sinad_sfdr (label, data_x, data_y, chans=[0,1,2,3], titles=['SFDR','SINAD']): """ x x values of data (same for all chans) y array with shape (2, chans, data) """ n=len(chans) n2=len(titles) pos=np.arange(n2*n)+1 for t in range(n2): pos_val=pos[t::n2] for chan in chans: plt.subplot(n,n2,pos_val[chan]) plt.plot(data_x,data_y[t][chan],label=label) if t==0: plt.ylabel('Chan %i' %chan) if chan==0: plt.title(titles[t])
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues, filename='viz\\confusion_matrix.png'): plt.figure() plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.savefig(filename)
def display(self, data, candidates, fname, display): finallist=[] for c in candidates: finallist.append(c[0]) #print finallist part1 = finallist[:len(finallist)/2] part2 = finallist[len(finallist)/2:] meandiff=int(np.sqrt(np.power(np.mean(part2),2)-np.power(np.mean(part1),2))) rangeA = max(part1)-min(part1) rangeB = max(part2)-min(part2) span = int((rangeA+rangeB)/2) dspan = int(meandiff/span) theta = float(meandiff/(rangeA+rangeB)) oneortwo="" if dspan >3 and meandiff > 20 or meandiff>36: oneortwo = "Two distributions \n\n MD: %d \n Span: %d \n Dspan: %d \n theta: %d" % (meandiff, span, dspan, theta) else: oneortwo = "One distribution \n\n MD: %d \n Span: %d \n Dspan: %d \n theta: %d" % (meandiff, span, dspan, theta) cans = np.array(candidates) plt.plot(cans[:,0],cans[:,1],'ro') plt.axhline(max(cans[:,1])/4, color='r') plt.axhline(max(cans[:,1]/2), color='r') plt.axhline(int(max(cans[:,1]))*0.75, color='r') red_patch = mpatches.Patch(color='red', label='75%, 50% and 25% \nof maximum frequency') plt.legend(handles=[red_patch]) plt.ylabel('Frequency of occurence') plt.xlabel('separate items') plt.title('Frequency distribution estimation graph: %s' %(fname)) plt.text(max(data)*1.1, max(cans[:,1])*0.62, oneortwo, fontsize = 11, color = 'r') plt.hist(data,range(int(min(data)),int(max(data)),1)) ofile = fname[0:-3]+"png" print ("Writing outfile: %s") % (ofile) plt.savefig(ofile, bbox_inches='tight') if display == True: plt.show() return;
def execute(): plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False x = random.normal(5, .5, 1000) y = random.normal(3, 1, 1000) a = x*cos(pi/4) + y*sin(pi/4) b = -x*sin(pi/4) + y*cos(pi/4) plt.plot(a, b, '.') plt.xlabel('x') plt.ylabel('y') plt.title('原数据集') data = zeros((1000, 2)) data[:, 0] = a data[:, 1] = b x, y, evals, evecs = pca(data, 1) print(y) plt.figure() plt.plot(y[:, 0], y[:, 1], '.') plt.xlabel('x') plt.ylabel('y') plt.title('重新构造数据') plt.show()
def plotDisparityMap(network=None, disparity=0): assert network is not None, "Network is not initialised! Visualising failed." assert disparity >= 0 and disparity <= maxDisparity, "No such disparity map in the network." import matplotlib.pyplot as plt from matplotlib import animation from NetworkBuilder import sameDisparityInd print "Visualising results for disparity value {0}...".format(disparity) cellsOut = [network[x][2] for x in sameDisparityInd[disparity]] spikes = [x.getSpikes() for x in cellsOut] # print spikes sortedSpikes = sortSpikes(spikes) # print sortedSpikes framesOfSpikes = generateFrames(sortedSpikes) # print framesOfSpikes x = range(0, dimensionRetinaX) y = range(0, dimensionRetinaY) from numpy import meshgrid rows, pixels = meshgrid(x,y) fig = plt.figure() initialData = createInitialisingData() # print initialData imNet = plt.imshow(initialData, cmap='gray', interpolation='none', origin='upper') plt.xticks(range(0, dimensionRetinaX)) plt.yticks(range(0, dimensionRetinaY)) plt.title("Disparity Map {0}".format(disparity)) args = (framesOfSpikes, imNet) anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30) plt.show()
def plotdatatree(treeID, scale1, mass1): plot_title="Mass Accretion History Tree " + str(treeID) #Can code the number in with treemax x_axis="scale time" y_axis="total mass" figure_name=os.path.expanduser('~/figureTree' + str(treeID)) #Choose which type of plot you would like: Commented out. plt.plot(scale1, mass1, linestyle="-", marker="o") #plt.scatter(scale1, mass1, label="first tree") plt.title(plot_title) plt.xlabel(x_axis) plt.ylabel(y_axis) #plt.yscale("log") plt.savefig(figure_name) #In order to Plot only a single tree on a plot must clear lists before loop. #Comment out to over plot curves. plt.clf() clearmass = [] clearscale = [] return clearmass, clearscale
def plotCentroidFitDiagnostic(img, hdr, ccdMod, ccdOut, res, prfObj): """Some diagnostic plots showing the performance of fitPrfCentroid() Inputs: ------------- img (np 2d array) Image of star to be fit. Image is in the format img[row, col]. img should not contain Nans hdr (Fits header object) header associated with the TPF file the image was drawn from ccdMod, ccdOut (int) CCD module and output of image. Needed to create the correct PRF model prfObj An object of the class prf.KeplerPrf() Returns: ------------- **None** Output: ---------- A three panel subplot is created """ mp.figure(1) mp.clf() mp.subplot(131) plotTpf.plotCadence(img, hdr) mp.colorbar() mp.title("Input Image") mp.subplot(132) c,r = res.x[0], res.x[1] bbox = getBoundingBoxForImage(img, hdr) model = prfObj.getPrfForBbox(ccdMod, ccdOut, c, r, bbox) model *= res.x[2] plotTpf.plotCadence(model, hdr) mp.colorbar() mp.title("Best fit model") mp.subplot(133) diff = img-model plotTpf.plotCadence(diff, hdr) mp.colorbar() mp.title("Residuals") print "Performance %.3f" %(np.max(np.abs(diff))/np.max(img))
def plot(self, output): # Create adaptive scale scale_len = 100 scale_fix = 250 nframes = self.v.shape[2] scale = zeros((nframes, 1)) win = ones((scale_len, 1)) for ii in range(0, nframes): scale[ii] = amax(absolute(self.v[:, :, ii])) scale = convolve(squeeze(scale), squeeze(win), mode='same') / output.scale_sat if (self.writestep == 0): scale[:scale_fix] = scale[scale_fix] # Initialize figure comp = {'x': ['Y', 'Z'], 'y': ['X', 'Z'], 'z': ['X', 'Y']} fig = plt.figure(figsize=(output.hres / output.sres, output.hres / (output.sres * output.hratio)), dpi=output.sres) imsize = [self.x[0], self.x[-1], self.y[-1], self.y[0]] vimg = plt.imshow(transpose(self.v[:, :, 0]), extent=imsize, vmin=-scale[0], vmax=scale[0], cmap=cm.RdBu) vtitle = plt.title('') plt.xlabel(comp[self.dir][0]) plt.ylabel(comp[self.dir][1]) plt.colorbar() def animate(ii): vimg.set_array(transpose(self.v[:, :, ii])) vimg.set_clim(-scale[ii], scale[ii]) vtitle.set_text("%s for %s=%s km (t=%1.2e s)" % (self.type, self.dir, self.loc, self.t[ii])) return vimg, vtitle try: ani = animation.FuncAnimation(fig, animate, frames=self.v.shape[2], interval=20, blit=False, repeat=False) if (self.writestep == 0): ani.save("./%s_%s_%s.mp4" % (self.dir, self.loc, self.type), fps=30, codec='libx264', bitrate=1800) else: ani.save("./%s_%s_%s_%i.mp4" % (self.dir, self.loc, self.type, self.writestep), fps=30, codec='libx264', bitrate=1800) except IndexError: print 'To render movies, make sure that ffmpeg is installed!' self.writestep += 1
def plot(self, model, output): Z = linspace(0, model.number[2] * model.spacing[2], model.number[2]) + model.spacing[2] imsize = [model.origin[0], model.size[0] + model.origin[0], model.origin[1], model.size[1] + model.origin[1]] fig = plt.figure(figsize=(output.hres / output.sres, output.hres / (output.sres * output.hratio)), dpi=output.sres) vimg = plt.imshow(transpose(self.v[:, :, 0]), extent=imsize, vmin=round(amin(self.v), 1) - 0.05, vmax=round(amax(self.v) + 0.05, 1), cmap=cm.jet) vtitle = plt.title('') plt.xlabel('X') plt.ylabel('Y') plt.colorbar() def animate(ii): vimg.set_array(transpose(self.v[:, :, ii])) vtitle.set_text("%s Plot (Z = %1.2fkm)" % (self.name, Z[ii])) return vimg, vtitle try: ani = animation.FuncAnimation(fig, animate, frames=len(Z), interval=20, blit=False, repeat=False) ani.save("./%s.mp4" % self.type, fps=30, codec='libx264', bitrate=1800) except IndexError: print 'To render movies, make sure that ffmpeg is installed!'
For channels 2 and 3 """ adc_cal.clear_ogp() adc_cal.clear_inl() freqarray=[50,800,30] sfdr,sinad=adc_cal.do_sfdr_sinad_cw_sweep(chans=[2,3], freqarray=freqarray) sinad_values,freqs= dic2arr(sinad) sfdr_values,f = dic2arr(sfdr) """ No corrections """ plt.subplot(221) plt.plot(freqs,sinad_values[0],'-*', label='No corrections') plt.title('SINAD') plt.ylabel('Chan 2') plt.subplot(223) plt.plot(freqs,sinad_values[1],'-*', label='No corrections') plt.ylabel('Chan 3') plt.subplot(222) plt.plot(freqs,sfdr_values[0],'-*', label='No corrections') plt.title('SFDR') plt.subplot(224) plt.plot(freqs,sfdr_values[1],'-*', label='No corrections') """ OGP corrections """ adc_cal.do_ogp_cw_sweep(chans=[2,3])
pickle_file = open("pickled_data.pkl", "r") t = pickle.load(pickle_file) v = pickle.load(pickle_file) print t print v initialize(v, s, t, dt, n) calculate(v, s, t, dt, n) store(v, t, n) #plot plt.figure(1) plt.subplot(211) plt.plot(t, v,"g-", linewidth=2.0) plt.scatter(t, v) plt.title('The Velocity of a Free Falling Object') plt.xlabel('Time($t$)', fontsize=14) plt.ylabel('Velocity($m/s$)', fontsize=14) plt.text(3,-60,r'$g = 9.8 m/s^2$', fontsize=16) plt.grid(True) plt.subplot(212) plt.plot(t, s,"g-", linewidth=2.0) plt.scatter(t, s) plt.title('The Displacement of a Free Falling Object') plt.xlabel('Time($t$)', fontsize=14) plt.ylabel('Displacement($m$)', fontsize=14) plt.text(3,-300,r'$g = 9.8 m/s^2$', fontsize=16) plt.grid(True) plt.show()
m.drawcountries() pylab.title('Soil Moisture') cb = m.colorbar(pcm) cb.set_label('Soil FOO (mm)') plt.show() pylab.figure(num=None, figsize=(20,10), dpi=100) plt.title("Importance of Different Colormaps") pylab.subplot(2,2,1) plotpanel(x, y, soil) pcm = plt.pcolormesh(x, y, soil, cmap=plt.cm.nipy_spectral) cb = m.colorbar(pcm) cb.set_label('Soil FOO (mm)') pylab.title("nipy_spectral (best)") pylab.subplot(2,2,2) plotpanel(x, y, soil) pylab.title("Accent (okay)") pcm = plt.pcolormesh(x, y, soil, cmap=plt.cm.Accent) cb = m.colorbar(pcm) cb.set_label('Soil FOO (mm)')
kmin=(2*3.14)/100 kmax=(2*3.14) rhoInBin=0.0 nInBin=0 Power=np.zeros((100)) for i in range(0,99): lowBin=kmin+(i*(kmax-kmin)/50) highBin=lowBin+((kmax-kmin)/50) for l in range(0,100): for m in range(0,100): for n in range(0,100): if l!=0 and m!=0 and n!=0: modK=math.sqrt((2*3.14)**2 / ((1.0/l**2) + (1.0/m**2) + (1.0/n**2))) if modK >= lowBin and modK < highBin: rhoInBin+=(ftpert[l,m,n].conjugate() * ftpert[l,m,n]) nInBin+=1 Power[i]=rhoInBin/nInBin plt.plot(np.arange(kmin,kmax,1,100),Power,markerfacecolor='blue', marker='o', markersize=1) plt.show() plt.title('Power Spectrum') savefig('/home/vee8497/Downloads/MuSIC Cosmology/Project/set4/Power Spectrum.png',bbox_inches='tight') f.close()
print 'Intercept: ', intercept print 'r-value ', p_value print 'r-squared ', r_value**2 print 'p-value: ', p_value print 'Standard deviation: ', std_err print 'Pearson coefficient: ', stats.pearsonr(X,Y) print 'Spearman coefficient: ', stats.spearmanr(X,Y) print '' lfit = slope * np.array(X) + intercept #some plotting #note that the solid blue line (pyplot) and dashed ornage line(linregress) should be identycal plt.plot(X,Y,marker='s',color='k',ls='None',ms=7) plt.plot(X,px,ls='-',lw=2) plt.plot(X, lfit,ls='--',lw=1) plt.title('Example',fontsize=22) legend(['Random data','Polyfit regression', 'Linregress regression'],ncol=1,loc=1) ylabel('Y',fontsize=20) xlabel('X',fontsize=20) ax.minorticks_on() #adds minor thick on th eplot # you can play with the border and with multiple figures even without the graphic api #fig.subplots_adjust(hspace=0.07,wspace=0.07,left=0.12,right=0.88,top=0.92,bottom=0.09) plt.show() # can save the figure in the format you want and other little perks #fig.savefig('test.pdf',bbox_inches='tight',format='pdf',dpi=1000)
Z = dpca.fit_transform(R,trialR) # In[6]: time = arange(T) plt.figure(figsize=(16,7)) plt.subplot(131) for s in range(S): plt.plot(time,Z['t'][0,s]) plt.title('1st time component') subplot(132) for s in range(S): plot(time,Z['s'][0,s]) title('1st stimulus component') subplot(133) for s in range(S): plot(time,Z['st'][0,s]) title('1st mixing component') show()
diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] regr = linear_model.LinearRegression() regr.fit(diabetes_X_train, diabetes_y_train) # >> LinearRegression(copy_X=True, fit_intercept=True, normalize=False) print regr.coef_ # The mean square error np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2) # Explained variance score: 1 is perfect prediction # and 0 means that there is no linear relationship # between X and Y. regr.score(diabetes_X_test, diabetes_y_test) # Plot results pl.clf() # Clear plots pl.plot(diabetes_X_test, regr.fit(diabetes_X_train, diabetes_y_train)); pl.title('Linear regression of sample diabetes data\n' 'Centroids are marked with white cross') pl.xlim(x_min, x_max) pl.ylim(y_min, y_max) pl.xticks(()) pl.yticks(()) pl.show()
kinf_list = [] filename = assembly + "-numazim-errors.h5" if os.path.isfile("results/" + filename): f = h5py.File("results/" + filename, "r") else: f = h5py.File("results/" + assembly + "-errors.h5", "r") for j, x in enumerate(x_axis): value_keys = f[test][sorted_keys[j]].keys() for key in value_keys: if "Kinf_Error" in key: kinf_list.append(f[test][sorted_keys[j]][key][...] * 10 ** 5) plt.plot(x_axis, kinf_list, colors[i] + "o-", ms=10, lw=2) f.close() plt.axis([0, 130, 0, 500]) plt.title("Error in K-Infinity") plt.xlabel("Number of Azimuthal Angles") plt.ylabel("K-Infinity Error [pcm]") plt.grid() plt.legend(legend) plt.show() fig.savefig("K-Infinity-Error-Azim.png") fig = plt.figure() for i, assembly in enumerate(assembly_list): mean_list = [] filename = assembly + "-numazim-errors.h5" if os.path.isfile("results/" + filename): f = h5py.File("results/" + filename, "r") else: f = h5py.File("results/" + assembly + "-errors.h5", "r")
for array in fsr_kinf_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k", linewidths=1, vmin=nparray[:, :].min(), vmax=nparray[:, :].max(), ) plt.colorbar() plt.axis([0, 5, 0, 5]) plt.title("FSR K-infinity Errors") plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) plt.show() fig.savefig(assembly_list[fsr_kinf_error.index(array)] + "-fsr-kinf-errors.jpeg") for array in fsr_mean_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k", linewidths=1, vmin=nparray[:, :].min(),
# -*- coding: utf-8 -*- """ Created on Mon Jan 23 11:07:06 2017 @author: Paige """ import matplotlib as plt import numpy as np x = np.linspace(-10, 10, 400) cos = np.cos(x) sin = np.sin(x) plt.plot(x, cos, "r", label="cos(x)") # r for red line plt.plot(x, sin, "b--", label="sin(x)") # b-- for blue dashed line # colors include red(r), green(g), yellow(y), blue(b), cyan(c), # magenta(m), black(k), white(w) # line styles include solid line("-"), dashed line("--"), # solid line("-"), square("s"), dots("o"), smaller dots(".") plt.xlim(-10, 10) plt.legend() plt.xlabel("x") plt.title("Trigonometric Functions") plt.ylabel("cos(x) or sin(x)") # plt.savefig("1-23-2017.png") plt.show()
import matplotlib as plt # X-axis sorted for making the graph clean from crazy lines all over and just a single line print(plt.style.available) plt.style.use("dark_background") forest_fires = forest_fires.sort(["rain"]) plt.plot(forest_fires["rain"], forest_fires["area"]) # Set the x axis label plt.xlabel("Amount of Rain") # Set the y axis label plt.ylabel("Area") # Set the title plt.title("Rain quantity vs fire area") plt.show()
kinf_list = [] filename = assembly + '-trackspacing-errors.h5' if os.path.isfile('results/' + filename): f = h5py.File('results/' + filename, 'r') else: f = h5py.File('results/' + assembly + '-errors.h5', 'r') for j, x in enumerate(x_axis): value_keys = f[test][sorted_keys[j]].keys() for key in value_keys: if 'Kinf_Error' in key: kinf_list.append(f[test][sorted_keys[j]][key][...]*10**5) plt.plot(x_axis,kinf_list, colors[i] + 'o-', ms = 10, lw = 2) f.close() plt.axis([max(x_axis), 0, 0, 400]) plt.title('Error in K-Infinity') plt.xlabel('Track Spacing [cm]') plt.ylabel('K-Infinity Error [pcm]') plt.grid() plt.legend(legend) plt.show() fig.savefig('K-Infinity-Error-TS.png') fig = plt.figure() for i, assembly in enumerate(assembly_list): mean_list = [] filename = assembly + '-trackspacing-errors.h5' if os.path.isfile('results/' + filename): f = h5py.File('results/' + filename, 'r') else: f = h5py.File('results/' + assembly + '-errors.h5', 'r')
eye_sample, eye_line = row[1:3] nose_sample, nose_line = row[3:5] print eye_sample, eye_line, nose_sample, nose_line print "opening",bg_file[0] cube = gdal.Open(bg_file[0], GA_ReadOnly ) xOff = int(eye_sample) - size/2 -1 yOff = int(eye_line) - size/2 -1 array = cube.ReadAsArray(xOff, yOff, size, size) array = array / math.cos(incAnglerad) means.append(array.mean()) if i == 1 and vmin == None: vmin = array.min() vmax = array.max() print vmin,vmax generate_plot(array, vmin, vmax) xOff = int(nose_sample) - size/2 -1 yOff = int(nose_line) - size/2 -1 array = cube.ReadAsArray(xOff, yOff, size, size) array = array/math.cos(incAnglerad) means2.append(array.mean()) generate_plot(array, vmin,vmax, 3) plt.figure(2) plt.plot(times,means,'bo') plt.xlabel('L_s [deg]') plt.ylabel('Reflectance / cos(i) for {0}x{0} pixels'.format(size)) plt.title('mean(BG) vs L_s, eye-crater') plt.plot(times,means2,'ro') plt.show()