我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用matplotlib.pyplot.semilogx()。
def _plot_cmc(cmcs, colors, labels, title, fontsize=10, position=None): if position is None: position = 'lower right' # open new page for current plot figure = pyplot.figure() max_R = 0 # plot the CMC curves for i in range(len(cmcs)): probs = bob.measure.cmc(cmcs[i]) R = len(probs) pyplot.semilogx(range(1, R+1), probs, figure=figure, color=colors[i], label=labels[i]) max_R = max(R, max_R) # change axes accordingly ticks = [int(t) for t in pyplot.xticks()[0]] pyplot.xlabel('Rank') pyplot.ylabel('Probability') pyplot.xticks(ticks, [str(t) for t in ticks]) pyplot.axis([0, max_R, -0.01, 1.01]) pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def plot_series(series): plt.figure(1) # colors = [np.array([1, 0.1, 0.1]), np.array([0.1, 1, 0.1]), np.array([0.1, 0.1, 1])] colors = ['m', 'g', 'r', 'b', 'y'] for i, s in enumerate(series): print(s['x'], s['y'], s['std'], s['label']) small_number = np.ones_like(s['x']) * (s['x'][1]*0.1) x_axis = np.where(s['x'] == 0, small_number, s['x']) plt.plot(x_axis, s['y'], color=colors[i], label=s['label']) plt.fill_between(x_axis, s['y'] - s['std'], s['y'] + s['std'], color=colors[i], alpha=0.2) plt.semilogx() plt.xlabel('MI reward bonus') plt.ylabel('Final intrinsic reward') plt.title('Final intrinsic reward in pointMDP with 10 good modes') plt.legend(loc='best') plt.show()
def quiz15(): X, Y, N = read_file("features.train") Y_0 = (Y == 0).astype(int) c_l = [] w_l = [] for i in range(-6, 4, 2): c = 10 ** i c_l.append(c) clf = svm.SVC(C=c, kernel='linear', shrinking=False) clf.fit(X, Y_0) w = clf.coef_.flatten() norm_w = np.linalg.norm(w, ord=2) w_l.append(norm_w) print("C = ", c, ' norm(w) =', norm_w) plt.semilogx(c_l, w_l) plt.savefig("h5_q15.png", dpi=300)
def plot_evolution(params, color=None, label=None): data = get_results(NAME, params, calc=do_calculations) times = data.times success = data.success N = float(len(success)) t = sorted(times[success]) p = np.arange(sum(success))/N t.append(endtime) p = np.append(p, [p[-1]]) errp = 1.96*np.sqrt(p*(1.-p)/N) # 95% confidence plt.semilogx(t, p, color=color, label=label) plt.fill_between(t, p - errp, p + errp, alpha=0.2, facecolor=color, linewidth=0) plt.xlabel("Time [ns]") plt.ylabel("Exit probability") plt.xlim(xmin=0.1, xmax=5e6) print "last time: %.5f ms\nend prob: %.3f\nstd. dev.: %.3f" % ( t[-2]*1e-6, p[-2], errp[-2])
def test_S_curve(): T0 = 500.0; X0 = 'CH4:1, O2:2, N2:7.52'; atm = 1 soln_in = ct.Solution('gri30.xml') soln_out = ct.Solution('gri30.xml') raw = S_curve(soln_in, soln_out, atm, T0, X0, path_raw='psr.npz') tt = raw['axis0'] TT = raw['temperature'] #print raw[0].T #print raw[-1].T plt.semilogx(tt, TT, marker='o') plt.savefig('S_curve.jpg')
def plot(x: typing.List[float], y: typing.List[float], out_dir: str): ''' plot x vs y and save in out_dir Arguments --------- x: typing.List[float] time stamps y:typing.List[float] predicted performance values out_dir: str output directory to save plot ''' plt.plot(x, y) plt.semilogx() plt.ylabel("Average Cost") plt.xlabel("Configuration Time") plt.title("Predicted Performance of Incumbents over Time") out_fn = os.path.join(out_dir, "pred_perf_over_time.png") logger.info("Plot average performance and save at %s" % (out_fn)) plt.savefig(out_fn)
def show_gs_alpha( grid_scores): alphas = np.array([ x[0]['alpha'] for x in grid_scores]) r2_mean = np.array([ x[1] for x in grid_scores]) r2_std = np.array([ np.std(x[2]) for x in grid_scores]) r2_mean_pos = r2_mean + r2_std r2_mean_neg = r2_mean - r2_std plt.semilogx( alphas, r2_mean, 'x-', label = 'E[$r^2$]') plt.semilogx( alphas, r2_mean_pos, ':k', label = 'E[$r^2$]+$\sigma$') plt.semilogx( alphas, r2_mean_neg, ':k', label = 'E[$r^2$]-$\sigma$') plt.grid() plt.legend( loc = 2) plt.show() best_idx = np.argmax( r2_mean) best_r2_mean = r2_mean[ best_idx] best_r2_std = r2_std[ best_idx] best_alpha = alphas[ best_idx] print("Best: r2(alpha = {0}) -> mean:{1}, std:{2}".format( best_alpha, best_r2_mean, best_r2_std))
def _plot_roc(frrs, colors, labels, title, fontsize=10, position=None, farfrrs=None): if position is None: position = 'lower right' figure = pyplot.figure() # plot FAR and CAR for each algorithm for i in range(len(frrs)): pyplot.semilogx([f for f in frrs[i][0]], [1. - f for f in frrs[i][1]], color=colors[i], label=labels[i]) if isinstance(farfrrs, list): pyplot.plot(farfrrs[i][0], (1.-farfrrs[i][1]), 'o', color=colors[i], markeredgecolor=colors[i]) # plot vertical bar, if desired if farfrrs is not None: if isinstance(farfrrs, float): pyplot.plot([farfrrs,farfrrs],[0.,1.], "--", color='black') else: pyplot.plot([x[0] for x in farfrrs], [(1.-x[1]) for x in farfrrs], '--', color='black') _add_far_labels(frrs[0][0][0]) # set label, legend and title pyplot.xlabel('FMR') pyplot.ylabel('1 - FNMR') pyplot.grid(True, color=(0.6,0.6,0.6)) pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def _plot_dir(cmc_scores, far_values, rank, colors, labels, title, fontsize=10, position=None): if position is None: position = 'lower right' # open new page for current plot figure = pyplot.figure() # for each probe, for which no positives exists, get the highest negative # score; and sort them to compute the FAR thresholds for i, cmcs in enumerate(cmc_scores): negatives = sorted(max(neg) for neg, pos in cmcs if (pos is None or not numpy.array(pos).size) and neg is not None) if not negatives: raise ValueError("There need to be at least one pair with only negative scores") # compute thresholds based on FAR values thresholds = [bob.measure.far_threshold(negatives, [], v, True) for v in far_values] # compute detection and identification rate based on the thresholds for # the given rank rates = [bob.measure.detection_identification_rate(cmcs, t, rank) for t in thresholds] # plot DIR curve pyplot.semilogx(far_values, rates, figure=figure, color=colors[i], label=labels[i]) # finalize plot _add_far_labels(far_values[0]) pyplot.xlabel('FAR') pyplot.ylabel('DIR') pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def plot_mean_fit(sol, ax): data = sol[0]["data"] Zr0 = max(abs(data["Z"])) f = data["freq"] list_best_fit = [s["fit"]["best"] for s in sol] mean_fit = old_div(np.mean(list_best_fit, axis=0),Zr0) # Real-Imag plt.axes(ax[1]) plt.semilogx(f, -mean_fit.imag, '-r', linewidth=2, label='Mean fit', zorder=1) plt.legend(loc=2, fontsize=12) plt.axes(ax[0]) plt.semilogx(f, mean_fit.real, '-r',linewidth=2, label='Mean fit', zorder=1) plt.legend(loc=3, fontsize=12)
def validation_crv(estimator, X, y, title, n_jobs=1): param_range = np.logspace(-6, -1, 5) train_scores, test_scores = validation_curve( estimator, X, y, param_name="max_features", param_range=param_range, cv=10, scoring="accuracy", n_jobs=n_jobs) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.title(title) plt.xlabel("$\gamma$") plt.ylabel("Score") plt.ylim(0.0, 1.1) lw = 2 plt.semilogx(param_range, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_range, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.semilogx(param_range, test_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_range, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") return plt
def drawValidationCurve(self): """ To draw the validation curve :return:NA """ X, y = self.X_train, self.y_train.ravel() indices = np.arange(y.shape[0]) np.random.shuffle(indices) X, y = X[indices], y[indices] train_sizes = np.logspace(-5,5) train_scores, valid_scores = validation_curve(self.clf, X, y, "C", train_sizes, cv=5) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.1, color="g") plt.semilogx(train_sizes, train_scores_mean, 'o-', color="r", label="Training Precision") plt.semilogx(train_sizes, valid_scores_mean, '*-', color="g", label="Cross-validation Precision") plt.legend(loc="best") plt.xlabel('Tradeoff C') plt.ylabel('Precision') plt.title('Validation Curve with Logistic Regression on the parameter of C') plt.grid(True) plt.show()
def plot_accuracy_by_freq(freqs, accuracies, filename=None, title=''): plt.semilogx(freqs, accuracies, marker='.') plt.xlabel('Frequency') plt.ylabel('Accuracy') plt.title(title) if filename: print 'saving plot to:', filename plt.savefig(filename)
def plot(self): """Draw performance profile.""" import matplotlib.pyplot as plt nsolvs, nprobs = self.ratios.shape y = np.arange(nprobs, dtype=np.float) / nprobs grays = ['0.0', '0.5', '0.8', '0.2', '0.6', '0.9', '0.4', '0.95'] ngrays = len(grays) xmax = 1.1 * self.max_ratio if self.options['logscale']: xmax = max(xmax, 2) pltcmd = plt.semilogx if self.options['logscale'] else plt.plot for solv in range(nsolvs): pltargs = () if self.options['bw']: pltargs = (grays[solv % ngrays],) # Draw profile tail all the way. self.ratios[solv, -1] = xmax line, = pltcmd(self.ratios[solv, :], y, linewidth=2, drawstyle='steps-pre', antialiased=True, alpha=0.75, *pltargs) line.set_label(self.solvers[solv]) plt.legend(loc='lower right') ax = plt.gca() if self.options['logscale']: ax.set_xscale('log', basex=2) xmax = max(xmax, 2) ax.set_xlim([1, xmax]) ax.set_ylim([0, 1.1]) ax.set_xlabel('Within this factor of the best') ax.set_ylabel('Proportion of problems') if self.options['title'] is not None: ax.set_title(self.options['title']) plt.show()
def plot_fft(self, plotname=None, window='hann', normalise=True, **kwargs): """Make a plot (in the frequency domain) of all channels""" ymin = kwargs.get('ymin', -160) #dB freq, mag = self.fft(window=window, normalise=normalise) fig_id = 1 plt.figure(fig_id) #plt.semilogx(freq, mag, **kwargs) # plots all channel directly plt.hold(True) for ch in range(self.ch): plt.semilogx(freq, mag[:,ch], label='ch%2i' %(ch+1)) plt.hold(False) plt.xlim(xmin=1) # we're not interested in freqs. below 1 Hz plt.ylim(ymin=ymin) plt.xlabel('Frequency [Hz]') plt.ylabel('Magnitude [dB]') plt.legend(loc='best') plt.grid(True) if plotname is None: plt.show() else: plt.savefig(plotname) plt.close(fig_id)
def test_qtable(): single_run = True n_episode = 1000000 tMax = 200 env = gym.make('FrozenLake-v0') S = env.observation_space A = env.action_space learning_rate=1e-2 gamma=0.99 policy=epsilon_greedy if single_run: agent = QTable(S, A, learning_rate=learning_rate, gamma=gamma, policy=policy) ave_r = run(env, agent, n_episode, tMax, plot=True, epsilon=0.1) plt.matshow(flQ_table(agent.table)) plt.savefig('qtable_data/policy.png', format='png') else: # Sample learning rates # lrs = 10**np.random.uniform(-4.0, -2, size=10) learning_rates = [lrs[n] for n in xrange(lrs.shape[0]) ] ave_returns = [] for lr in learning_rates: agent = QTable(S, A, learning_rate=lr, gamma=gamma, policy=policy) ave_r = run(env, agent, n_episode, tMax, plot=True) print agent.table ave_returns.append(ave_r) plt.figure() plt.semilogx(learning_rates, ave_returns, 'o') plt.savefig('lr_returns.png'.format(), format='png') plt.xlabel('learning rate') plt.ylabel('average returns')
def test(): n_episode = 100000 tMax = 200 gamma = 0.9 epsilon = 0.1 learning_rate = 1e-2 env = gym.make('CartPole-v0') S = env.observation_space A = env.action_space agent = SimpleAgent(S, A, gamma=gamma, epsilon=epsilon, learning_rate=learning_rate) #agent.model = load_model('model.h5') ave_r = run(env, agent, n_episode, tMax, plot=True) agent.model.save('model.h5') exit() # Sample learning rates # lrs = 10**np.random.uniform(-2.0, -1.0, size=10) learning_rates = [lrs[n] for n in xrange(lrs.shape[0]) ] ave_returns = [] for lr in learning_rates: agent = SimpleAgent(S, A, gamma=gamma, epsilon=epsilon, learning_rate=lr) ave_r = run(env, agent, n_episode, tMax, plot=True) ave_returns.append(ave_r) plt.figure() plt.semilogx(learning_rates, ave_returns, 'o') plt.savefig('ave_returns.png'.format(), format='png')
def hypers_demo(): steps, mc = 500, 20 ssm = UNGM() # initialize UNGM model x, z = ssm.simulate(steps, mc_sims=mc) # generate some data lscale = [1e-3, 3e-3, 1e-2, 3e-2, 1e-1, 3e-1, 1, 3, 1e1, 3e1] # , 1e2, 3e2] sigmas_ut = Unscented.unit_sigma_points(ssm.xD, kappa=0.0) mean_f, cov_f = np.zeros((ssm.xD, steps, mc, len(lscale))), np.zeros((ssm.xD, ssm.xD, steps, mc, len(lscale))) for iel, el in enumerate(lscale): # initialize BHKF with current lenghtscale f = GPQuadKalman(ssm, usp_dyn=sigmas_ut, usp_meas=sigmas_ut, hyp_dyn={'sig_var': 1.0, 'lengthscale': el * np.ones(ssm.xD, ), 'noise_var': 1e-8}, hyp_meas={'sig_var': 1.0, 'lengthscale': el * np.ones(ssm.xD, ), 'noise_var': 1e-8}) # filtering for s in range(mc): mean_f[..., s, iel], cov_f[..., s, iel] = f.forward_pass(z[..., s]) # compute average (over MC sims) RMSE and NCI rmseVsEl = rmse(x, mean_f).mean(axis=1) nciVsEl = nci(x, mean_f, cov_f).mean(axis=1) # plot influence of changing lengthscale on the RMSE and NCI filter performance plt.figure() plt.semilogx(lscale, rmseVsEl.squeeze(), color='k', ls='-', lw=2, marker='o', label='RMSE') plt.semilogx(lscale, nciVsEl.squeeze(), color='k', ls='--', lw=2, marker='o', label='NCI') plt.grid(True) plt.legend() plt.show() return lscale, rmseVsEl, nciVsEl
def plotLL(network,meta,line="LLs",log=False,DC=False,lc='b',qs=None): nl="neoLL" if DC: line="DC_"+line nl="DC_" + nl with open("out/%s_%s_%s.txt" %(network,str(meta),line)) as f: results=np.float64([row.strip().split() for row in f.readlines()]) with open("out/%s_%s_%s.txt" %(network,str(meta),nl)) as f: LLs=np.float64([row.strip().split() for row in f.readlines()]) thetamin=results[0,0] thetas=np.append(0,10**np.arange(thetamin,0-thetamin/50.,-thetamin/50.)) idx=np.argmax(LLs,0)[2:] y=results[idx,np.arange(len(thetas))+2] #~ print zip(thetas,y) if log: plt.semilogx(thetas,y,lc) #~ try: #~ print y[0],qs[-1] #~ N=qs[-1] #~ ftheta=y[0]-qs*np.log(thetas/(1-thetas)) - N*np.log(1-thetas) #~ plt.semilogx(thetas, ftheta,'r:') #~ for q in np.arange(0.,N,50.): #~ print q #~ ftheta=y[0]-q*np.log(thetas/(1-thetas)) - N*np.log(1-thetas) #~ plt.semilogx(thetas, ftheta,'k:') #~ except TypeError: #~ pass else: plt.plot(thetas,y,lc) plt.xlim(0,1) #~ print results[0,1] return y ##################################################
def plot_fit(s, ax): filepath = s["path"] sample_name = filepath.replace("\\", "/").split("/")[-1].split(".")[0] data = s["data"] fit = s["fit"] # Graphiques du fit f = data["freq"] Zr0 = max(abs(data["Z"])) zn_dat = old_div(data["Z"],Zr0) zn_err = old_div(data["Z_err"],Zr0) zn_fit = old_div(fit["best"],Zr0) zn_min = old_div(fit["lo95"],Zr0) zn_max = old_div(fit["up95"],Zr0) # for t in ax: # t.tick_params(labelsize=14) # Real-Imag plt.axes(ax[1]) plt.semilogx(f, -zn_fit.imag, '-', color='lightgray', zorder=0, label="Fitted models (%d)"%len(sol)) plt.fill_between(f, -zn_max.imag, -zn_min.imag, color='lightgray', alpha=1, zorder=-1) plt.xlabel(sym_labels['freq'], fontsize=14) plt.ylabel(sym_labels['imag'], fontsize=14) # plt.legend(loc=2, numpoints=1, fontsize=14) # plt.xlim([None, 1]) # plt.title(title+" step method", fontsize=14) plt.ylim([0, max(-zn_dat.imag)]) # Freq-Ampl # plt.axes(ax[0]) # plt.errorbar(f, Amp_dat, Amp_err, None, '.', label='Data') # plt.semilogx(f, Amp_fit, 'r-', label='Fitted model') # plt.fill_between(f, Amp_max, Amp_min, color='dimgray', alpha=0.3) # plt.xlabel(sym_labels['freq'], fontsize=14) # plt.ylabel(sym_labels['ampl'], fontsize=14) # ax[0].legend(loc=1, numpoints=1, fontsize=12) # plt.ylim([None,1.0]) # # Freq-Phas # # Real-Imag plt.axes(ax[0]) plt.semilogx(f, zn_fit.real, '-', color='lightgray',zorder=0, label="Fitted models (%d)"%len(sol)) plt.fill_between(f, zn_min.real, zn_max.real, color='lightgray', alpha=1, zorder=-1) plt.xlabel(sym_labels['freq'], fontsize=14) plt.ylabel(sym_labels['real'], fontsize=14) # plt.legend([handle_dat, handle_fit], ["Data", "Fitted models"], loc=1, numpoints=1, fontsize=14) # plt.xlim([None, 1]) plt.ylim([0.0, 1.0]) # # plt.title(sample_name, fontsize=12) # plt.subplots_adjust(top=0.55) # plt.title(title+" step method", fontsize=14)
def plot_GPedge_mf(soln, GP_dir, opt, raw, path_save, rename, i_plot=None, title=None): plt.rc('font', **{'family':'Times New Roman'}) if i_plot is None: sample_loc = float(opt['sample_loc'][0]) sample_by = opt['sample_by'] i_plot = find_i_plot(sample_loc, raw, sample_by) if opt['xscale'] == 'log': plot = plt.semilogx print 'using log as xscale = '+str(opt['xscale']) else: plot = plt.plot print 'using linear as xscale = '+str(opt['xscale']) i = 0 for sp in GP_dir['member']: id_sp = soln.species_names.index(sp) mf = raw['mole_fraction'][i_plot, id_sp] #plot([0, mf], [-i,-i], color='k') #plt.text(0,-i, rename_species(sp, rename), horizontalalignment='right') plot(mf,-i, color='k', marker='o') plt.text(mf,-i, rename_species(sp, rename), horizontalalignment='right') i += 1 T = raw['temperature'] x = raw['axis0'] tau_ign = find_tau_ign_raw(raw) if title is None: title = 'T = '+str(T[i_plot])+', axis0 = '+str(x[i_plot]) if tau_ign is not None: title +=', norm_x = '+str(1.0*x[i_plot]/tau_ign) title+='\n' plt.title(title) plt.savefig(path_save) return True
def plot_log(): # Plot the tonemapping curves plt.figure(figsize=(12, 6)) color_in = [] color_generic = [] color_piecewise = [] color_uncharted = [] color_aces = [] color_linear = [] hdr_max = 16.0 generic = Generic(hdr_max) piecewise = Piecewise(hdr_max) for x in numpy.logspace(-1, 5, num=256, base=2): color = x - math.pow(2, -1) color_in.append(color) color_generic.append(generic.evaluate(color)) color_piecewise.append(piecewise.evaluate(color)) #color_uncharted.append(uncharted(color)) color_uncharted.append(normalized_uncharted(color, hdr_max)) #color_aces.append(aces(color)) color_aces.append(normalized_aces(color, hdr_max)) color_linear.append(normalized_linear(color, hdr_max)) plt.semilogx(color_in, color_generic, basex=2, label='Generic') plt.plot(color_in, color_piecewise, label='Piecewise') plt.plot(color_in, color_uncharted, label='Uncharted (normalized)') plt.plot(color_in, color_aces, label='ACES (normalized)') plt.plot(color_in, color_in, label='Linear (clamped)') plt.plot(color_in, color_linear, label='Linear (normalized)') plt.axis([0, 18.66, 0, 1.04]) plt.legend(loc=2, bbox_to_anchor=[0.0, 0.95]) plt.xlabel('Input') plt.ylabel('Tonemapped') ax = plt.axes() xlabels = ['', '', '0.015625', '0.03125', '0.0625', '0.125', '0.25', '0.5', '1.0', '2.0', '4.0', '8.0', '16.0'] ax.set_xticklabels(xlabels) ax.tick_params(which='both', # Options for both major and minor ticks direction='out', top='off', # turn off top ticks left='on', # turn off left ticks right='off', # turn off right ticks bottom='on') # turn off bottom ticks ax.axhline(1.0, linestyle='--', color='k') ax.axvline(1.0, linestyle=':', color='k') ax.axvline(16.0, linestyle='--', color='k') plt.savefig('tonemapper_log.png', bbox_inches='tight')
def filter_freqs(lowcut, highcut, fs, plot=False, corners=4): ''' The frequency band information should technically be the amplitude spectrum of the filtered seismograms, but the amplitude spectrum of the bandpass filter is sufficient. Here we use a bandpass butterworth filter. The function freq band takes 3 arguments: lowcut = low end of bandpass (in Hz) highcut = high end of bandpass (in Hz) fs = sample rate (1.0/dt) It returns two vectors: omega = frequency axis (in rad/s) amp = frequency response of the filter ''' #Define bandpass parameters nyquist = 0.5 * fs fmin = lowcut/nyquist fmax = highcut/nyquist #Make filter shape b, a = iirfilter(corners, [fmin,fmax], btype='band', ftype='butter') #Determine freqency response freq_range = np.linspace(0,0.15,200) w, h = freqz(b,a,worN=freq_range) omega = fs * w # in rad/s omega_hz = (fs * w) / (2*np.pi) # in hz amp = abs(h) if(plot == True): #Checks---------------- #plt.semilogx(omega,amp) #plt.axvline(1/10.0) #plt.axvline(1/25.0) #plt.axhline(np.sqrt(0.5)) plt.plot(omega,amp) plt.xlabel('frequency (rad/s)') plt.ylabel('amplitude') plt.show() return omega, amp
def plot_validation_curve(): name = 'svc_linear' pipeline = get_pipeline(name) param_range = np.logspace(-2, 3, 6) # param_range = np.logspace(-5, -1, 5) train_scores, val_scores = validation_curve( estimator=pipeline, X=train.as_matrix(), y=y_train_binary, param_name='%s__C' % name, # param_name='lr_lbfgs__tol', param_range=param_range, cv=5, scoring='accuracy', n_jobs=6 ) plt.semilogx( param_range, train_scores.mean(axis=1), ls='-', lw=1, color='b', alpha=1, label='train' ) plt.fill_between( param_range, train_scores.mean(axis=1) - train_scores.std(axis=1), train_scores.mean(axis=1) + train_scores.std(axis=1), color='b', alpha=0.1, lw=0.5 ) plt.semilogx( param_range, val_scores.mean(axis=1), ls='-', lw=1, color='r', alpha=1, label='validation' ) plt.fill_between( param_range, val_scores.mean(axis=1) - val_scores.std(axis=1), val_scores.mean(axis=1) + val_scores.std(axis=1), color='r', alpha=0.1, lw=0.5 ) plt.title('%s: validation curve' % name) plt.xlabel('C') plt.ylabel('Score') plt.ylim(0.0, 1.1) plt.legend(loc="best") plt.show() # **************************************************************************
def intensityRatioInterpolate(self,data, scale = 'lin', plot=0, verbose=0): ''' to take a set of date and interpolate against the IntensityRatio the scale can be one of 'lin'/'linear' [default], 'loglog', 'logx', 'logy', ''' # first, what variable to use if self.IntensityRatio['temperature'].max() > self.IntensityRatio['temperature'].min(): x = self.IntensityRatio['ratio'] y = self.IntensityRatio['temperature'] if verbose: print('using temperature with %i5 values'%(len(x))) print(' number of values') else: x = self.IntensityRatio['ratio'] y = self.IntensityRatio['eDensity'] # if x[0] > x[-1]: x = sorted(x) sy = [] for idx in range(len(y) -1, -1, -1): sy.append(y[idx]) else: sy = y # if 'lin' in scale: y2 = interpolate.splrep(x, sy, s=0) interpolatedData = interpolate.splev(data,y2) if plot: plt.plot(sy, x) plt.plot(interpolatedData, data, 'bD') elif scale == 'loglog': y2 = interpolate.splrep(np.log(x), np.log(sy), s=0) interpolatedData = np.exp(interpolate.splev(np.log(data),y2)) if plot: plt.loglog(sy, x) plt.loglog(interpolatedData, data, 'bD') elif scale == 'logx': y2 = interpolate.splrep(x, np.log(sy), s=0) interpolatedData = np.exp(interpolate.splev(data,y2)) if plot: plt.semilogx(sy, x) plt.semilogx(interpolatedData, data, 'bD') elif scale == 'logy': y2 = interpolate.splrep(np.log(x), sy, s=0) interpolatedData = interpolate.splev(np.log(data),y2) if plot: plt.semilogy(sy, x) plt.semilogy(interpolatedData, data, 'bD') else: print(' scale not understood = %s'%(scale)) for i, avalue in enumerate(interpolatedData): print(' data, value = %12.3e %12.3e'%(data[i], avalue)) self.IntensityRatioInterpolated = {'data':data, 'value':interpolatedData}
def spectogram(trace, traceSyn): ''' Plots the amplitude spectrum of a recorded trace and a sytnthetic trace. Calculation with the Fast Fourier Transform (FFT) from numpy. The x-axis is converted to frequencies from 0 to half of the maximum sampling frequency (Nyquist frequency). The y-axis is converted by taking the absolute value of the FFT and multiplication by a factor of 2. Further the amplitude has to be normalized with the number of samples. To improve the amplitude spectrum the data is also multiplied with a Hanning window. Balzer explains how to apply the FFT in his IPython Notebook: rhttp://nbviewer.jupyter.org/github/balzer82/FFT-Python/blob/master/FFT-Tutorial.ipynb :param trace: The recorded trace :type trace: obspy.core.trace.Trace :param traceSyn: The synthetic trace :type traceSyn: obspy.core.trace.Trace ''' #spektrum trace.data -= trace.data.mean() traceSyn.data -= traceSyn.data.mean() Fs = trace.stats.sampling_rate fig = plt.figure(1) fig.suptitle(trace.stats.station, fontsize=20) ax1 = plt.subplot(211) ax1.set_title('Recorded Signal') # Calculate amplitude spectrum for recorded data y = trace.data hann = np.hanning(len(y)) N = len(y)/2 +1 Y = np.fft.fft(y*hann) X = np.linspace(0, Fs/2, N, endpoint = True) plt.ylabel('|Ground Motion (m/s)|') plt.semilogx(X, (2.0*np.abs(Y[:N])/N), 'k') # plotting the spectrum plt.setp(ax1.get_xticklabels(), visible=False) # Calculate amplitude spectrum for synthetic data y = traceSyn.data hann = np.hanning(len(y)) N = len(y)/2 +1 Y = np.fft.fft(y*hann) X = np.linspace(0, Fs/2, N, endpoint = True) ax2 = plt.subplot(212, sharex=ax1) ax2.set_title('Synthetic Signal') plt.semilogx(X, (2.0*np.abs(Y[:N]))/N) # plotting the spectrum plt.xlabel('Freq (Hz)') plt.ylabel('|Ground Motion (m/s)|') plt.yticks(np.array([0,1,2,3,4,5])*10e-8) plt.ticklabel_format(axis='y',style='sci',scilimits=(0,0)) fig.subplots_adjust(top=0.85) plt.savefig('../spectrum.pdf', bbox_inches='tight', pad_inches=0.05) plt.draw()
def test_dqn(): import os filename = 'dqn.h5' single_run = True load = False save = False n_episode = 100 tMax = 200 env = gym.make('CartPole-v0') S = env.observation_space A = env.action_space learning_rate=5e-3 gamma=0.99 policy=epsilon_greedy batch_size=32 update_freq=1000 memory_size=10000 agent = DQN(S, A, learning_rate=learning_rate, gamma=gamma, policy=policy, batch_size=batch_size, update_freq=update_freq, memory_size=memory_size) initial_weights = agent.model.get_weights() if single_run: agent = DQN(S, A, learning_rate=learning_rate, gamma=gamma, policy=policy, batch_size=batch_size, update_freq=update_freq, memory_size=memory_size) if load: if os.path.isfile(filename): agent.model = load_model(filename) agent.target_model = load_model(filename) ave_r = run(env, agent, n_episode, tMax, plot=False) if save: agent.model.save(filename) else: # Sample learning rates # lrs = 10**np.random.uniform(-4.0, -2, size=10) learning_rates = [lrs[n] for n in xrange(lrs.shape[0]) ] ave_returns = [] for lr in learning_rates: agent = DQN(S, A, learning_rate=lr, gamma=gamma, policy=policy, batch_size=batch_size, update_freq=update_freq, memory_size=memory_size) agent.model.set_weights(initial_weights) agent.target_model.set_weights(initial_weights) ave_r = run(env, agent, n_episode, tMax, plot=True) ave_returns.append(ave_r) plt.figure() plt.semilogx(learning_rates, ave_returns, 'o') plt.savefig('lr_returns.png'.format(), format='png') plt.xlabel('learning rate') plt.ylabel('average returns')
def test_proportional(self, base_instrs, p_dB, in_offset, out_offset): """ Tests the Proportional (gain only) setting of both PID channels with various offsets. :type p_dB: float; :param p_dB: Proportional gain for PIDs (in dB/amplitude gain) :type in_offset: float; V :param in_offset: Signal offset at input :type out_offset: float; V :param out_offset: Signal offset at output """ master = base_instrs[0] slave = base_instrs[1] # Set up the Bode Analyser to be 10Hz-1MHz, 100mVpp sweep master.set_output(1, BODE_SWEEP_AMPLITUDE) master.set_output(2, BODE_SWEEP_AMPLITUDE) master.set_sweep(BODE_SWEEP_MIN,BODE_SWEEP_MAX,sweep_points=512,averaging_time=0.002, settling_time=0.002, averaging_cycles=4, settling_cycles=4) # Set up the PID Controller slave.set_by_frequency(1, kp=from_dB(p_dB), in_offset=in_offset, out_offset=out_offset) slave.set_by_frequency(2, kp=from_dB(p_dB), in_offset=in_offset, out_offset=out_offset) # Take a single sweep of the system under test master.start_sweep(single=True) # Get the sweep data data = master.get_data() # Perform calculations on the data # Check that the min/max never exceed a particular tolerance print("Channel 1") in_rms_bounds(data.ch1.magnitude_dB, p_dB, 1) print("Channel 2") in_rms_bounds(data.ch2.magnitude_dB, p_dB, 1) plt.ion() plt.show() plt.semilogx(data.frequency, data.ch1.magnitude_dB) plt.semilogx(data.frequency, data.ch2.magnitude_dB) plt.pause(5) """ # Check the data plt.ion() plt.show() plt.plot(data.frequency, data.ch1.magnitude_dB) #plt.plot(data.ch2.magnitude) plt.plot(calibration_trace.frequency, calibration_trace.ch1.magnitude_dB) #plt.plot(calibration_trace.ch2.magnitude) plt.pause(10) """ assert False
def do_benchmark(): functions = [ # quicksort_flat, # quicksort_hybrid, quicksort, heap_sort, # heap_sort_batch, # lazysort, sorted, # insertion_sort, # merge_sort, ] r = random.Random(0) batch_unsorted_ints = [ [r.randint(0, 1024) for _ in range(1 << 21)], [r.randint(0, 1024) for _ in range(1 << 21)], [r.randint(0, 1024) for _ in range(1 << 21)], ] sizes = [1 << i for i in range(5, 17)] sizes += [s * 3 for s in sizes if s > 100] sizes += [s * 5 for s in sizes if s > 100] sizes.sort() # sizes = range(1000, 50000, 1000) print("%20s" % "", end="") for size in sizes: print("%6i " % size, end="") print() plt.xlabel("Number of Integers") plt.ylabel("Total ms spent") plt.axis([0, max(sizes), 0, 400]) # plt.semilogx() # plt.semilogy() for sort_fn in functions: print("%20s" % sort_fn.__name__, end="") results = [] for size in sizes: durations = [ benchmark_one(sort_fn, size, 10, i) * 1000 for i in batch_unsorted_ints ] durations.sort() duration = durations[1] results.append(duration) print("%6.1fms " % duration, end="") sys.stdout.flush() if duration > 2000: break plt.plot(sizes[:len(results)], results, label=sort_fn.__name__) print() plt.legend() plt.show()
def fft(tmp,tmpch,samp,freqall,pathfig) : # Calculate the Fourier transform for one time serie # Names allowed in freqall = intra,inter,decadal y = tmp L = len(y) # Length of the signal NF = len(freqall) tmpFFT = np.zeros((NF,L)) if samp is 'mth' : Fs = 1/(30.*24.*3600.) # Sampling frequency # Not sure about the real value to use ripple = 0.01#.00001 #Fs#(Fs/np.power(10,8))*10^12 fig = plt.figure('freq') #print freqall j = 1 for ff in freqall : # Extract information band, deg, pmin, pmax = define_fft(ff) if band is 'low' : WP = 2/float(pmin) elif band is 'high' : WP = 2/float(pmax) else : WP = [2/float(pmax),2/float(pmin)] # Create a Chebyshev type I filter design b, a = signal.cheby1(deg, ripple, WP, band) # Frequency and amplitude of the signal w, h = signal.freqs(b, a) # Forward-backward filter yd = signal.filtfilt(b, a, tmp) if NF >= 2 : plt.subplot(2,round(float(NF)/2),j) plt.plot(tmp,'k') plt.plot(yd,'r') #plt.semilogx(w, np.log10(abs(h))) plt.title(ff) # Saving the filtered time series tmpFFT[j-1,:]=yd del yd j += 1 namefig = 'FFT_decomp_'+samp fig.savefig(pathfig+namefig+'_'+tmpch+'.png') fig.savefig(pathfig+namefig+'_'+tmpch+'.pdf') plt.close() del ripple, WP, band, deg, pmin, pmax return tmpFFT # FFT information(cheby1 filter)