markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Hyperparameter Tuning in KNN Manually finding the optimal value of n_neighbors parameter
# Find the optimal value of the n_neighbors parameter models={f'KNN_{i}':KNeighborsClassifier(n_neighbors=i) for i in range(2,31)} # run the model only for fold number 4 ie the 5th fold accuracy,confusion_matrices,classification_report=run(fold=4,df=df_optimal_KNN,models=models,print_details=True) x=[i for i in range...
_____no_output_____
MIT
Diabetes.ipynb
AryanMethil/Diabetes-KNN-vs-Naive-Bayes
Using Grid Search to find optimal values of n_neighbors and p
from sklearn import model_selection from sklearn import metrics def hyperparameter_tune_and_run(df,num_folds,models,target_name,param_grid,evaluation_metric,print_details=False): X=df.drop(labels=[target_name,'kfolds'],axis=1).values y=df[target_name] model_name,model_constructor=list(models.items())[0] mode...
Fitting 5 folds for each of 58 candidates, totalling 290 fits [CV] n_neighbors=2, p=2 .............................................. [CV] .................. n_neighbors=2, p=2, score=0.770, total= 0.0s [CV] n_neighbors=2, p=2 .............................................. [CV] .................. n_neighbors=2, p=2, s...
MIT
Diabetes.ipynb
AryanMethil/Diabetes-KNN-vs-Naive-Bayes
Comparison between KNN and NB1. Dataset when KNN was considered for feature selection2. Dataset when NB was considered for feature selection
# Compare between KNN and Naive Bayes models={ 'KNN': KNeighborsClassifier(n_neighbors=12,p=3), 'Gaussian Naive Bayes': GaussianNB(), } # accuracies => list of 5 lists. Each list will contain 3 values ie KNN accuracy, Gaussian Naive Bayes accuracies,confusion_matrices,classification_reports=[]...
_____no_output_____
MIT
Diabetes.ipynb
AryanMethil/Diabetes-KNN-vs-Naive-Bayes
Getting info on Priming experiment dataset that's needed for modeling Info:* __Which gradient(s) to simulate?__* For each gradient to simulate: * Infer total richness of starting community * Get distribution of total OTU abundances per fraction * Number of sequences per sample * Infer total abundance of each ta...
baseDir = '/home/nick/notebook/SIPSim/dev/priming_exp/' workDir = os.path.join(baseDir, 'exp_info') otuTableFile = '/var/seq_data/priming_exp/data/otu_table.txt' otuTableSumFile = '/var/seq_data/priming_exp/data/otu_table_summary.txt' metaDataFile = '/var/seq_data/priming_exp/data/allsample_metadata_nomock.txt' #otu...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Init
import glob %load_ext rpy2.ipython %%R library(ggplot2) library(dplyr) library(tidyr) library(gridExtra) library(fitdistrplus) if not os.path.isdir(workDir): os.makedirs(workDir)
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Loading OTU table (filter to just bulk samples)
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(ends_with('.NA')) tbl %>% ncol %>% print tbl[1:4,1:4] %%R tbl.h = tbl %>% gather('sample', 'count', 1:ncol(tbl)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'), sep='\\.', remove=F) tbl.h %>...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Which gradient(s) to simulate?
%%R -w 900 -h 400 tbl.h.s = tbl.h %>% group_by(sample) %>% summarize(total_count = sum(count)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'), sep='\\.', remove=F) ggplot(tbl.h.s, aes(day, total_count, color=rep %>% as.character)) + geom_point() + facet_grid(isotope ~ treatme...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
NotesSamples to simulate* Isotope: * 12C vs 13C* Treatment: * 700* Days: * 14 * 28 * 45
%%R # bulk soil samples for gradients to simulate samples.to.use = c( "X12C.700.14.05.NA", "X12C.700.28.03.NA", "X12C.700.45.01.NA", "X13C.700.14.08.NA", "X13C.700.28.06.NA", "X13C.700.45.01.NA" )
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Total richness of starting (bulk-soil) communityMethod:* Total number of OTUs in OTU table (i.e., gamma richness)* Just looking at bulk soil samples Loading just bulk soil
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(ends_with('.NA')) tbl$OTUId = rownames(tbl) tbl %>% ncol %>% print tbl[1:4,1:4] %%R tbl.h = tbl %>% gather('sample', 'count', 1:(ncol(tbl)-1)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'),...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Number of taxa in all fractions corresponding to each bulk soil sample* Trying to see the difference between richness of bulk vs gradients (veil line effect)
%%R -i otuTableFile # loading OTU table tbl = read.delim(otuTableFile, sep='\t') %>% select(-ends_with('.NA')) tbl.h = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'), sep='\\.', remove=F) tbl.h %>% head %%R # basename of fractions samp...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Distribution of total sequences per fraction * Number of sequences per sample* Using all samples to assess this one* Just fraction samples__Method:__* Total number of sequences (total abundance) per sample Loading OTU table
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(-ends_with('.NA')) tbl %>% ncol %>% print tbl[1:4,1:4] %%R tbl.h = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'), sep='\\.', remove=F) tbl.h %...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Distribution fitting
%%R -w 700 -h 350 plotdist(tbl.h.s$total_seqs) %%R -w 450 -h 400 descdist(tbl.h.s$total_seqs, boot=1000) %%R f.n = fitdist(tbl.h.s$total_seqs, 'norm') f.ln = fitdist(tbl.h.s$total_seqs, 'lnorm') f.ll = fitdist(tbl.h.s$total_seqs, 'logis') #f.c = fitdist(tbl.s$count, 'cauchy') f.list = list(f.n, f.ln, f.ll) plot.legend...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Notes:* best fit: * lognormal * mean = 10.113 * sd = 1.192 Does sample size correlate to buoyant density? Loading OTU table
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(-ends_with('.NA')) %>% select(-starts_with('X0MC')) tbl = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% mutate(sample = gsub('^X', '', sample)) tbl %>% head %%R # summarize tbl.s = tbl %>% group_by(sa...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Loading metadata
%%R -i metaDataFile tbl.meta = read.delim(metaDataFile, sep='\t') tbl.meta %>% head(n=3)
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Determining association
%%R -w 700 tbl.j = inner_join(tbl.s, tbl.meta, c('sample' = 'Sample')) ggplot(tbl.j, aes(Density, total_count, color=rep)) + geom_point() + facet_grid(Treatment ~ Day) %%R -w 600 -h 350 ggplot(tbl.j, aes(Density, total_count)) + geom_point(aes(color=Treatment)) + geom_smooth(method='lm') + labs(...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Number of taxa along the gradient
%%R tbl.s = tbl %>% filter(count > 0) %>% group_by(sample) %>% summarize(n_taxa = sum(count > 0)) tbl.j = inner_join(tbl.s, tbl.meta, c('sample' = 'Sample')) tbl.j %>% head(n=3) %%R -w 900 -h 600 ggplot(tbl.j, aes(Density, n_taxa, fill=rep, color=rep)) + #geom_area(stat='identity', alpha=0.5, posit...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Notes:* Many taxa out to the tails of the gradient.* It seems that the DNA fragments were quite diffuse in the gradients. Total abundance of each target taxon: bulk soil approach* Getting relative abundances from bulk soil samples * This has the caveat of likely undersampling richness vs using all gradient fraction ...
%%R -i otuTableFile # loading OTU table tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(matches('OTUId'), ends_with('.NA')) tbl %>% ncol %>% print tbl[1:4,1:4] %%R # long table format w/ selecting samples of interest tbl.h = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% separa...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
For each sample, writing a table of OTU_ID and count
%%R -i workDir setwd(workDir) samps = tbl.h$sample %>% unique %>% as.vector for(samp in samps){ outFile = paste(c(samp, 'OTU.txt'), collapse='_') tbl.p = tbl.h %>% filter(sample == samp, count > 0) write.table(tbl.p, outFile, sep='\t', quote=F, row.names=F) message('Table writt...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Making directories for simulations
p = os.path.join(workDir, '*_OTU.txt') files = glob.glob(p) baseDir = os.path.split(workDir)[0] newDirs = [os.path.split(x)[1].rstrip('.NA_OTU.txt') for x in files] newDirs = [os.path.join(baseDir, x) for x in newDirs] for newDir,f in zip(newDirs, files): if not os.path.isdir(newDir): print 'Making new di...
Directory exists: /home/nick/notebook/SIPSim/dev/priming_exp/X13C.700.28.06 Directory exists: /home/nick/notebook/SIPSim/dev/priming_exp/X12C.700.28.03 Directory exists: /home/nick/notebook/SIPSim/dev/priming_exp/X13C.700.14.08 Directory exists: /home/nick/notebook/SIPSim/dev/priming_exp/X13C.700.45.01 Directory exists...
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Rank-abundance distribution for each sample
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(matches('OTUId'), ends_with('.NA')) tbl %>% ncol %>% print tbl[1:4,1:4] %%R # long table format w/ selecting samples of interest tbl.h = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% separate(sample, c('isoto...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Taxon abundance range for each sample-fraction
%%R -i otuTableFile tbl = read.delim(otuTableFile, sep='\t') # filter tbl = tbl %>% select(-ends_with('.NA')) %>% select(-starts_with('X0MC')) tbl = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% mutate(sample = gsub('^X', '', sample)) tbl %>% head %%R tbl.ar = tbl %>% #mutate(fraction = gsu...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Total abundance of each target taxon: all fraction samples approach* Getting relative abundances from all fraction samples for the gradient * I will need to calculate (mean|max?) relative abundances for each taxon and then re-scale so that cumsum = 1
%%R -i otuTableFile # loading OTU table tbl = read.delim(otuTableFile, sep='\t') %>% select(-ends_with('.NA')) tbl.h = tbl %>% gather('sample', 'count', 2:ncol(tbl)) %>% separate(sample, c('isotope','treatment','day','rep','fraction'), sep='\\.', remove=F) tbl.h %>% head %%R # basename of fractions samp...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
For each sample, writing a table of OTU_ID and count
%%R -i workDir setwd(workDir) # each sample is a file samps = otu.rel.abund.l$sample %>% unique %>% as.vector for(samp in samps){ outFile = paste(c(samp, 'frac_OTU.txt'), collapse='_') tbl.p = otu.rel.abund %>% filter(sample == samp, mean_perc_abund > 0) write.table(tbl.p, outFile, se...
_____no_output_____
MIT
ipynb/bac_genome/priming_exp/priming_exp_info.ipynb
arischwartz/test
Here Z ∼ binomial(1, 0.5) is the protected attribute. Features related to the protected attribute are sampled from X ∼ N(µ, I) with µ = 1 when Z = 0 and µ = 2 when Z = 1. Other features not related to the protected attribute Z are generated with µ = 0. First 4 features are correlated with z. The first 10 features are c...
z = np.zeros(1000) for j in range(1000): z[j] = np.random.binomial(1,0.5) x_correlated = np.zeros((1000,4)) x_uncorrelated = np.zeros((1000,16)) for j in range(16): for i in range (1000): if j < 4: x_correlated[i][j] = np.random.normal((z[i]*2 + 10), 1, 1) x_uncorrelated[i][j] = np.r...
809 191 104 87 498 502
MIT
benchmark/synthetic.ipynb
DebolinaHalder/599
![Annif_logo.png](attachment:Annif_logo.png) Annif tutorial with Jupyter notebook [Annif](https://annif.org/) is an open source subject indexing tool for new documents and aims to improve the discoverability of vast amount of electronic documents. In order to accomplish automatic subject indexing task, annif uses ML/...
import requests import json from pandas import json_normalize headers = {'Accept': 'application/json'} base_url='https://annif.rahtiapp.fi/v1/projects' # Annif webserver hosted by CSC #base_url='https://api.annif.org/v1/projects' # Annif webserver by NatLibFi response = requests.get(base_url, headers=headers) d=resp...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
Perform subject indexing with AnnifThere are mainly six types of projects in a test case example of [Annif](https://annif.rahtiapp.fi) hosted at CSC and it runson Rahti container cloud. Let's see how to get subject indexing with each of these projects here 1. Perform subject indexing for your own text using YSO TFIDF ...
projectid='yso-tfidf-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = {'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = requests.pos...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
2. Perform subject indexing with YSO ensemble project (projectid:'yso-ensemble-en') This can be accomplished using swagger API POST call> **Note**: curl command - curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'text=frequently occurring or otherwise sal...
projectid='yso-ensemble-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = {'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = requests....
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
3. Perform subject indexing with for your own text using project 'yso-maui-en' This can be accomplished using swagger API POST call> **curl command**:curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'text=frequently occurring or otherwise salient terms in ...
projectid='yso-maui-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = { 'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = requests.post...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
4. Perform subject indexing for your own text using project 'yso-omikuji-parabel-en' This can be accomplished using swagger API POST call>**curl command**: curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'text=frequently occurring or otherwise salient ter...
projectid='yso-omikuji-parabel-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = {'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = req...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
5. Perform subject indexing for your own text using project 'yso-omikuji-bonsai-en' This can be accomplished using swagger API POST call>**curl command**:curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'text=frequently occurring or otherwise salient terms...
projectid='yso-omikuji-bonsai-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = {'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = req...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
6. Perform subject indexing for your own text using project 'yso-nn-ensemble-en' This can be accomplished using swagger API POST call>**curl command**: curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'text=frequently occurring or otherwise salient terms ...
projectid='yso-nn-ensemble-en' text='frequently occurring or otherwise salient terms in the document are matched with terms in the vocabulary' url= base_url+ '/' + projectid +'/suggest' data = {'text': text} headers = { 'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'} response = reques...
_____no_output_____
Apache-2.0
annif.ipynb
CSCfi/annif-utils
Several exercises: Jupyter Notebook, iPython and ipyparallel, and HPC MPICHThe content of this notebook is borrowed extensively from Daan Van Hauwermeiren, from his tutotial of ipyparallel, stored on github https://github.com/DaanVanHauwermeiren/ipyparallel-tutorial/blob/master/02-ipyparallel-tutorial-direct-interface...
# import the IPython ipyparallel module and create a Client instance # In this demonstration, an MPI-oriented client is created, referenced by the 'mpi' profile # There are 4 mpi engines that have been configured and running on 4 separate HPC compute nodes import ipyparallel as ipp rc = ipp.Client(profile='mpi') # Sho...
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Python’s builtin map() functions allows a function to be applied to a sequence element-by-element. This type of code is typically trivial to parallelize. In fact, since IPython’s interface is all about functions anyway, you can just use the builtin map() with a RemoteFunction, or a vobject’s map() method.do an arbitrar...
%%time serial_result = list(map(lambda x:x**2**2, range(30)))
CPU times: user 18 µs, sys: 3 µs, total: 21 µs Wall time: 25.5 µs
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Now do the same computation using the MPI compute nodes HPC cluster, ... and show how long it takes
%%time parallel_result = vobject.map_sync(lambda x:x**2**2, range(30)) serial_result==parallel_result
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Remote function decoratorsRemote functions are just like normal functions, but when they are called, they execute on one or more engines, rather than locally. Here we will demonstrate the @parallel function decorator, which creates parallel functions that break up an element-wise operations and distribute them to rem...
# First, we'll enable blocking, which will be explored more throughly later. # In short, blocking will ensure that each task won't proceed until all the remotely distributed work is complete. @vobject.remote(block=True) # Define a function called "getpid" that ... well, you can see the description def getpid(): ...
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
We'll use numpy to create some complicated (random) arrays, then use those arrays for some big computations that should benefit by some distributed HPC compute resources.
import numpy as np A = np.random.random((64,48)) # Create a little function that can do the calculations as a distribution among multiple, parallel compute nodes @vobject.parallel(block=True) def pmul(A,B): return A*B
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
We want to be able to compare the amount of time it takes to do the calulation locally on the HPC headand the amount of time it takes to do the calculation among the distributed compute nodesFirst, do the calculation locally, then do it remotely
%%time C_local = A*A %%time C_remote = pmul(A,A) (C_local == C_remote).all()
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Create a simple, new function that can be called locally but that will execute remotely, in parallel.It's just a simple instruction that will "echo" the output of what is run on the remote worker
@vobject.parallel(block=True) def echo(x): return str(x) echo(range(5)) echo.map(range(5))
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Blocking executionIn blocking mode, the iPython ipyparallel object (called vobject in these examples; defined at the beginning of this notebook) submits the command to the controller, which places the command in the engines’ queues for execution. The apply() call then blocks until the engines are done executing the co...
# Show function names (on the remote worker) that beging with the string "apply" [x for x in dir(vobject) if x.startswith('apply')] vobject.block = True vobject['a'] = 5 vobject['b'] = 10 vobject.apply(lambda x: a+b+x, 27) vobject.block = False vobject.apply_sync(lambda x: a+b+x, 27)
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Python commands can be executed as strings on specific engines by using a vobject’s execute method:
rc[::2].execute('c=a+b') rc[1::2].execute('c=a-b') vobject['c'] # shorthand for vobject.pull('c', block=True)
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Non-blocking executionIn non-blocking mode, apply() submits the command to be executed and then returns a AsyncResult object immediately. The AsyncResult object gives you a way of getting a result at a later time through its get() method.More info on the AsyncResult object: http://ipyparallel.readthedocs.io/en/6.0.2/a...
# define our function def wait(t): import time tic = time.time() time.sleep(t) return time.time()-tic # In non-blocking mode ar = vobject.apply_async(wait, 3) # Now block for the result, and the output won't disply until after 3 seconds ar.get() # Again in non-blocking mode, with longer wait (10 seconds...
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Often, it is desirable to wait until a set of AsyncResult objects are done. For this, there is the method wait(). This method takes a tuple of AsyncResult objects (or msg_ids or indices to the client’s History), and blocks until all of the associated results are ready.In proper Jupyter Notebook fashion, the step progre...
vobject.block=False # A trivial list of AsyncResults objects pr_list = [vobject.apply_async(wait, 3) for i in range(10)] # Wait until all of the clients have completed the instruction vobject.wait(pr_list) # Then, their results are ready using get() or the `.r` attribute pr_list[0].get()
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
Scatter and gatherSometimes it is useful to partition a sequence and push the partitions to different engines. In MPI language, this is know as scatter/gather and we follow that terminology. However, it is important to remember that in IPython’s Client class, scatter() is from the interactive IPython session to the en...
vobject.scatter('a',range(16)) vobject['a'] vobject.gather('a')
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
parallel list comprehensionsIn many cases list comprehensions are nicer than using the map function. While we don’t have fully parallel list comprehensions, it is simple to get the basic effect using scatter() and gather():The %px magic executes a single Python command on the engines specified by the targets attribute...
vobject.scatter('x', range(64)) #Parallel execution on engines: [0, 1, 2, 3] %px y = [i**10 for i in x] y = vobject.gather('y') print(y.get()[-10:])
[210832519264920576, 253295162119140625, 303305489096114176, 362033331456891249, 430804206899405824, 511116753300641401, 604661760000000000, 713342911662882601, 839299365868340224, 984930291881790849]
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
example: monte carlo approximation of piA simple toy problem to get a handle on multiple engines is a Monte Carlo approximation of π.Let’s say we have a dartboard with a round target inscribed on a square board. If you threw darts randomly, and they land evenly distributed on the square board, how many darts would you...
from random import random from math import pi vobject['random'] = random def mcpi(nsamples): s = 0 for i in range(nsamples): x = random() y = random() if x*x + y*y <= 1: s+=1 return 4.*s/nsamples def multi_mcpi(view, nsamples): p = len(view.targets) if nsampl...
_____no_output_____
CC0-1.0
mpi.ipynb
craiggardner/jupyter_notebooks
def what_is_installed(): import pycaret from pycaret import show_versions show_versions() try: what_is_installed() except: !pip install pycaret-ts-alpha what_is_installed() import numpy as np import pandas as pd from pycaret.datasets import get_data from pycaret.time_series import TSForecasting...
_____no_output_____
MIT
time_series/pycaret/pycaret_ts_ccf.ipynb
ngupta23/medium_articles
**Not much to go by in terms of forecasting y just by itself (without exogenous variables)**
exp.plot_model(plot="ccf")
_____no_output_____
MIT
time_series/pycaret/pycaret_ts_ccf.ipynb
ngupta23/medium_articles
Q-Learning> Off-Policy Temporal Difference Learning.
import gym import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output from time import sleep env_name = "Taxi-v3" epsilon = 1 decay_rate = 0.001 min_epsilon = 0.01 max_episodes = 2500 print_interval = 100 test_episodes = 3 lr = 0.4 gamma = 0.99 env = gym.make(env_name) env = gym.wrapper...
_____no_output_____
MIT
Q_Learning/Taxi_env.ipynb
alirezakazemipour/Q-Table-Numpy
Pseudocode>
running_reward = [] for episode in range(1, 1 + max_episodes): state = env.reset() done = False episode_reward = 0 while not done: action = choose_action(state) next_state, reward, done, _ = env.step(action) update_table(state, action, reward, done, next_state) ...
Ep:3| Ep_reward:4|
MIT
Q_Learning/Taxi_env.ipynb
alirezakazemipour/Q-Table-Numpy
Stationary freatic flow between two water courses above a semi-pervious layer (Wesseling) Constant precipitation N on a strip of land between two parallel water courses with water level hs causes a rise h(x) of the groundwater level that induces in a groundwater flow towards the water courses. The phreatic groundwate...
import numpy as np %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') def hx(x,L,hs,p,H,c,T): """Return phreatic groundwater level h(x) between two water courses Parameters: x : numpy array Distance from centre of the water course (m) L : float D...
320.0 3.7037037037037033 2800.0000000000005 32.40740740740741 -308.63433088123435 -3.5721566074216935 -2628.53571800518 -30.422867106541435 181.26361767539473 2.097958537909661 -2138.637769448551 -24.752751961210077
MIT
Watercourse/Stationary freatic flow between two water courses above a semi-pervious layer (Wesseling).ipynb
tdmeij/GWF
Text Classification with PySpark - Multiclass Text ClassificationTask- Predict the subject category given a course title or text
import pyspark from pyspark import SparkContext sc = SparkContext(master='local[2]') # lunch UI sc # create spark seassion from pyspark.sql import SparkSession spark = SparkSession.builder.appName("Text Classifier").getOrCreate() # read the dataset and load df = spark.read.csv('udemy.csv',header=True, inferSchema=True...
+--------------------+----------------+ | course_title| subject| +--------------------+----------------+ |Ultimate Investme...|Business Finance| |Complete GST Cour...|Business Finance| |Financial Modelin...|Business Finance| |Beginner to Pro -...|Business Finance| |How To Maximize Y...|Business Finance| ...
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
Feature Extractionbuild features + count vectorizer+ tfIDF+ wordEmbeddings+ hashingTF+ etc...We have 2 things in Pipeline stages- Transformer- Estimator**Transformer** (Data to Data)Function that takes data and fit, transform them into augmented data or featuresi.e Extractors, Vectorizer, Scalers (Tokenizer, StopwordR...
from pyspark.ml.feature import Tokenizer, StopWordsRemover, CountVectorizer, IDF, StringIndexer # dir(pyspark.ml.feature) # Stages for the pipeline tokenizer = Tokenizer(inputCol='course_title', outputCol='mytokens') stopwordRemover = StopWordsRemover(inputCol='mytokens',outputCol='filtered_tokens') vectorizer = CountV...
_____no_output_____
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
Building the pipeline
from pyspark.ml import Pipeline pipeline = Pipeline( stages=[tokenizer, stopwordRemover, vectorizer, idf, lr] ) pipeline.stages # model building lr_model = pipeline.fit(train_df) lr_model # get predicction on test data predictions = lr_model.transform(test_df) # predictions.show() predictions.columns predictions.se...
+--------------------+--------------------+-------------------+-----+----------+ | rawPrediction| probability| subject|label|prediction| +--------------------+--------------------+-------------------+-----+----------+ |[8.30964874634511...|[0.87877993991729...|Musical Instruments| 2.0| 0...
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
model evaluation+ Accuracy+ Precision+ F1Score+ etc
from pyspark.ml.evaluation import MulticlassClassificationEvaluator evaluator = MulticlassClassificationEvaluator(predictionCol='prediction',labelCol='label') accuracy = evaluator.evaluate(predictions) accuracy*100 """ Method 2: precision, f1score classification report """ from pyspark.mllib.evaluation import Multicla...
Accuracy 0.9182509505703422 precision 0.9544159544159544 f1Score 0.9178082191780822 recall 0.8839050131926122
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
Confusion matrix- convert to pandas- sklearn
y_true = predictions.select('label') y_true = y_true.toPandas() y_predict = predictions.select('prediction') y_predict = y_predict.toPandas() from sklearn.metrics import confusion_matrix, classification_report cm = confusion_matrix(y_true, y_predict) cm
_____no_output_____
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
making prediction on one sample+ sample as df+ apply pipeline
from pyspark.sql.types import StringType exl = spark.createDataFrame([ ("Building Machine Learning Apps with Python and PySpark", StringType()) ], #column name ['course_title'] ) exl.show() # show fill exl.show(truncate=False) # making prediction prediction_ex1 = lr_model.transform(exl) prediction_ex1.show(trunca...
+--------------------+--------------------+--------------------+----------+ | course_title| rawPrediction| probability|prediction| +--------------------+--------------------+--------------------+----------+ |Building Machine ...|[14.7174498131555...|[0.99999814636182...| 0.0| +---------------...
Apache-2.0
getStarted/TextClassification/textClassification.ipynb
iamhimanshu0/Spark
______Copyright by Pierian Data Inc.For more information, visit us at www.pieriandata.com Text Methods A normal Python string has a variety of method calls available:
mystring = 'hello' mystring.capitalize() mystring.isdigit() help(str)
Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given e...
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Pandas and TextPandas can do a lot more than what we show here. Full online documentation on things like advanced string indexing and regular expressions with pandas can be found here: https://pandas.pydata.org/docs/user_guide/text.html Text Methods on Pandas String Column
import pandas as pd names = pd.Series(['andrew','bobo','claire','david','4']) names names.str.capitalize() names.str.isdigit()
_____no_output_____
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Splitting , Grabbing, and Expanding
tech_finance = ['GOOG,APPL,AMZN','JPM,BAC,GS'] len(tech_finance) tickers = pd.Series(tech_finance) tickers tickers.str.split(',') tickers.str.split(',').str[0] tickers.str.split(',',expand=True)
_____no_output_____
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Cleaning or Editing Strings
messy_names = pd.Series(["andrew ","bo;bo"," claire "]) # Notice the "mis-alignment" on the right hand side due to spacing in "andrew " and " claire " messy_names messy_names.str.replace(";","") messy_names.str.strip() messy_names.str.replace(";","").str.strip() messy_names.str.replace(";","").str.strip().str.cap...
_____no_output_____
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Alternative with Custom apply() call
def cleanup(name): name = name.replace(";","") name = name.strip() name = name.capitalize() return name messy_names messy_names.apply(cleanup)
_____no_output_____
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Which one is more efficient?
import timeit # code snippet to be executed only once setup = ''' import pandas as pd import numpy as np messy_names = pd.Series(["andrew ","bo;bo"," claire "]) def cleanup(name): name = name.replace(";","") name = name.strip() name = name.capitalize() return name ''' # code snippet whose exe...
_____no_output_____
Apache-2.0
07-Text-Methods.ipynb
srijikabanerjee/demo2
Texas updates their data daily at noon CDT
from selenium import webdriver import time import pandas as pd import pendulum import re import yaml from selenium.webdriver.chrome.options import Options chrome_options = Options() #chrome_options.add_argument("--disable-extensions") #chrome_options.add_argument("--disable-gpu") #chrome_options.add_argument("--no-sand...
_____no_output_____
MIT
TX by county.ipynb
kirbs-/covid-19-dataset
Convert Dataset FormatsThis recipe demonstrates how to use FiftyOne to convert datasets on disk between common formats. Setup If you haven't already, install FiftyOne:
!pip install fiftyone import fiftyone as fo
_____no_output_____
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
If the above import fails due to a `cv2` error, it is an issue with OpenCV in Colab environments. [Follow these instructions to resolve it.](https://github.com/voxel51/fiftyone/issues/1494issuecomment-1003148448). This notebook contains bash commands. To run it as a notebook, you must install the [Jupyter bash kernel]...
pip install bash_kernel python -m bash_kernel.install
_____no_output_____
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
In this recipe we'll use the [FiftyOne Dataset Zoo](https://voxel51.com/docs/fiftyone/user_guide/dataset_creation/zoo_datasets.html) to download some open source datasets to work with.Specifically, we'll need [TensorFlow](https://www.tensorflow.org/) and [TensorFlow Datasets](https://www.tensorflow.org/datasets) instal...
pip install tensorflow tensorflow-datasets
_____no_output_____
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Download datasets Download the test split of the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html) from the [FiftyOne Dataset Zoo](https://voxel51.com/docs/fiftyone/user_guide/dataset_creation/zoo_datasets.html) using the command below:
# Download the test split of CIFAR-10 fiftyone zoo datasets download cifar10 --split test
Downloading split 'test' to '~/fiftyone/cifar10/test' Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ~/fiftyone/cifar10/tmp-download/cifar-10-python.tar.gz 170500096it [00:04, 35887670.65it/s] Extracting ~/fiftyone/cifar10/tmp-download/cifar-10-python....
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Download the validation split of the [KITTI dataset]( http://www.cvlibs.net/datasets/kitti) from the [FiftyOne Dataset Zoo](https://voxel51.com/docs/fiftyone/user_guide/dataset_creation/zoo_datasets.html) using the command below:
# Download the validation split of KITTI fiftyone zoo datasets download kitti --split validation
Split 'validation' already downloaded
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
The fiftyone convert command The [FiftyOne CLI](https://voxel51.com/docs/fiftyone/cli/index.html) provides a number of utilities for importing and exporting datasets in a variety of common (or custom) formats.Specifically, the `fiftyone convert` command provides a convenient way to convert datasets on disk between for...
fiftyone convert -h
usage: fiftyone convert [-h] [--input-dir INPUT_DIR] [--input-type INPUT_TYPE] [--output-dir OUTPUT_DIR] [--output-type OUTPUT_TYPE] Convert datasets on disk between supported formats. Examples:: # Convert an image classification directory tree to TFRecords format fiftyone...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Convert CIFAR-10 dataset When you downloaded the test split of the CIFAR-10 dataset above, it was written to disk as a dataset in [fiftyone.types.FiftyOneImageClassificationDataset](https://voxel51.com/docs/fiftyone/user_guide/dataset_creation/datasets.htmlfiftyoneimageclassificationdataset) format.You can verify this...
fiftyone zoo datasets info cifar10
***** Dataset description ***** The CIFAR-10 dataset consists of 60000 32 x 32 color images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. Dataset size: 132.40 MiB Source: https://www.cs.toronto.edu/~kriz/cifar.html ***** Supporte...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
The snippet below uses `fiftyone convert` to convert the test split of the CIFAR-10 dataset to [fiftyone.types.ImageClassificationDirectoryTree](https://voxel51.com/docs/fiftyone/user_guide/export_datasets.htmlimageclassificationdirectorytree) format, which stores classification datasets on disk in a directory tree str...
INPUT_DIR=$(fiftyone zoo datasets find cifar10 --split test) OUTPUT_DIR=/tmp/fiftyone/cifar10-dir-tree fiftyone convert \ --input-dir ${INPUT_DIR} --input-type fiftyone.types.FiftyOneImageClassificationDataset \ --output-dir ${OUTPUT_DIR} --output-type fiftyone.types.ImageClassificationDirectoryTree
Loading dataset from '~/fiftyone/cifar10/test' Input format 'fiftyone.types.dataset_types.FiftyOneImageClassificationDataset' 100% |███| 10000/10000 [4.2s elapsed, 0s remaining, 2.4K samples/s] Import complete Exporting dataset to '/tmp/fiftyone/cifar10-dir-tree' Export format 'fiftyone.types.dataset_types.Image...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Let's verify that the conversion happened as expected:
ls -lah /tmp/fiftyone/cifar10-dir-tree/ ls -lah /tmp/fiftyone/cifar10-dir-tree/airplane/ | head
total 8000 drwxr-xr-x 1002 voxel51 wheel 31K Jul 14 11:08 . drwxr-xr-x 12 voxel51 wheel 384B Jul 14 11:08 .. -rw-r--r-- 1 voxel51 wheel 1.2K Jul 14 11:23 000004.jpg -rw-r--r-- 1 voxel51 wheel 1.1K Jul 14 11:23 000011.jpg -rw-r--r-- 1 voxel51 wheel 1.1K Jul 14 11:23 000022.jpg -rw-r--r-- ...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Now let's convert the classification directory tree to [TFRecords](https://voxel51.com/docs/fiftyone/user_guide/export_datasets.htmltfimageclassificationdataset) format!
INPUT_DIR=/tmp/fiftyone/cifar10-dir-tree OUTPUT_DIR=/tmp/fiftyone/cifar10-tfrecords fiftyone convert \ --input-dir ${INPUT_DIR} --input-type fiftyone.types.ImageClassificationDirectoryTree \ --output-dir ${OUTPUT_DIR} --output-type fiftyone.types.TFImageClassificationDataset
Loading dataset from '/tmp/fiftyone/cifar10-dir-tree' Input format 'fiftyone.types.dataset_types.ImageClassificationDirectoryTree' 100% |███| 10000/10000 [4.0s elapsed, 0s remaining, 2.5K samples/s] Import complete Exporting dataset to '/tmp/fiftyone/cifar10-tfrecords' Export format 'fiftyone.types.dataset_types...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Let's verify that the conversion happened as expected:
ls -lah /tmp/fiftyone/cifar10-tfrecords
total 29696 drwxr-xr-x 3 voxel51 wheel 96B Jul 14 11:24 . drwxr-xr-x 4 voxel51 wheel 128B Jul 14 11:24 .. -rw-r--r-- 1 voxel51 wheel 14M Jul 14 11:24 tf.records
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Convert KITTI dataset When you downloaded the validation split of the KITTI dataset above, it was written to disk as a dataset in [fiftyone.types.FiftyOneImageDetectionDataset](https://voxel51.com/docs/fiftyone/user_guide/dataset_creation/datasets.htmlfiftyoneimagedetectiondataset) format.You can verify this by printi...
fiftyone zoo datasets info kitti
***** Dataset description ***** KITTI contains a suite of vision tasks built using an autonomous driving platform. The full benchmark contains many tasks such as stereo, optical flow, visual odometry, etc. This dataset contains the object detection dataset, including the monocular images and bounding b...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
The snippet below uses `fiftyone convert` to convert the test split of the CIFAR-10 dataset to [fiftyone.types.COCODetectionDataset](https://voxel51.com/docs/fiftyone/user_guide/export_datasets.htmlcocodetectiondataset) format, which writes the dataset to disk with annotations in [COCO format](https://cocodataset.org/f...
INPUT_DIR=$(fiftyone zoo datasets find kitti --split validation) OUTPUT_DIR=/tmp/fiftyone/kitti-coco fiftyone convert \ --input-dir ${INPUT_DIR} --input-type fiftyone.types.FiftyOneImageDetectionDataset \ --output-dir ${OUTPUT_DIR} --output-type fiftyone.types.COCODetectionDataset
Loading dataset from '~/fiftyone/kitti/validation' Input format 'fiftyone.types.dataset_types.FiftyOneImageDetectionDataset' 100% |███████| 423/423 [1.2s elapsed, 0s remaining, 351.0 samples/s] Import complete Exporting dataset to '/tmp/fiftyone/kitti-coco' Export format 'fiftyone.types.dataset_types.COCODete...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Let's verify that the conversion happened as expected:
ls -lah /tmp/fiftyone/kitti-coco/ ls -lah /tmp/fiftyone/kitti-coco/data | head cat /tmp/fiftyone/kitti-coco/labels.json | python -m json.tool 2> /dev/null | head -20 echo "..." cat /tmp/fiftyone/kitti-coco/labels.json | python -m json.tool 2> /dev/null | tail -20
{ "info": { "year": "", "version": "", "description": "Exported from FiftyOne", "contributor": "", "url": "https://voxel51.com/fiftyone", "date_created": "2020-07-14T11:24:40" }, "licenses": [], "categories": [ { "id": 0, "n...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Now let's convert from COCO format to [CVAT Image format](https://voxel51.com/docs/fiftyone/user_guide/export_datasets.htmlcvatimageformat) format!
INPUT_DIR=/tmp/fiftyone/kitti-coco OUTPUT_DIR=/tmp/fiftyone/kitti-cvat fiftyone convert \ --input-dir ${INPUT_DIR} --input-type fiftyone.types.COCODetectionDataset \ --output-dir ${OUTPUT_DIR} --output-type fiftyone.types.CVATImageDataset
Loading dataset from '/tmp/fiftyone/kitti-coco' Input format 'fiftyone.types.dataset_types.COCODetectionDataset' 100% |███████| 423/423 [2.0s elapsed, 0s remaining, 206.4 samples/s] Import complete Exporting dataset to '/tmp/fiftyone/kitti-cvat' Export format 'fiftyone.types.dataset_types.CVATImageDataset' 100%...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Let's verify that the conversion happened as expected:
ls -lah /tmp/fiftyone/kitti-cvat cat /tmp/fiftyone/kitti-cvat/labels.xml | head -20 echo "..." cat /tmp/fiftyone/kitti-cvat/labels.xml | tail -20
<?xml version="1.0" encoding="utf-8"?> <annotations> <version>1.1</version> <meta> <task> <size>423</size> <mode>annotation</mode> <labels> <label> <name>Car</name> <attributes> </attributes> ...
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
CleanupYou can cleanup the files generated by this recipe by running the command below:
rm -rf /tmp/fiftyone
_____no_output_____
Apache-2.0
docs/source/recipes/convert_datasets.ipynb
pixta-dev/fiftyone
Session 1 Homework Solution=========================This is the homework for the first session of the MolSSI Python Scripting Level 2 Workshop.This homework is intended to give you practice with the material covered in the first session. Goals: - Utilize pandas to read in and work with the data in a csv file. - Utilize...
# Import necessary packages for the homework: import os import pandas as pd import matplotlib.pyplot as plt # %matplotlib notebook # Create a filepath to the periodic table csv file. file_path = os.path.join("data", "PubChemElements_all.csv") # Use pandas to read the csv file into a table. df = pd.read_csv(file_path)...
_____no_output_____
BSD-3-Clause
book/homework_1_solutions.ipynb
janash/python-analysis
Exercise 2 Solution
# Create a set of subplots of the two trends: Ionization Energy and Electronegativity. comparison_fig, comparison_ax = plt.subplots(1, 2) # Add the first subplot. comparison_ax[0].scatter('AtomicNumber', 'IonizationEnergy', data=df) comparison_ax[0].set_xlabel('Atomic Number') comparison_ax[0].set_ylabel('Ionization')...
_____no_output_____
BSD-3-Clause
book/homework_1_solutions.ipynb
janash/python-analysis
Exercise 3 Solution
# Determine possible states stored in the Dataframe states = pd.unique(df['StandardState']) states # Create a function that returns a different color for each type of standard state. def assign_state_color(standard_state): state_markers = {'Gas': 'r', 'Solid': 'b', 'Liquid'...
_____no_output_____
BSD-3-Clause
book/homework_1_solutions.ipynb
janash/python-analysis
Generator function to armstrong numbers
def genFunc(): start = 1 end = 1000 for i in range(start, end + 1): if i >= 10: order = len(str(i)) sum = 0 temp = i while temp > 0: dig = temp % 10 sum += dig ** order temp //= 10 if i == sum: yield i for x in genFunc(): print(x)
153 370 371 407
Apache-2.0
Assignment Day 9 q2.ipynb
gopi2650/letsupgrade-python
define categorical / numeric columns
d.hist(figsize=[20, 20], sharey=False, bins=50) d.hist(figsize=[20, 20], sharey=True) print() col_identity = {'ignore': ['accident_id','provider_and_id','provider_code'], 'numeric' : ['license_acquiring_date', 'accident_year','accident_month'], 'category' : ['age_group', 'sex', 'vehicle_ty...
_____no_output_____
MIT
datascience/2018_10_27_anyway_data_trial_1.ipynb
neuhofmo/anyway_projects
balance the data and train forest of decision trees
from sklearn.model_selection import train_test_split from imblearn.ensemble import BalancedRandomForestClassifier # !!!!!! balanced! from sklearn.metrics import f1_score, precision_score, recall_score, balanced_accuracy_score del df X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=42, test_size=0....
_____no_output_____
MIT
datascience/2018_10_27_anyway_data_trial_1.ipynb
neuhofmo/anyway_projects
Data Support
fan_smoothing_window = 60 # time width of smoothing wndow def load_df(df_name): df = pd.read_csv( df_name, usecols=[0, 1, 2, 3, 4, 5, 6] ) df.rename(index=str, columns={ # remove units for easier indexing 'Time (s)': 'Time', 'Temperature': 'Thermistor', 'Error (deg...
_____no_output_____
BSD-3-Clause
results/Temperature Control Plots.ipynb
ethanjli/punchcard-microfluidics
Plotting Support
figure_width = 17.5 figure_temps_height = 4 figure_complete_height = 7.5 figure_complete_height_ratio = (3, 2) box_width_shrink_factor = 0.875 # to fit the figure legend on the right ylabel_position = -0.08 min_temp = 20 max_temp = 100 legend_location = 'center right' reached_color = 'gainsboro' # light gray setpo...
_____no_output_____
BSD-3-Clause
results/Temperature Control Plots.ipynb
ethanjli/punchcard-microfluidics
Stepwise Sequence
df_stepwise = load_df('20190117 Thermal Subsystem Testing Data - Fifth Test.csv') smooth_fan(df_stepwise) df_stepwise fig_plot_temps(df_stepwise, 'Stepwise Adjustment Control Sequence') plt.savefig('stepwise_control.pdf', format='pdf') plt.savefig('stepwise_control.png', format='png') fig_plot_complete(df_stepwise, 'St...
_____no_output_____
BSD-3-Clause
results/Temperature Control Plots.ipynb
ethanjli/punchcard-microfluidics
Lysis Sequence
df_lysis = load_df('20190117 Thermal Subsystem Testing Data - Fourth Test.csv') smooth_fan(df_lysis) df_lysis fig_plot_temps(df_lysis, 'Thermal Lysis Control Sequence') fig_plot_complete(df_lysis, 'Thermal Lysis Control Sequence') plt.savefig('thermal_lysis.pdf', format='pdf') plt.savefig('thermal_lysis.png', format='p...
'HelveticaNeueLTStd_Md.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output. 'HelveticaNeueLTStd_Roman.otf' can not be subsetted into a Type 3 font. The entire font will be embedded in the output. 'HelveticaNeueLTStd_Md.otf' can not be subsetted into a Type 3 font. The entire fon...
BSD-3-Clause
results/Temperature Control Plots.ipynb
ethanjli/punchcard-microfluidics
**Table of Contents:*** Introduction* The RMS Titanic* Import Libraries* Getting the Data* Data Exploration/Analysis* Data Preprocessing - Missing Data - Converting Features - Creating Categories - Creating new Features* Building Machine Learning Models - Training 8 different models - Which is the be...
# linear algebra import numpy as np # data processing import pandas as pd # data visualization import seaborn as sns %matplotlib inline from matplotlib import pyplot as plt from matplotlib import style # Algorithms from sklearn import linear_model from sklearn.linear_model import LogisticRegression from sklearn.en...
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
**Getting the Data**
test_df = pd.read_csv("../input/test.csv") train_df = pd.read_csv("../input/train.csv")
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
**Data Exploration/Analysis**
train_df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): PassengerId 891 non-null int64 Survived 891 non-null int64 Pclass 891 non-null int64 Name 891 non-null object Sex 891 non-null object Age 714 non-null float64 SibSp ...
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
**The training-set has 891 examples and 11 features + the target variable (survived)**. 2 of the features are floats, 5 are integers and 5 are objects. Below I have listed the features with a short description: survival: Survival PassengerId: Unique Id of a passenger. pclass: Ticket class sex: Sex Age:...
train_df.describe()
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
Above we can see that **38% out of the training-set survived the Titanic**. We can also see that the passenger ages range from 0.4 to 80. On top of that we can already detect some features, that contain missing values, like the 'Age' feature.
train_df.head(15)
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
From the table above, we can note a few things. First of all, that we **need to convert a lot of features into numeric** ones later on, so that the machine learning algorithms can process them. Furthermore, we can see that the **features have widely different ranges**, that we will need to convert into roughly the same...
total = train_df.isnull().sum().sort_values(ascending=False) percent_1 = train_df.isnull().sum()/train_df.isnull().count()*100 percent_2 = (round(percent_1, 1)).sort_values(ascending=False) missing_data = pd.concat([total, percent_2], axis=1, keys=['Total', '%']) missing_data.head(5)
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
The Embarked feature has only 2 missing values, which can easily be filled. It will be much more tricky, to deal with the 'Age' feature, which has 177 missing values. The 'Cabin' feature needs further investigation, but it looks like that we might want to drop it from the dataset, since 77 % of it are missing.
train_df.columns.values
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
Above you can see the 11 features + the target variable (survived). **What features could contribute to a high survival rate ?** To me it would make sense if everything except 'PassengerId', 'Ticket' and 'Name' would be correlated with a high survival rate. **1. Age and Sex:**
survived = 'survived' not_survived = 'not survived' fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10, 4)) women = train_df[train_df['Sex']=='female'] men = train_df[train_df['Sex']=='male'] ax = sns.distplot(women[women['Survived']==1].Age.dropna(), bins=18, label = survived, ax = axes[0], kde =False) ax = sns.dis...
_____no_output_____
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
You can see that men have a high probability of survival when they are between 18 and 30 years old, which is also a little bit true for women but not fully. For women the survival chances are higher between 14 and 40.For men the probability of survival is very low between the age of 5 and 18, but that isn't true for wo...
FacetGrid = sns.FacetGrid(train_df, row='Embarked', size=4.5, aspect=1.6) FacetGrid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette=None, order=None, hue_order=None ) FacetGrid.add_legend()
/opt/conda/lib/python3.6/site-packages/seaborn/axisgrid.py:230: UserWarning: The `size` paramter has been renamed to `height`; please update your code. warnings.warn(msg, UserWarning) /opt/conda/lib/python3.6/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional index...
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects
Embarked seems to be correlated with survival, depending on the gender. Women on port Q and on port S have a higher chance of survival. The inverse is true, if they are at port C. Men have a high survival probability if they are on port C, but a low probability if they are on port Q or S. Pclass also seems to be correl...
sns.barplot(x='Pclass', y='Survived', data=train_df)
/opt/conda/lib/python3.6/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a ...
MIT
titanic/end-to-end-project-with-python.ipynb
MLVPRASAD/KaggleProjects