def test(): filename = "iris.csv" data = read_csv(filename, skiprows=[1]) data.plot(kind="density", y="petallength") plt.show() #To save the plot figure plt.savefig('fig_data_plot.png')
def test_changepoint_scaled(): p = 150 M = multiscale(p) M.minsize = 10 X = ra.adjoint(M) Y = np.random.standard_normal(p) Y[20:50] += 8 Y += 2 meanY = Y.mean() lammax = np.fabs(np.sqrt(M.sizes) * X.adjoint_map(Y) / (1 + np.sqrt(np.log(M.sizes)))).max() penalty = rr.weighted_l1norm((1 + np.sqrt(np.log(M.sizes))) / np.sqrt(M.sizes), lagrange=0.5*lammax) loss = rr.squared_error(X, Y - meanY) problem = rr.simple_problem(loss, penalty) soln = problem.solve() Yhat = X.linear_map(soln) Yhat += meanY if INTERACTIVE: plt.scatter(np.arange(p), Y) plt.plot(np.arange(p), Yhat) plt.show()
def trumpet_plot(self, scan_rates, trumpets, **kwargs): if "ax" not in kwargs: ax = None else: ax = kwargs["ax"] if "label" not in kwargs: label = None else: label = kwargs["label"] if "description" not in kwargs: kwargs["description"] = False else: label = None if "log" not in kwargs: kwargs["log"] = np.log10 if len(trumpets.shape) != 2: raise ValueError( "For plotting reductive and oxidative sweeps together") else: colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] if ax == None: plt.scatter(kwargs["log"](scan_rates), trumpets[:, 0], label="Forward sim", color=colors[0]) plt.scatter(kwargs["log"](scan_rates), trumpets[:, 1], label="Reverse sim", color=colors[0], facecolors='none') plt.legend() plt.show() else: if kwargs["description"] == False: if ax.collections: pass else: self.color_counter = 0 ax.scatter(kwargs["log"](scan_rates), trumpets[:, 0], label=label, color=colors[self.color_counter]) ax.scatter(kwargs["log"](scan_rates), trumpets[:, 1], color=colors[self.color_counter], facecolors='none') self.color_counter += 1 else: ax.scatter(kwargs["log"](scan_rates), trumpets[:, 0], label="$E_{p(ox)}-E^0$", color=colors[0]) ax.scatter(kwargs["log"](scan_rates), trumpets[:, 1], label="$E_{p(red)}-E^0$", color=colors[0], facecolors='none')
def load_csv(filename): dataset=list() with open(filename,'r') as file: csv_reader=reader(file) for row in csv_reader: if not row: continue dataset.append(row) plt.dataset() plt.show() return dataset
def plot_slice(self, neuron_type, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None): cell_id = self.neuron_type_lookup[neuron_type] ok_idx = np.zeros((len(cell_id), ), dtype=int) ok_idx[cell_id] = 1 if x_min is not None: ok_idx = np.logical_and(ok_idx, x_min < self.neuron_positions[:, 0]) if x_max is not None: ok_idx = np.logical_and(ok_idx, self.neuron_positions[:, 0] < x_max) if y_min is not None: ok_idx = np.logical_and(ok_idx, y_min < self.neuron_positions[:, 1]) if y_max is not None: ok_idx = np.logical_and(ok_idx, self.neuron_positions[:, 1] < y_max) if z_min is not None: ok_idx = np.logical_and(ok_idx, z_min < self.neuron_positions[:, 2]) if z_max is not None: ok_idx = np.logical_and(ok_idx, self.neuron_positions[:, 2] < z_max) cell_pos = self.neuron_positions[ok_idx, :] fig = plt.figure() ax = fig.add_subplot(projection='3d') plt.scatter(x=cell_pos[:, 0], y=cell_pos[:, 1], z=cell_pos[:, 2]) plt.show()
def plot_embeddings(embeddings,): X, Y = read_node_label('../data/wiki_labels.txt') emb_list = [] for k in X: emb_list.append(embeddings[k]) emb_list = np.array(emb_list) model = TSNE(n_components=2) node_pos = model.fit_transform(emb_list) color_idx = {} for i in range(len(X)): color_idx.setdefault(Y[i][0], []) color_idx[Y[i][0]].append(i) for c, idx in color_idx.items(): plt.scatter(node_pos[idx, 0], node_pos[idx, 1], label=c) plt.legend() plt.show()
def simulate(self, parameters, frequency_range): maxes=np.zeros(len(frequency_range)) for j in range(0, len(frequency_range)): self.dim_dict["omega"]=frequency_range[j] self.nd_param=params(self.dim_dict) #self.calculate_times() #start=time.time() #volts=self.define_voltages() #start=time.time() current=super().simulate(parameters, []) f, b, net, potential=super().SW_peak_extractor(current) if self.simulation_options["synthetic_noise"]!=0: current=self.add_noise(net, self.simulation_options["synthetic_noise"]*max(net)) #current=self.rolling_window(current, 8) else: current=net #plt.plot(potential, current) #current=self.rolling_window(current, 8) if self.simulation_options["record_exps"]==True: self.saved_sims["current"].append(current) self.saved_sims["voltage"].append(volts) first_half=tuple(np.where(potential<self.dim_dict["E_0"])) second_half=tuple(np.where(potential>self.dim_dict["E_0"])) data=[first_half, second_half] peak_pos=[0 ,0] for i in range(0, 2): maximum=max(current[data[i]]) max_idx=potential[data[i]][np.where(current[data[i]]==maximum)] peak_pos[i]=max_idx maxes[j]=(peak_pos[1]-peak_pos[0])*1000 if self.simulation_options["SWVtest"]==True: plt.scatter(1/frequency_range, maxes) plt.scatter(1/frequency_range, self.test) plt.show() #print(time.time()-start) return maxes
def simulate(self, parameters, scan_rates): forward_sweep_pos = np.zeros(len(scan_rates)) reverse_sweep_pos = np.zeros(len(scan_rates)) for i in range(0, len(scan_rates)): self.dim_dict["v"] = scan_rates[i] self.nd_param = params(self.dim_dict) self.calculate_times() volts = self.define_voltages() current = super().simulate(parameters, []) if self.simulation_options["synthetic_noise"] != 0: current = self.add_noise( current, self.simulation_options["synthetic_noise"] * max(current)) #current=self.rolling_window(current, 8) if self.simulation_options["record_exps"] == True: self.saved_sims["current"].append(current) self.saved_sims["voltage"].append(volts) forward_sweep_pos[i], reverse_sweep_pos[ i] = self.trumpet_positions(current, volts) if "dcv_sep" in self.optim_list: forward_sweep_pos += self.nd_param.nd_param_dict["dcv_sep"] reverse_sweep_pos -= self.nd_param.nd_param_dict["dcv_sep"] if self.simulation_options["trumpet_method"] == "both": if self.simulation_options["trumpet_test"] == True: print(parameters) log10_scans = np.log10(scan_rates) fig, ax = plt.sublots(1, 1) ax.scatter(log10_scans, forward_sweep_pos) ax.scatter(log10_scans, reverse_sweep_pos) ax.scatter(log10_scans, self.secret_data_trumpet[:, 0]) ax.scatter(log10_scans, self.secret_data_trumpet[:, 1]) plt.show() return np.column_stack((forward_sweep_pos, reverse_sweep_pos)) elif self.simulation_options["trumpet_method"] == "forward": return forward_sweep_pos else: return reverse_sweep_pos
def show_detected_objects(img_path, model, labels_to_names): # img_path = '/content/drive/My Drive/person_detection/WiderPerson/bus_showcase.jpg' image = read_image_bgr(img_path) boxes, scores, labels = predict(image, model) for i, score in enumerate(scores[0]): if score > THRES_SCORE: print('row ', img_path, 'score ', scores[0, i]) if all(i < THRES_SCORE for i in scores[0]): print('no detections') return draw = image.copy() draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB) draw_detections(draw, boxes, scores, labels, labels_to_names) plt.axis('off') plt.imshow(draw) plt.show()
def simulate(self, parameters, frequency_range): start=time.time() maxes=np.zeros(len(frequency_range)) if self.simulation_options["amplitudes_set"]!=True: raise ValueError("Need to define SW ampltidues") for j in range(0, len(frequency_range)): self.dim_dict["omega"]=frequency_range[j] delta_p=np.zeros(len(self.Esw_range)) for q in range(0, len(self.Esw_range)): self.dim_dict["SW_amplitude"]=self.Esw_range[q] self.nd_param=params(self.dim_dict) #self.calculate_times() #start=time.time() #volts=self.define_voltages() current=super().simulate(parameters, []) f, b, net, potential=super().SW_peak_extractor(current) if self.simulation_options["synthetic_noise"]!=0: current=self.add_noise(net, self.simulation_options["synthetic_noise"]*max(net)) #current=self.rolling_window(current, 8) else: current=net #plt.plot(potential, current) #current=self.rolling_window(current, 8) if self.simulation_options["record_exps"]==True: self.saved_sims["current"].append(current) self.saved_sims["voltage"].append(volts) delta_p[q]=(max(current))/self.Esw_range[q] #plt.show() maxes[j]=(self.Esw_range[np.where(delta_p==max(delta_p))]) if self.simulation_options["SWVtest"]==True: plt.scatter(1/frequency_range, maxes) plt.scatter(1/frequency_range, self.test) plt.show() return maxes
model.add(Dense(100)) model.add(Dropout(0.5)) model.add(Dense(50)) model.add(Dropout(0.5)) model.add(Dense(10)) #model.add(Dropout(0.5)) model.add(Dense(1)) model.compile(loss='mse', optimizer='adam') history_object = model.fit(X_train, y_train, batch_size=32, nb_epoch=8, shuffle=True, verbose=1, validation_split=0.1) model.save('model.h5') from matplotlib.pyplot import plt print(history_object.history.keys()) plt.plot(history_object.history['loss']) plt.plot(history_object.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'], loc='upper right') plt.show()
# Extract x and y coordinates x = r[:,0] y = r[:,1] # Import functionality for plotting from matplotlib.pyplot import plt # Plot figure plt.plot(x,y) # Prettify the plot plt.xlabel('Horizontal distance, [m]') plt.ylabel('Vertical distance, [m]') plt.title('Trajectory of a fired cannonball') plt.grid() plt.axis([0, 900, 0, 250]) # Makes the plot appear on the screen plt.show()
def k0_interpoltation(self, scans, trumpet, **units): scan_rates = np.log(scans) anodic_sweep = trumpet[:, 0] cathodic_sweep = trumpet[:, 1] data = [anodic_sweep, cathodic_sweep] if "T" not in units: units["T"] = 278 if "n" not in units: units["n"] = 1 if "E_0" not in units: units["E_0"] = (anodic_sweep[-1] - cathodic_sweep[-1]) / 2 print(units["E_0"]) if "deviation" not in units: deviation = 100 else: deviation = units["deviation"] if "plot" not in units: units["plot"] = False else: if "ax" not in units: units["ax"] = None fig, ax = plt.subplots(1, 1) else: ax = units["ax"] units["F"] = 96485.3329 units["R"] = 8.31446261815324 nF = units["n"] * units["F"] RT = units["R"] * units["T"] difference = self.square_error(anodic_sweep, cathodic_sweep) mean_low_scans = np.mean(difference[:5]) low_scan_deviation = np.divide(difference, mean_low_scans) start_scan = tuple(np.where(low_scan_deviation > deviation)) inferred_k0 = [0 for x in range(0, len(data))] for i in range(0, len(data)): fitting_scan_rates = scan_rates[start_scan] fitting_data = np.subtract(data[i][start_scan], units["E_0"]) popt, _ = curve_fit(self.poly_1, fitting_scan_rates, fitting_data) m = popt[0] c = popt[1] #print(m,c) if i == 0: alpha = 1 - ((RT) / (m * nF)) exp = np.exp(c * nF * (1 - alpha) / (RT)) inferred_k0[i] = (nF * (1 - alpha)) / (RT * exp) else: alpha = -((RT) / (m * nF)) exp = np.exp(c * nF * (-alpha) / (RT)) inferred_k0[i] = (nF * (alpha)) / (RT * exp) fitted_curve = [self.poly_1(t, *popt) for t in fitting_scan_rates] if units["plot"] == True: if i == 0: ax.plot(fitting_scan_rates, fitted_curve, color="red", label="Linear region") else: ax.plot(fitting_scan_rates, fitted_curve, color="red") if units["plot"] == True: self.trumpet_plot(scans, np.column_stack((data[0] - units["E_0"], data[1] - units["E_0"])), ax=ax, log=np.log, description=True) plt.legend() fig = plt.gcf() fig.set_size_inches(7, 4.5) plt.show() fig.savefig("DCV_trumpet_demonstration.png", dpi=500) return inferred_k0