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 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()
model.add(Flatten()) 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()
# Plot each component overlayed on each other. import numpy as np import matplotlib.pyplot.plt def square_copmonent(x, omega, k): """returns kth term frm square_wave aprxmtn""" return (4.0/np.pi) * np.sin(2*np.pi * (2*k-1) * omega*x) / (2*k-1) x = np.linspace(0, 1, 500) y = np.zeros((5, len(x)) for k in range(5): y[k,:] = square_component(x, 2, k+1) plt.plot(x, y[k,:], label = 'k=' + str(k+1)) plt.legend() plt.show() # Staff Soln: # import numpy as np # import matplotlib.pyplot as plt # def square_component(x,omega,k): # val = (4.0/np.pi)* np.sin(2*np.pi*(2*k-1)*omega*x)/(2*k-1) # return val # # omega=2 # x = np.linspace(0,1,500) # ks = [1,2,3,4,5] # y = np.zeros((5,len(x))) # # for indx,k in enumerate(ks):
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
batch_size=batch_size, epochs=epochs, #verbose=1, callbacks=[cb], validation_split=.1, #validation_data=(X_test, y_test) ) score = model.evaluate(X_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) predicted = model.predict(X_test, verbose=False) predicted = np.argmax(predicted, axis=1) from keras.utils import plot_model plot_model(model, to_file='CNN.png') #CM = ConfusionMatrix(predicted, y_test_orig, c); #np.savetxt("data/CNN_predicted_raw.txt", predicted, "%d") #np.savetxt("data/CNN_cm_raw.txt", CM, "%d"); from matplotlib.pyplot import plt plt.plot(history.history['val_acc']) plt.plot(history.history['acc']) plt.legend(['Validation Accuracy', 'Training Accuracy']) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.title('CNN Convergence Curve') plt.show()