markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Lower left panel
pu.PlotFrequency(s4gdata.logfgas, ii_barred_limited1_m8_5, ii_unbarred_limited1_m8_5, -3,2,0.5, noErase=False, fmt='ro', ms=9, label=ss1m) pu.PlotFrequency(s4gdata.logfgas, ii_barred_limited2_m9, ii_unbarred_limited2_m9, -3,2,0.5, offset=0.03, noErase=True, fmt='ro', mfc='None', mec='r', ms=9, label=ss2m) plt.xlabel(xt...
s4gbars_main.ipynb
perwin/s4g_barfractions
bsd-3-clause
Lower right panel
pu.PlotFrequency(s4gdata.logfgas, ii_SB_limited1_m8_5, ii_nonSB_limited1_m8_5, -3,2,0.5, fmt='ko', ms=8, label="SB ("+ss1m+")") pu.PlotFrequency(s4gdata.logfgas, ii_SB_limited2_m9, ii_nonSB_limited2_m9, -3,2,0.5, noErase=True, ms=8, fmt='ko', mfc='None', mec='k', offset=0.03, label="SB ("+ss2m+")") pu.PlotFrequency(s4g...
s4gbars_main.ipynb
perwin/s4g_barfractions
bsd-3-clause
Figure B2
ii_all_limited1_S0 = [i for i in range(nDisksTotal) if s4gdata.dist[i] <= 25 and s4gdata.t_s4g[i] <= -0.5] ii_barred_limited1_with_S0 = [i for i in range(nDisksTotal) if i in ii_barred and s4gdata.dist[i] <= 25] ii_unbarred_limited1_with_S0 = [i for i in range(nDisksTotal) if i in ii_unbarred and s4gdata.dist[i] <= 25]...
s4gbars_main.ipynb
perwin/s4g_barfractions
bsd-3-clause
Create Two Vectors
# Create two vectors vector_a = np.array([1,2,3]) vector_b = np.array([4,5,6])
machine-learning/calculate_dot_product_of_two_vectors.ipynb
tpin3694/tpin3694.github.io
mit
Calculate Dot Product (Method 1)
# Calculate dot product np.dot(vector_a, vector_b)
machine-learning/calculate_dot_product_of_two_vectors.ipynb
tpin3694/tpin3694.github.io
mit
Calculate Dot Product (Method 2)
# Calculate dot product vector_a @ vector_b
machine-learning/calculate_dot_product_of_two_vectors.ipynb
tpin3694/tpin3694.github.io
mit
Data science friday tales: Using Fréchet Bounds for Bandwidth selection in MV Kernel Methods. Lia Silva-Lopez Tuesday, 19/03/2019 This story starts with a reading accident One moment you are reading a book... <img src="img/reading_accident.png"> ...And the next there are bounds for everything. Bounds for distribution...
n=1000 distr=spst.beta #<-- From SciPy smpl=np.linspace(0,1,num=n) params={'horns':(0.5,0.5),'horns1':(0.5,0.55), 'shower':(5.,2.),'grower':(2.,5.)} v_type=f'{"c"*len(params)}' #<-- Statsmodels wants to know if data is # continuous (c) # discrete ordere...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
Kernels and BW Selection Methods Kernel selection depends on "v_type". For "c" -> Gaussian Kernel. This is a list of the kernel functions available in the package kernel_func = dict( wangryzin=kernels.wang_ryzin, aitchisonaitken=kernels.aitchison_aitken, gaussian=kernels.ga...
import statsmodels.api as sm #Generate some independent data for each parameter set mvdata={k:distr.rvs(*params[k],size=n) for k in params} rd=np.array(list(mvdata.values())) %timeit -n3 sm.nonparametric.KDEMultivariate(data=rd,var_type=v_type, bw='normal_reference') dens_u_rot = sm.nonparametric.KDEMultivariate(data...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
Now the fun part: modifying the package to do our bidding All we need is in two classes: class KDEMultivariate(GenericKDE) and its parent, class GenericKDE(object). When we call the constructor for the KDEMultivariate object, this happens: Data checks & reshaping, internal stuff settings. Bandwidth selection func...
def loo_likelihood(self, bw, func=lambda x: x): LOO = LeaveOneOut(self.data) #<- iterator for a leave-one-out over the data L = 0 for i, X_not_i in enumerate(LOO): #<- per leave-one-out of the data (ouch!) f_i = gpke(bw, #<- provided by the optimization algorithm ...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
What happens inside gkpe? Both the CDF and PDF are estimated with a gpke. They just use a different kernel. All the kernel implementations are here.
def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True): kertypes = dict(c=ckertype, o=okertype, u=ukertype) #<- kernel selection Kval = np.empty(data.shape) for ii, vtype in enumerate(var_type): #per ii dimension f...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
What did I do? Groundwork: Methods for: Estimating the Fréchet bounds for a dataset. Visualizing the bounds (2d datasets) see here Counting how many violations of the bound were made by a CDF. Measuring the size of the violation at each point (diff between the point of the CDF in which the violation happened,...
def get_frechets(dvars): d=len(dvars) n=len(dvars[0]) dimx=np.array(range(d)) un=np.ones(d,dtype=int) bottom_frechet = np.array([max( np.sum( dvars[dimx,un*i] ) +1-d, 0 ) for i in range(n) ]) top_frechet = np.array([min([y[i] for y in dvars]) for i in range(n...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
Calculating number of violations
def check_frechet_fails(guinea_cdf,frechets): fails={'top':[], 'bottom':[]} for n in range(len(guinea_cdf)): #n_hyper_point=np.array([x[n] for x in rd]) if guinea_cdf[n]>frechets['top'][n]: fails['top'].append(True) else: fails['top'].append(False) if gui...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
Given 4 dimensions and 1000 samples, we got: For Silverman: 58.8% violations For cv_ml: 58.0% violations For cv_ls: 57.0% violations
# For Silverman violations_silverman=check_frechet_fails(dens_u_rot.cdf(),frechets) violations_silverman=np.sum(violations_silverman['top'])+ np.sum(violations_silverman['bottom']) print(f'violations:{violations_silverman} ({100.*violations_silverman/len(smpl)}%)') # For cv_ml violations_cv_ml=check_frechet_fails(dens...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
What more? Quite a lot of sweat went into generating code for comparing my approaches with cv_ml I may as well show it to you, and point where the bug was :(.
def generate_experiments(reps,n,params, distr, dims): bws_frechet={f'bw_{x}':[] for x in params} bws_cv_ml={f'bw_{x}':[] for x in params} for iteration in range(reps): mvdata = {k: distr.rvs(*params[k], size=n) for k in params} rd = np.array(list(mvdata.values())) #<---- THIS IS NOT A CDF!...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
And this is how the functions that make the calculations look underneath.
def get_bw(datapfft, var_type, reference, frech_bounds=None): # Using leave-one-out likelihood # the initial value for the optimization is the normal_reference # h0 = normal_reference() data = adjust_shape(datapfft, len(var_type)) if not frech_bounds: fmin =lambda bw, funcx: loo_likelihood...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
And this was my frechet_likelihood method
def frechet_likelihood(bww, datax, var_type, frech_bounds, func=None, debug_mode=False,): cdf_est = cdf(datax, bww, var_type) # <- calls gpke underneath, but is a short call d_violations = calc_frechet_fails(cdf_est, frech_bounds) width_bound = frech_bounds['top'] - frech_bounds['bottom'] ...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
And this is how profiling info was collected The python profiler is a bit unfriendly, so maybe this code could be useful as a snippet? Or, getting a professional license of pycharm ;) (Thanks boss!)
def profile_run(rd,frechets,iterx): dims=len(rd) n=len(rd[0]) v_type = f'{"c"*dims}' # threshold: number of violations by the cheapest method. dens_u_rot = sm.nonparametric.KDEMultivariate(data=rd, var_type=v_type, bw='normal_reference') cdf_dens_u_rot = dens_u_rot.cdf() violations_rot = cou...
mv_kecdf_frechet.ipynb
lia-statsletters/notebooks
gpl-3.0
Elif Let's say you want to check a different condition before just saying, "The first condition was false, let's do the else statement." We could just use a second if statement, but instead we have the else-if statement, elif. It allows us to check a second condition after the first one fails. Let us concrete this idea...
#I love food, let's take a look in my fridge fridge = ['bananas', 'apples', 'water', 'tortillas', 'cheese'] #I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese if('pizza' in fridge): print('Patrick ate pizza and was happy') elif('tortillas' in fridge and 'c...
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
Let's revamp that example, but this time, I went out and bought a pizza.
#I love food, let's take a look in my fridge fridge = ['bananas', 'apples', 'water', 'tortillas', 'cheese', 'pizza'] #I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese if('pizza' in fridge): print('Patrick ate pizza and was happy') elif('tortillas' in frid...
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
Notice that, although I had the fixings for a quesadilla in my fridge, I had pizza so I never needed to check for a tortilla and cheese. This illustrates the fact that elif wont run unless the if statements before it fails. Further, you can stack elif statements forever. Let's see that.
#I love food, let's take a look in my fridge fridge = ['bananas', 'apples', 'water', 'tortillas', 'beer'] #I want some pizza, but if I don't have any I will settle for a quesadilla which requires tortillas and cheese if('pizza' in fridge): print('Patrick ate pizza and was happy') elif('tortillas' in fridge and 'che...
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
Exercises Write some "dummy" if, if else, and if elif else statements that will print out exactly what you expect until you feel comfortable with them. What will be the output of the following code sample: if(2<4): if(len([1,2,3])<=len(set([1,1,1,2,2,3,3,3]))): print("This will certainly print") elif(...
t=15 while(t>0): print("t-minus " + str(t)) t-=1
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
While loops are really good if you want to do something over and over again. Let's generate some fake data with this. I introduce here the range() function. This generates a list of numbers. Let's see briefly how it works.
# Let's make a list of numbers starting at zero and going to 99. range() by default uses a step size of 1 #so this will yield integers from 0 to 99 x = range(0,100) print(x) # Unfortunately range does some strange things and doesn't return a list, if you want a list, you already know how to convert it. print(list(x)) ...
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
So that was a cute example of how we can generate some data based on some equation. Later on, however, we will want to graph our data and this requires a second list for our x values. The while loop is cumbersome in the respect and so we now introduce the for loop. For Loops A for loop will loop through any container e...
x = range(1,100) #Remember that this makes a list of integers from 1 to 99 y = [] for val in x: #val is our special variable here, it will take on the value of every element in x print(val) y.append(val**2+3*val) print(y)
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
Again, a neat little example. The true power of for loops comes when we have lists that are not numerical. Let's make every string in a list uppercase.
words = ['i', 'am', 'sorry', 'dave', 'i', 'can\'t', 'do', 'that'] upperwords = [] for word in words: #remember that word will take on the value of every element of words print(word) upperwords.append(word.upper()) # to make a string uppercase, you can use the .upper() function. print(upperwords)
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
We have one more special type of loop to cover. List comprehensions; a quick way to make a list in one line. List Comprehensions A list comprehension is essentially a for loop sandwiched into a list. The syntax for a list comprehension is as follows: X = [(expression involving special variable) for (special variable) i...
y = [x**2 for x in range(0,11)] print(y)
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
What about something wierder?
print(words) wordslength = [len(word) for word in words] print(wordslength)
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
My god, it worked! Think of the possibilities! With these new tools we can do 90% of all programming we will ever do. Pretty neat huh. I would like to show you one more example of list comprehensions.
# I only want words with length less than 3 newwords = [word for word in words if len(word)<3] print(newwords)
Python Workshop/Logic.ipynb
CalPolyPat/Python-Workshop
mit
Problem statement Tuning the hyper-parameters of a machine learning model is often carried out using an exhaustive exploration of (a subset of) the space all hyper-parameter configurations (e.g., using sklearn.model_selection.GridSearchCV), which often results in a very time consuming operation. In this notebook, we i...
from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.model_selection import cross_val_score boston = load_boston() X, y = boston.data, boston.target reg = GradientBoostingRegressor(n_estimators=50, random_state=0) def objective(params): max_depth, learning_r...
examples/hyperparameter-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Next, we need to define the bounds of the dimensions of the search space we want to explore, and (optionally) the starting point:
space = [(1, 5), # max_depth (10**-5, 10**-1, "log-uniform"), # learning_rate (1, X.shape[1]), # max_features (2, 30), # min_samples_split (1, 30)] # min_samples_leaf x0 = [3, 0.01, 6,...
examples/hyperparameter-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Optimize all the things! With these two pieces, we are now ready for sequential model-based optimisation. Here we compare gaussian process-based optimisation versus forest-based optimisation.
from skopt import gp_minimize res_gp = gp_minimize(objective, space, x0=x0, n_calls=50, random_state=0) "Best score=%.4f" % res_gp.fun print("""Best parameters: - max_depth=%d - learning_rate=%.6f - max_features=%d - min_samples_split=%d - min_samples_leaf=%d""" % (res_gp.x[0], res_gp.x[1], ...
examples/hyperparameter-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
As a baseline, let us also compare with random search in the space of hyper-parameters, which is equivalent to sklearn.model_selection.RandomizedSearchCV.
from skopt import dummy_minimize res_dummy = dummy_minimize(objective, space, x0=x0, n_calls=50, random_state=0) "Best score=%.4f" % res_dummy.fun print("""Best parameters: - max_depth=%d - learning_rate=%.4f - max_features=%d - min_samples_split=%d - min_samples_leaf=%d""" % (res_dummy.x[0], res_dummy.x[1], ...
examples/hyperparameter-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Convergence plot
from skopt.plots import plot_convergence plot_convergence(("gp_optimize", res_gp), ("forest_optimize", res_forest), ("dummy_optimize", res_dummy))
examples/hyperparameter-optimization.ipynb
glouppe/scikit-optimize
bsd-3-clause
Prepare the pipeline (str) filepath: Give the csv file (str) y_col: The column to predict (bool) regression: Regression or Classification ? (bool) process: (WARNING) apply some preprocessing on your data (tune this preprocess with params below) (char) sep: delimiter (list) col_to_drop: which columns you don't want to u...
cls = Baboulinet(filepath="toto2.csv", y_col="predict", regression=True)
mozinor/example/Mozinor example Reg.ipynb
Jwuthri/Mozinor
mit
Open the file located in the path directory, one line at a time, and store it in a list called records.
records = [json.loads(line) for line in open(path,'r')] type(records) records[0]
chapter 02/List-dict-defaultdict-Counter.ipynb
harishkrao/Python-for-Data-Analysis
mit
Calling a specific key within the list
records[0]['tz']
chapter 02/List-dict-defaultdict-Counter.ipynb
harishkrao/Python-for-Data-Analysis
mit
Printing all time zone values in the records list. Here we search for the string 'tz' in each element of the records list. If the search returns a string, then we print the corresponding value of the key 'tz' for that element.
time_zones = [rec['tz'] for rec in records if 'tz' in rec] time_zones[:10]
chapter 02/List-dict-defaultdict-Counter.ipynb
harishkrao/Python-for-Data-Analysis
mit
Counting the frequency of each time zone's occurrence in the list using a dict type in Python
counts = {} for x in time_zones: if x in counts: counts[x] = counts.get(x,0) + 1 else: counts[x] = 1 print(counts) from collections import defaultdict counts = defaultdict(int) for x in time_zones: counts[x] += 1 print(counts) counts['America/New_York'] len(time_zones)
chapter 02/List-dict-defaultdict-Counter.ipynb
harishkrao/Python-for-Data-Analysis
mit
To list the top n time zone occurrences
def top_counts(count_dict, n): value_key_pairs = [(count, tz) for tz, count in count_dict.items()] value_key_pairs.sort() return value_key_pairs[-n:] top_counts(counts,10) from collections import Counter counts = Counter(time_zones) counts.most_common(10)
chapter 02/List-dict-defaultdict-Counter.ipynb
harishkrao/Python-for-Data-Analysis
mit
ReportLab import the necessary functions one by one
from markdown import markdown as md_markdown from xml.etree.ElementTree import fromstring as et_fromstring from xml.etree.ElementTree import tostring as et_tostring from reportlab.platypus import BaseDocTemplate as plat_BaseDocTemplate from reportlab.platypus import Frame as plat_Frame from reportlab.platypus import ...
iPython/Reportlab2-FromMarkdown.ipynb
oditorium/blog
agpl-3.0
The ReportFactory class creates a ReportLab document / report object; the idea is that all style information as well as page layouts are collected in this object, so that when a different factory is passed to the writer object the report looks different.
class ReportFactory(): """create a Reportlab report object using BaseDocTemplate the report creation is a two-step process 1. instantiate a ReportFactory object 2. retrieve the report using the report() method note: as it currently stands the report object is remembered in the fac...
iPython/Reportlab2-FromMarkdown.ipynb
oditorium/blog
agpl-3.0
The ReportWriter object executes the conversion from markdown to pdf. It is currently very simplistic - for example there is no entry hook for starting the conversion at the html level rather than at markdown, and only a few basic tags are implemented.
class ReportWriter(): def __init__(self, report_factory): self._simple_tags = { 'h1' : 'Heading1', 'h2' : 'Heading2', 'h3' : 'Heading3', 'h4' : 'Heading4', 'h5' : 'Heading5', 'p' : 'BodyText', } ...
iPython/Reportlab2-FromMarkdown.ipynb
oditorium/blog
agpl-3.0
create a standard report (A4, black text etc)
rfa4 = ReportFactory('report_a4.pdf') pdfw = ReportWriter(rfa4) pdfw.create_report(markdown_text*10)
iPython/Reportlab2-FromMarkdown.ipynb
oditorium/blog
agpl-3.0
create a second report with different parameters (A5, changed colors etc; the __dict__ method shows all the options that can be modified for changing styles)
#rfa5.styles['Normal'].__dict__ rfa5 = ReportFactory('report_a5.pdf') rfa5.pagesize = ps_portrait(ps_A5) #rfa5.styles['Normal'].textColor = '#664422' #rfa5.refresh_styles() rfa5.styles['BodyText'].textColor = '#666666' rfa5.styles['Bullet'].textColor = '#666666' rfa5.styles['Heading1'].textColor = '#000066' rfa5.sty...
iPython/Reportlab2-FromMarkdown.ipynb
oditorium/blog
agpl-3.0
Note that 12288 comes from $64 \times 64 \times 3$. Each image is square, 64 by 64 pixels, and 3 is for the RGB colors. Please make sure all these shapes make sense to you before continuing. Your goal is to build an algorithm capable of recognizing a sign with high accuracy. To do so, you are going to build a tensorflo...
# GRADED FUNCTION: create_placeholders def create_placeholders(n_x, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288) n_y -- scalar, number of classes (from 0 to 5, so -> 6) Returns:...
archive/MOOC/Deeplearning_AI/ImprovingDeepNeuralNetworks/HyperparameterTuning/Tensorflow+Tutorial.ipynb
KrisCheng/ML-Learning
mit
Expected Output: <table> <tr> <td> **Z3** </td> <td> Tensor("Add_2:0", shape=(6, ?), dtype=float32) </td> </tr> </table> You may have noticed that the forward propagation doesn't output any cache. You will understand why below, when we get to brackpropaga...
# GRADED FUNCTION: compute_cost def compute_cost(Z3, Y): """ Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the c...
archive/MOOC/Deeplearning_AI/ImprovingDeepNeuralNetworks/HyperparameterTuning/Tensorflow+Tutorial.ipynb
KrisCheng/ML-Learning
mit
<a id='sec3.2'></a> 3.2 Compute POI Info Compute POI (Longitude, Latitude) as the average coordinates of the assigned photos.
poi_coords = traj[['poiID', 'photoLon', 'photoLat']].groupby('poiID').agg(np.mean) poi_coords.reset_index(inplace=True) poi_coords.rename(columns={'photoLon':'poiLon', 'photoLat':'poiLat'}, inplace=True) poi_coords.head()
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec3.3'></a> 3.3 Construct Travelling Sequences
seq_all = traj[['userID', 'seqID', 'poiID', 'dateTaken']].copy()\ .groupby(['userID', 'seqID', 'poiID']).agg([np.min, np.max]) seq_all.head() seq_all.columns = seq_all.columns.droplevel() seq_all.head() seq_all.reset_index(inplace=True) seq_all.head() seq_all.rename(columns={'amin':'arrivalTime', 'amax':'d...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec3.4'></a> 3.4 Transition Matrix 3.4.1 Transition Matrix for Time at POI
users = seq_all['userID'].unique() transmat_time = pd.DataFrame(np.zeros((len(users), poi_all.index.shape[0]), dtype=np.float64), \ index=users, columns=poi_all.index) poi_time = seq_all[['userID', 'poiID', 'poiDuration(sec)']].copy().groupby(['userID', 'poiID']).agg(np.sum) poi_time.head(...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
3.4.2 Transition Matrix for POI Category
poi_cats = traj['poiTheme'].unique().tolist() poi_cats.sort() poi_cats ncats = len(poi_cats) transmat_cat = pd.DataFrame(data=np.zeros((ncats, ncats), dtype=np.float64), index=poi_cats, columns=poi_cats) for seqid in seq_all['seqID'].unique().tolist(): seqi = seq_all[seq_all['seqID'] == seqid].copy() seqi.sor...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
Normalise each row to get an estimate of transition probabilities (MLE).
for r in transmat_cat.index: rowsum = transmat_cat.ix[r].sum() if rowsum == 0: continue # deal with lack of data transmat_cat.loc[r] /= rowsum transmat_cat
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
Compute the log of transition probabilities with smooth factor $\epsilon=10^{-12}$.
log10_transmat_cat = np.log10(transmat_cat.copy() + 1e-12) log10_transmat_cat
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec4'></a> 4. Trajectory Recommendation -- Approach I A different leave-one-out cross-validation approach: - For each user, choose one trajectory (with length >= 3) uniformly at random from all of his/her trajectories as the validation trajectory - Use all other trajectories (of all users) to 'train' (i...
cv_seqs = seq_all[['userID', 'seqID', 'poiID']].copy().groupby(['userID', 'seqID']).agg(np.size) cv_seqs.rename(columns={'poiID':'seqLen'}, inplace=True) cv_seqs = cv_seqs[cv_seqs['seqLen'] > 2] cv_seqs.reset_index(inplace=True) print(cv_seqs.shape) cv_seqs.head() cv_seq_set = [] # choose one sequence for each user i...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec4.2'></a> 4.2 Recommendation by Solving ILPs
def calc_poi_info(seqid_set, seq_all, poi_all): poi_info = seq_all[seq_all['seqID'].isin(seqid_set)][['poiID', 'poiDuration(sec)']].copy() poi_info = poi_info.groupby('poiID').agg([np.mean, np.size]) poi_info.columns = poi_info.columns.droplevel() poi_info.reset_index(inplace=True) poi_info.rename(c...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec4.3'></a> 4.3 Evaluation Results from paper (Toronto data, time-based uesr interest, eta=0.5): - Recall: 0.779&plusmn;0.10 - Precision: 0.706&plusmn;0.013 - F1-score: 0.732&plusmn;0.012
def calc_recall_precision_F1score(seq_act, seq_rec): assert(len(seq_act) > 0) assert(len(seq_rec) > 0) actset = set(seq_act) recset = set(seq_rec) intersect = actset & recset recall = len(intersect) / len(seq_act) precision = len(intersect) / len(seq_rec) F1score = 2. * precision * recal...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec5'></a> 5. Trajectory Recommendation -- Approach II The paper stated "We evaluate PERSTOUR and the baselines using leave-one-out cross-validation [Kohavi,1995] (i.e., when evaluating a specific travel sequence of a user, we use this user's other travel sequences for training our algorithms" While it's not cle...
seq_ge3 = seq_len[seq_len['seqLen'] >= 3] seq_ge3['seqLen'].hist(bins=20)
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
Split travelling sequences into training set and testing set using leave-one-out for each user. For testing purpose, users with less than two travelling sequences are not considered in this experiment.
train_set = [] test_set = [] user_seqs = seq_ge3[['userID', 'seqID']].groupby('userID') for user, indices in user_seqs.groups.items(): if len(indices) < 2: continue idx = random.choice(indices) test_set.append(seq_ge3.loc[idx, 'seqID']) train_set.extend([seq_ge3.loc[x, 'seqID'] for x in indices if x !...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
Sanity check: the total number of travelling sequences used in training and testing
seq_exp = seq_ge3[['userID', 'seqID']].copy() seq_exp = seq_exp.groupby('userID').agg(np.size) seq_exp.reset_index(inplace=True) seq_exp.rename(columns={'seqID':'#seq'}, inplace=True) seq_exp = seq_exp[seq_exp['#seq'] > 1] # user with more than 1 sequences print('total #seq for experiment:', seq_exp['#seq'].sum()) #seq...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec5.2'></a> 5.2 Compute POI popularity and user interest using training set Compute average POI visit duration, POI popularity as defined at the top of the notebook.
poi_info = seq_all[seq_all['seqID'].isin(train_set)] poi_info = poi_info[['poiID', 'poiDuration(sec)']].copy() poi_info = poi_info.groupby('poiID').agg([np.mean, np.size]) poi_info.columns = poi_info.columns.droplevel() poi_info.reset_index(inplace=True) poi_info.rename(columns={'mean':'avgDuration(sec)', 'size':'popu...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
Compute time/frequency based user interest as defined at the top of the notebook.
user_interest = seq_all[seq_all['seqID'].isin(train_set)] user_interest = user_interest[['userID', 'poiID', 'poiDuration(sec)']].copy() user_interest['timeRatio'] = [poi_info.loc[x, 'avgDuration(sec)'] for x in user_interest['poiID']] #user_interest[user_interest['poiID'].isin({9, 10, 12, 18, 20, 26})] #user_interest[...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='switch'></a> Sum defined in paper, but sum of (time ratio) * (avg duration) will become extremely large in some cases, which is unrealistic, switch between the two to have a look at the effects.
#user_interest = user_interest.groupby(['userID', 'poiTheme']).agg([np.sum, np.size]) # the sum user_interest = user_interest.groupby(['userID', 'poiTheme']).agg([np.mean, np.size]) # try the mean value user_interest.columns = user_interest.columns.droplevel() #user_interest.rename(columns={'sum':'timeBased', 'size':'...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec5.3'></a> 5.3 Generate ILP
poi_dist_mat = pd.DataFrame(data=np.zeros((poi_info.shape[0], poi_info.shape[0]), dtype=np.float64), \ index=poi_info.index, columns=poi_info.index) for i in range(poi_info.index.shape[0]): for j in range(i+1, poi_info.index.shape[0]): r = poi_info.index[i] c = poi_info.i...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
5.3.1 Generate ILPs for training set
def extract_seq(seqid_set, seq_all): """Extract the actual sequences (i.e. a list of POI) from a set of sequence ID""" seq_dict = dict() for seqid in seqid_set: seqi = seq_all[seq_all['seqID'] == seqid].copy() seqi.sort(columns=['arrivalTime'], ascending=True, inplace=True) seq_dict[...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
5.3.2 Generate ILPs for testing set
test_seqs = extract_seq(test_set, seq_all) for seqid in sorted(test_seqs.keys()): if not os.path.exists(lpDir): print('Please create directory "' + lpDir + '"') break seq = test_seqs[seqid] lpFile = os.path.join(lpDir, str(seqid) + '.lp') user = seq_user.loc[seqid].iloc[0] the_user...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
<a id='sec5.4'></a> 5.4 Evaluation
def load_solution_gurobi(fsol, startPoi, endPoi): """Load recommended itinerary from MIP solution file by GUROBI""" seqterm = [] with open(fsol, 'r') as f: for line in f: if re.search('^visit_', line): # e.g. visit_0_7 1\n item = line.strip().split(' ') # visi...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
5.4.1 Evaluation on training set
train_seqs_rec = dict() solDir = os.path.join(data_dir, os.path.join('lp_' + suffix, 'eta05_time')) #solDir = os.path.join(data_dir, os.path.join('lp_' + suffix, 'eta10_time')) if not os.path.exists(solDir): print('Directory for solution files', solDir, 'does not exist.') for seqid in sorted(train_seqs.keys()): ...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
5.4.2 Evaluation on testing set Results from paper (Toronto data, time-based uesr interest, eta=0.5): - Recall: 0.779&plusmn;0.10 - Precision: 0.706&plusmn;0.013 - F1-score: 0.732&plusmn;0.012
test_seqs_rec = dict() solDirTest = os.path.join(data_dir, os.path.join('lp_' + suffix, 'eta05_time.test')) if not os.path.exists(solDirTest): print('Directory for solution files', solDirTest, 'does not exist.') for seqid in sorted(test_seqs.keys()): if not os.path.exists(solDirTest): print('Directory...
tour/ijcai15.ipynb
charmasaur/digbeta
gpl-3.0
The Pearson's test Exercise: See the similarities The above example shows you how two number sequences can be compared with nothing more complicated than by using the dot product. This works as long as the sequences comprise of the same numbers but in a shuffled order. To compare different sequences with the original ...
#The cross-correlation algorithm is another name for the Pearson's test. #Here it is written in code form and utilising the builtin functions: c = [0,1,2] d = [3,4,5] rho = np.average((c-np.average(c))*(d-np.average(d)))/(np.std(c)*np.std(d)) print('rho',np.round(rho,3)) #equally you can write rho = np.dot(c-np.average...
day2_colocalisation/2015 Correlation and Colocalisation practical.ipynb
dwaithe/ONBI_image_analysis
gpl-2.0
Pearson's comparison of microscopy derived images
a = im[0,:,:].reshape(-1) b = im[3,:,:].reshape(-1) #Calculate the pearson's coefficent (rho) for the image channel 0, 3. #You should hopefully obtain a value 0.829 #from tifffile import imread as imreadtiff im = imreadtiff('composite.tif') #The organisation of this file is not simple. It is also a 16-bit image. prin...
day2_colocalisation/2015 Correlation and Colocalisation practical.ipynb
dwaithe/ONBI_image_analysis
gpl-2.0
Maybe remove so not to clash with Mark's. Last challenge Exercise: The above image is not registered. Can you devise a way of registering this image using the Pearson's test, as a measure for the similarity of the image in different positions. hint you will need to move one of the images relative to the other and measu...
np.max(imRGB/256.0) rho_max = 0 #This moves one of your images with respect to the other. for c in range(1,40): for r in range(1,40): #We need to dynamically sample our image. temp = CH0[c:-40+c,r:-40+r].reshape(-1); #The -40 makes sure they are the same size. ref = CH1[:-40,:-40].r...
day2_colocalisation/2015 Correlation and Colocalisation practical.ipynb
dwaithe/ONBI_image_analysis
gpl-2.0
Exercise: Read the documentation of scipy.interpolate.interp1d. Pass a keyword argument to interpolate to specify one of the other kinds of interpolation, and run the code again to see what it looks like.
# Solution goes here
notebooks/chap17.ipynb
AllenDowney/ModSimPy
mit
Exercise: Interpolate the glucose data and generate a plot, similar to the previous one, that shows the data points and the interpolated curve evaluated at the time values in ts.
# Solution goes here
notebooks/chap17.ipynb
AllenDowney/ModSimPy
mit
将 tf.summary 用法迁移到 TF 2.0 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://tensorflow.google.cn/tensorboard/migrate"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">在 TensorFlow.org 上查看 </a></td> <td><a target="_blank" href="https://colab.research.google.com/git...
import tensorflow as tf
site/zh-cn/tensorboard/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
TensorFlow 2.0 包含对 tf.summary API(用于写入摘要数据以在 TensorBoard 中进行可视化)的重大变更。 变更 将 tf.summary API 视为两个子 API 非常实用: 一组用于记录各个摘要(summary.scalar()、summary.histogram()、summary.image()、summary.audio() 和 summary.text())的运算,从您的模型代码内嵌调用。 写入逻辑,用于收集各个摘要并将其写入到特殊格式化的日志文件中(TensorBoard 随后会读取该文件以生成可视化效果)。 在 TF 1.x 中 上述二者必须手动关联在一起,方法是通过 Sess...
writer = tf.summary.create_file_writer("/tmp/mylogs/eager") with writer.as_default(): for step in range(100): # other model code would go here tf.summary.scalar("my_metric", 0.5, step=step) writer.flush() ls /tmp/mylogs/eager
site/zh-cn/tensorboard/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
tf.function 计算图执行的示例用法:
writer = tf.summary.create_file_writer("/tmp/mylogs/tf_function") @tf.function def my_func(step): with writer.as_default(): # other model code would go here tf.summary.scalar("my_metric", 0.5, step=step) for step in tf.range(100, dtype=tf.int64): my_func(step) writer.flush() ls /tmp/mylogs/tf_function
site/zh-cn/tensorboard/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
旧 TF 1.x 计算图执行的示例用法:
g = tf.compat.v1.Graph() with g.as_default(): step = tf.Variable(0, dtype=tf.int64) step_update = step.assign_add(1) writer = tf.summary.create_file_writer("/tmp/mylogs/session") with writer.as_default(): tf.summary.scalar("my_metric", 0.5, step=step) all_summary_ops = tf.compat.v1.summary.all_v2_summary_...
site/zh-cn/tensorboard/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
The figure below shows the input data-matrix, and the current batch batchX_placeholder is in the dashed rectangle. As we will see later, this “batch window” is slided truncated_backprop_length steps to the right at each run, hence the arrow. In our example below batch_size = 3, truncated_backprop_length = 3, and tot...
Image(url= "https://cdn-images-1.medium.com/max/1600/1*n45uYnAfTDrBvG87J-poCA.jpeg") #Now it’s time to build the part of the graph that resembles the actual RNN computation, #first we want to split the batch data into adjacent time-steps. # Unpack columns #Unpacks the given dimension of a rank-R tensor into rank-(R-...
How-to-Use-Tensorflow-for-Time-Series-Live--master/demo_full_notes.ipynb
swirlingsand/deep-learning-foundations
mit
Project 3D electrodes to a 2D snapshot Because we have the 3D location of each electrode, we can use the :func:mne.viz.snapshot_brain_montage function to return a 2D image along with the electrode positions on that image. We use this in conjunction with :func:mne.viz.plot_alignment, which visualizes electrode positions...
fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir, surfaces=['pial'], meg=False) mlab.view(200, 70) xy, im = snapshot_brain_montage(fig, mon) # Convert from a dictionary to array to plot xy_pts = np.vstack([xy[ch] for ch in info['ch_names']]) # Define an arbitrary "activity" ...
0.18/_downloads/66fec418bceb5ce89704fb8b44930330/plot_3d_to_2d.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Custom STIX Content Custom Properties Attempting to create a STIX object with properties not defined by the specification will result in an error. Try creating an Identity object with a custom x_foo property:
from stix2 import Identity Identity(name="John Smith", identity_class="individual", x_foo="bar")
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
To create a STIX object with one or more custom properties, pass them in as a dictionary parameter called custom_properties:
identity = Identity(name="John Smith", identity_class="individual", custom_properties={ "x_foo": "bar" }) print(identity.serialize(pretty=True))
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Alternatively, setting allow_custom to True will allow custom properties without requiring a custom_properties dictionary.
identity2 = Identity(name="John Smith", identity_class="individual", x_foo="bar", allow_custom=True) print(identity2.serialize(pretty=True))
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Likewise, when parsing STIX content with custom properties, pass allow_custom=True to parse():
from stix2 import parse input_string = """{ "type": "identity", "spec_version": "2.1", "id": "identity--311b2d2d-f010-4473-83ec-1edf84858f4c", "created": "2015-12-21T19:59:11Z", "modified": "2015-12-21T19:59:11Z", "name": "John Smith", "identity_class": "individual", "x_foo": "bar" }"""...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
To remove a custom properties, use new_version() and set that property to None.
identity4 = identity3.new_version(x_foo=None) print(identity4.serialize(pretty=True))
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Custom STIX Object Types To create a custom STIX object type, define a class with the @CustomObject decorator. It takes the type name and a list of property tuples, each tuple consisting of the property name and a property instance. Any special validation of the properties can be added by supplying an __init__ function...
from stix2 import CustomObject, properties @CustomObject('x-animal', [ ('species', properties.StringProperty(required=True)), ('animal_class', properties.StringProperty()), ]) class Animal(object): def __init__(self, animal_class=None, **kwargs): if animal_class and animal_class not in ['mammal', '...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Now we can create an instance of our custom Animal type.
animal = Animal(species="lion", animal_class="mammal") print(animal.serialize(pretty=True))
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Trying to create an Animal instance with an animal_class that's not in the list will result in an error:
Animal(species="xenomorph", animal_class="alien")
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Parsing custom object types that you have already defined is simple and no different from parsing any other STIX object.
input_string2 = """{ "type": "x-animal", "id": "x-animal--941f1471-6815-456b-89b8-7051ddf13e4b", "created": "2015-12-21T19:59:11Z", "modified": "2015-12-21T19:59:11Z", "spec_version": "2.1", "species": "shark", "animal_class": "fish" }""" animal2 = parse(input_string2) print(animal2.species)
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
However, parsing custom object types which you have not defined will result in an error:
input_string3 = """{ "type": "x-foobar", "id": "x-foobar--d362beb5-a04e-4e6b-a030-b6935122c3f9", "created": "2015-12-21T19:59:11Z", "modified": "2015-12-21T19:59:11Z", "bar": 1, "baz": "frob" }""" parse(input_string3)
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Custom Cyber Observable Types Similar to custom STIX object types, use a decorator to create custom Cyber Observable types. Just as before, __init__() can hold additional validation, but it is not necessary.
from stix2 import CustomObservable @CustomObservable('x-new-observable', [ ('a_property', properties.StringProperty(required=True)), ('property_2', properties.IntegerProperty()), ]) class NewObservable(): pass new_observable = NewObservable(a_property="something", property_2...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Likewise, after the custom Cyber Observable type has been defined, it can be parsed.
from stix2 import ObservedData input_string4 = """{ "type": "observed-data", "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", "spec_version": "2.1", "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", "created": "2016-04-06T19:58:16.000Z", "modified": "2016-04-06T19:...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
ID-Contributing Properties for Custom Cyber Observables STIX 2.1 Cyber Observables (SCOs) have deterministic IDs, meaning that the ID of a SCO is based on the values of some of its properties. Thus, if multiple cyber observables of the same type have the same values for their ID-contributing properties, then these SCOs...
from stix2 import CustomObservable @CustomObservable('x-new-observable-2', [ ('a_property', properties.StringProperty(required=True)), ('property_2', properties.IntegerProperty()), ], [ 'a_property' ]) class NewObservable2(): pass new_observable_a = NewObservable2(a_property="A property", property_2=2...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
In this example, a_property is the only id-contributing property. Notice that the ID for new_observable_a and new_observable_b is the same since they have the same value for the id-contributing a_property property. Custom Cyber Observable Extensions Finally, custom extensions to existing Cyber Observable types can also...
from stix2 import CustomExtension @CustomExtension('x-new-ext', [ ('property1', properties.StringProperty(required=True)), ('property2', properties.IntegerProperty()), ]) class NewExtension(): pass new_ext = NewExtension(property1="something", property2=10) print(new_ext.serialize(p...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
Once the custom Cyber Observable extension has been defined, it can be parsed.
input_string5 = """{ "type": "observed-data", "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", "spec_version": "2.1", "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", "created": "2016-04-06T19:58:16.000Z", "modified": "2016-04-06T19:58:16.000Z", "first_observed...
docs/guide/custom.ipynb
oasis-open/cti-python-stix2
bsd-3-clause
<table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://tensorflow.google.cn/io/tutorials/genome"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">在 TensorFlow.org 上查看 </a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/b...
try: %tensorflow_version 2.x except Exception: pass !pip install tensorflow-io import tensorflow_io as tfio import tensorflow as tf
site/zh-cn/io/tutorials/genome.ipynb
tensorflow/docs-l10n
apache-2.0
FASTQ 数据 FASTQ 是一种常见的基因组学文件格式,除了基本的质量信息外,还存储序列信息。 首先,让我们下载一个样本 fastq 文件。
# Download some sample data: !curl -OL https://raw.githubusercontent.com/tensorflow/io/master/tests/test_genome/test.fastq
site/zh-cn/io/tutorials/genome.ipynb
tensorflow/docs-l10n
apache-2.0
读取 FASTQ 数据 现在,让我们使用 tfio.genome.read_fastq 读取此文件(请注意,tf.data API 即将发布)。
fastq_data = tfio.genome.read_fastq(filename="test.fastq") print(fastq_data.sequences) print(fastq_data.raw_quality)
site/zh-cn/io/tutorials/genome.ipynb
tensorflow/docs-l10n
apache-2.0
如您所见,返回的 fastq_data 具有 fastq_data.sequences,后者是 fastq 文件中所有序列的字符串张量(大小可以不同);并具有 fastq_data.raw_quality,其中包含与在序列中读取的每个碱基的质量有关的 Phred 编码质量信息。 质量 如有兴趣,您可以使用辅助运算将此质量信息转换为概率。
quality = tfio.genome.phred_sequences_to_probability(fastq_data.raw_quality) print(quality.shape) print(quality.row_lengths().numpy()) print(quality)
site/zh-cn/io/tutorials/genome.ipynb
tensorflow/docs-l10n
apache-2.0
独热编码 您可能还需要使用独热编码器对基因组序列数据(由 A T C G 碱基组成)进行编码。有一项内置运算可以帮助编码。
print(tfio.genome.sequences_to_onehot.__doc__) print(tfio.genome.sequences_to_onehot.__doc__)
site/zh-cn/io/tutorials/genome.ipynb
tensorflow/docs-l10n
apache-2.0
We will often define functions to take optional keyword arguments, like this:
def hello(name, loud=False): if loud: print ('HELLO, %s' % name.upper()) else: print ('Hello, %s!' % name) hello('Bob') loud = True hello('Fred', True)
python-tutorial.ipynb
w4zir/ml17s
mit
KNN Classifier
# read X and y # cols = ['pclass','sex','age','fare'] cols = ['pclass','sex','age'] X = dframe[cols] y = dframe[["survived"]] dframe.head() # Use scikit-learn KNN classifier to predit survival probability from sklearn.neighbors import KNeighborsClassifier neigh = KNeighborsClassifier(n_neighbors=3) neigh.fit(X, y) ...
python-tutorial.ipynb
w4zir/ml17s
mit
Get Movielens-1M data this will download movielens-1m dataset from http://grouplens.org/datasets/movielens/:
data, genres = get_movielens_data(get_genres=True) data.head() data.info() genres.head() %matplotlib inline
polara_intro.ipynb
Evfro/RecSys_ISP2017
mit