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
Training the model
max_epochs = 100 vec_size = 50 alpha = 0.025 # Distributed memory model model = Doc2Vec(vector_size=vec_size, alpha=alpha, min_alpha=0.00025, min_count=1, dm=1, workers=8) # Initialize the model model.build_vocab(documents) # Train the mod...
_____no_output_____
MIT
TOI/Doc2Vec.ipynb
aashish-jain/Social-unrest-prediction
Generate the document dictionary that can be used to access a document by tag
# Generate the document dictionary that can be used to access a document by tag document_dic = {} for doc,tag in documents: document_dic[tag[0]] = doc
_____no_output_____
MIT
TOI/Doc2Vec.ipynb
aashish-jain/Social-unrest-prediction
Test the model for Random Data from ACLED after Jan-1-2019
article = "On July 15, a long protest march by farmers, from Mandsaur in Madhya Pradesh to New Delhi, demanding loan waiver and fair price for their produce, reached Jaipur." article = ' '.join(generate_document_vocabulary(article))
_____no_output_____
MIT
TOI/Doc2Vec.ipynb
aashish-jain/Social-unrest-prediction
Find the closest Document
# Reference : https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-lee.ipynb # find the vector vec = model.infer_vector(sabri) #find 10 closest documents sims = model.docvecs.most_similar([vec]) # Print the document for doc_tag,score in sims: print("Document has score : "score, "\nConte...
_____no_output_____
MIT
TOI/Doc2Vec.ipynb
aashish-jain/Social-unrest-prediction
https://github.com/pysal/mgwr/pull/56
import sys sys.path.append("C:/Users/msachde1/Downloads/Research/Development/mgwr") import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np from mgwr.gwr import GWR from spglm.family import Gaussian, Binomial, Poisson from mgwr.gwr import MGWR from mgwr.sel_bw import Sel_BW import mult...
_____no_output_____
MIT-0
Notebooks/Binomial_MGWR_approaches_tried.ipynb
mehak-sachdeva/MGWR_book
Fundamental equation By simple algebraic manipulation, the probability that Y=1 is: \begin{align}p = 1 / (1 + exp (-{\beta} & _k x _{k,i}) ) \\\end{align} Approaches tried:1. Changing XB to : `1 / (1 + np.exp (-1*np.sum(np.multiply(X,params),axis=1)))` - these are the predicted probabilities ~(0,1)2. Chan...
data_p = pd.read_csv("C:/Users/msachde1/Downloads/logistic_mgwr_data/landslides.csv") data_p.head()
_____no_output_____
MIT-0
Notebooks/Binomial_MGWR_approaches_tried.ipynb
mehak-sachdeva/MGWR_book
Helper functions - hardcoded here for simplicity in the notebook workflowPlease note: A separate bw_func_b will not be required when changes will be made in the repository
kernel='bisquare' fixed=False spherical=False search_method='golden_section' criterion='AICc' interval=None tol=1e-06 max_iter=500 X_glob=[] def gwr_func(y, X, bw,family=Gaussian(),offset=None): return GWR(coords, y, X, bw, family,offset,kernel=kernel, fixed=fixed, constant=False, sphe...
_____no_output_____
MIT-0
Notebooks/Binomial_MGWR_approaches_tried.ipynb
mehak-sachdeva/MGWR_book
GWR Binomial model with independent variable, x = slope
coords = list(zip(data_p['X'],data_p['Y'])) y = np.array(data_p['Landslid']).reshape((-1,1)) elev = np.array(data_p['Elev']).reshape((-1,1)) slope = np.array(data_p['Slope']).reshape((-1,1)) SinAspct = np.array(data_p['SinAspct']).reshape(-1,1) CosAspct = np.array(data_p['CosAspct']).reshape(-1,1) X = np.hstack([elev,...
_____no_output_____
MIT-0
Notebooks/Binomial_MGWR_approaches_tried.ipynb
mehak-sachdeva/MGWR_book
Multi_bw changes
def multi_bw(init,coords,y, X, n, k, family=Gaussian(),offset=None, tol=1e-06, max_iter=20, multi_bw_min=[None], multi_bw_max=[None],rss_score=True,bws_same_times=3, verbose=True): if multi_bw_min==[None]: multi_bw_min = multi_bw_min*X.shape[1] if multi_bw_max==[None]: ...
_____no_output_____
MIT-0
Notebooks/Binomial_MGWR_approaches_tried.ipynb
mehak-sachdeva/MGWR_book
Transfer LearningIn this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html). ImageNet is a massiv...
%matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`.
data_dir = 'Cat_Dog_data' # TODO: Define transforms for the training data and testing data train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), ...
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.htmlid5). Let's print out the model architecture so we can see what's going on.
model = models.densenet121(pretrained=True) model
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. T...
# Freeze parameters so we don't backprop through them for param in model.parameters(): param.requires_grad = False from collections import OrderedDict classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(1024, 500)), ('relu', nn.ReLU()), ...
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU lea...
import time for device in ['cpu', 'cuda']: criterion = nn.NLLLoss() # Only train the classifier parameters, feature parameters are frozen optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) model.to(device) for ii, (inputs, labels) in enumerate(trainloader): # Move input and ...
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
You can write device agnostic code which will automatically use CUDA if it's enabled like so:```python at beginning of the scriptdevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")... then whenever you get a new Tensor or Module this won't copy if they are already on the desired deviceinput = data.t...
# Use GPU if it's available device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = models.densenet121(pretrained=True) # Freeze parameters so we don't backprop through them for param in model.parameters(): param.requires_grad = False model.classifier = nn.Sequential(nn.Linear(1024, 256...
_____no_output_____
MIT
deep_learning/new-intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
willcanniford/python-learning
PNW Focal Species Sanity CheckWe'll use GBIF to select a species with lots of occurrences in the PNW and assess the impact of MHWs on that species.
plankton = pd.read_csv("../data/Phytoplankton_temperature_growth_rate_dataset_2016_01_29/traits_derived_2016_01_29.csv", engine='python') plankton = plankton[(plankton.minqual == "good") & (plankton.maxqual == "good") & (plankton.curvequal == "good")] plankton = plankton[plankton...
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
GBIF Occurrences*For locating PNW species...*
genera = plankton.genus.dropna().unique() genera genera = [pygbif.species.name_lookup(q=g, rank='genus') for g in genera] genera = [g for g in genera if len(g['results']) > 0] genera = [max(g['results'], key=lambda x: x['numDescendants']) for g in genera] [g['key'] for g in genera] genera_counts = [pygbif.occurrences.c...
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
TPC From Genus
def tpc(T, a, b, z, w): ''' https://science.sciencemag.org/content/sci/suppl/2012/10/25/science.1224836.DC1/Thomas.SM.pdf ''' return a * np.exp(b*T) * (1 - ((T - z)/(w / 2))**2) def plot_tpc(sample, ax=None): T = np.arange(sample['mu.c.opt.list'] - (sample['mu.wlist'] / 2), sample['mu.c.opt.list'] +...
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
**NOTE** Overrode above analysis and chose a single species
sample_species = this_genus.sample(1).iloc[0] plot_tpc(sample_species)
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
Enter MHW and SST
mhw_time = slice('2014-01-01', '2015-05-31') mhws = xr.open_dataset("../mhw_pipeline/pnw_mhw_intensity.nc").rename({ '__xarray_dataarray_variable__': 'mhw_intensity' }) mhws mhw_recent = mhws.sel(time=mhw_time) mhw_count = mhw_recent.median(dim='time').mhw_intensity plt.figure(figsize=(10,10)) ax = plt.axes(proj...
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
SST
fs = gcsfs.GCSFileSystem(project=GCP_PROJECT_ID, token="/home/jovyan/gc-pangeo.json") oisst = xr.open_zarr(fs.get_mapper(OISST_GCP)) oisst = oisst.assign_coords(lon=(((oisst.lon + 180) % 360) - 180)).sortby('lon') PNW_LAT = slice(mhw_count.lat.min(), mhw_count.lat.max()) PNW_LON = slice(mhw_count.lon.min(), mhw_count.l...
MovieWriter ffmpeg unavailable; trying to use <class 'matplotlib.animation.PillowWriter'> instead.
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
Compute Performance Detriment
def perf_det(T, T_opt, tpc, axis=1): return tpc(T_opt) - tpc(T) def tsm(T, T_opt, axis): return T - T_opt def plot_det(s, ax): this_tpc = partial(tpc, a=s['mu.alist'], b=s['mu.blist'], z=s['mu.c.opt.list'], w=s['mu.wlist']) T = np.arange(s['mu.g.opt.list'] - (s['mu.wlist'] / 2), s['mu.c.opt.list'...
_____no_output_____
MIT
analysis/distribution-analysis.ipynb
HuckleyLab/phyto-mhw
Data Analysis Research Question: Examine the top 3 countries who have competed at the olympics, and examine their preformance over the past 120 years. For Each top 3 country, these aspects should be examined in order to answer the question:- Which years did this country win the most medals? - Most gold medals?- Wh...
import pandas as pd import numpy as np from matplotlib import pyplot import matplotlib.pyplot as plt import seaborn as sns data = pd.read_csv('../data/raw/olympic_dataset.csv', low_memory=False, encoding = 'utf-8') top3Countries=(data.dropna(subset=['Medal'])).value_counts(subset=['NOC']) top3Countries.head(3)
_____no_output_____
MIT
analysis/.ipynb_checkpoints/Task_5-checkpoint_LOCAL_1236.ipynb
data301-2020-winter2/course-project-group_1001
Based on this, we can see that the United States leads the dataset with the most amount of medals, with the Soviet Union coming in second, and Germany in third. Therefore, our data analysis will focus on these three countries.Although, with the Soviet Union and Germany, there have been many historical changes to those ...
us =(data["NOC"] == "USA") athletes=data[(us)] print("Number of events particpated in by American athletes: "+str(athletes.shape[0])) athletesUnique=data[us].drop_duplicates(subset=['Name']) print("Number of American athletes who have competed at the olympics: "+str(athletesUnique.shape[0])) maleAthletesUnique=data[us&...
_____no_output_____
MIT
analysis/.ipynb_checkpoints/Task_5-checkpoint_LOCAL_1236.ipynb
data301-2020-winter2/course-project-group_1001
Other Graphs to Note
sns.countplot(data=medals, x="Medal", hue="Sex", palette='pastel') plt.title("Types of medals won by male and female American athletes") sns.countplot(data=medals, x="Year", hue="Sex", palette='pastel') plt.title("Medals won by American olympic athletes per year compared to sex")
_____no_output_____
MIT
analysis/.ipynb_checkpoints/Task_5-checkpoint_LOCAL_1236.ipynb
data301-2020-winter2/course-project-group_1001
K26 - Heated Wall Interface at 90°. Variable fluid densities => but very small variations Also no Heat capacity => infinitely fast heat conduction Height of the domain is reduced Implicit RK timestepping, to allow for an adaption of the maximum step size Also only the "start" of the process is simulated, i....
#r "..\..\..\src\L4-application\BoSSSpad\bin\Release\net5.0\BoSSSpad.dll" using System; using System.Collections.Generic; using System.Linq; using ilPSP; using ilPSP.Utils; using BoSSS.Platform; using BoSSS.Foundation; using BoSSS.Foundation.XDG; using BoSSS.Foundation.Grid; using BoSSS.Foundation.Grid.Classi...
_____no_output_____
Apache-2.0
examples/XNSFE_Solver/HeatedWall_VariableDensity/HeatedWall90DegVariableDensity.ipynb
FDYdarmstadt/BoSSS
Setup Workflowmanagement, Batchprocessor and Database
ExecutionQueues static var myBatch = BoSSSshell.GetDefaultQueue(); static var myDb = myBatch.CreateOrOpenCompatibleDatabase("XNSFE_HeatedWall"); myDb.Path BoSSSshell.WorkflowMgm.Init($"HeatedWall_VariableDensity");
Project name is set to 'HeatedWall_VariableDensity'.
Apache-2.0
examples/XNSFE_Solver/HeatedWall_VariableDensity/HeatedWall90DegVariableDensity.ipynb
FDYdarmstadt/BoSSS
Setup Simulationcontrols
using BoSSS.Application.XNSFE_Solver; int[] hRes = {16, 24, 32, 48}; int[] pDeg = {2}; double[] Q = {0.2}; double[] dRho_B = {0.0, -1e-3, -5e-3, -1e-2, -5e-2, -1e-1}; List<XNSFE_Control> Controls = new List<XNSFE_Control>(); foreach(int h in hRes){ foreach(int p in pDeg){ foreach(double q in Q){ ...
_____no_output_____
Apache-2.0
examples/XNSFE_Solver/HeatedWall_VariableDensity/HeatedWall90DegVariableDensity.ipynb
FDYdarmstadt/BoSSS
Start simulations on Batch processor
foreach(var C in Controls) { Type solver = typeof(BoSSS.Application.XNSFE_Solver.XNSFE<XNSFE_Control>); string jobName = C.SessionName; var oneJob = new Job(jobName, solver); oneJob.NumberOfMPIProcs = 1; oneJob.SetControlObject(C); oneJob.Activate(myBatch, true); }
_____no_output_____
Apache-2.0
examples/XNSFE_Solver/HeatedWall_VariableDensity/HeatedWall90DegVariableDensity.ipynb
FDYdarmstadt/BoSSS
Hyperexponential CaseThroughout this document, the following packages are required:
import numpy as np import scipy import math from scipy.stats import binom, erlang, poisson from scipy.optimize import minimize from functools import lru_cache
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
Plot Phase-Type Fit
from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets import matplotlib.pyplot as plt def SCV_to_params(SCV): # weighted Erlang case if SCV <= 1: K = math.floor(1/SCV) p = ((K + 1) * SCV - math.sqrt((K + 1) * (1 - K * SCV))) / (SCV + 1) mu...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
The recursion of the dynamic program is given as follows. For $i=1,\dots,n-1$, $k=1,\dots,i$, and $m\in\mathbb{N}_0$,\begin{align*}\xi_i(k,m) &= \inf_{t\in \mathbb{N}_0}\Big(\omega \bar{f}^{\circ}_{k,m\Delta}(t\Delta) + (1-\omega)\bar{h}^{\circ}_{k,m\Delta} +\sum_{\ell=2}^{k}\sum_{j=0}^{t}\bar{q}_{k\ell,mj}(t)\xi_{i+1}...
@lru_cache(maxsize=128) def B_sf(t): """The survival function P(B > t).""" return p * np.exp(-mu1 * t) + (1 - p) * np.exp(-mu2 * t) @lru_cache(maxsize=128) def gamma(z, t): """Computes P(Z_t = z | B > t).""" gamma_circ = B_sf(t) if z == 1: return p * np.exp(-mu1 * t) / gamma_circ ...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
Next, we implement $\bar{f}^{\circ}_{k,u}(t)$, which depends on $\bar{f}_{k,z}(t)$:
@lru_cache(maxsize=128) def f_bar(k,z,t): if z == 1: return sum([binom.pmf(m, k-1, p) * sigma(t, m+1, k-1-m) for m in range(k)]) elif z == 2: return sum([binom.pmf(m, k-1, p) * sigma(t, m, k-m) for m in range(k)]) @lru_cache(maxsize=128) def f_circ(k, u, t): return gamma(1, u) * f_bar(...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
In here, we need to evaluate the object $\sigma_{t}[m,k]$, which depends on $\rho_{t}[m,k]$:
@lru_cache(maxsize=512) def sigma(t,m,k): return (t - k / mu2) * erlang.cdf(t, m, scale=1/mu1) - (m / mu1) * erlang.cdf(t, m+1, mu1) + \ (mu1 / mu2) * sum([(k-i) * rho_t(t, m-1, i) for i in range(k)]) @lru_cache(maxsize=512) def rho_t(t,m,k): if not k: return np.exp(-mu2 * t) * (m...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
We do the same for $\bar{h}^{\circ}_{k,u}(t)$, which only depends on $\bar{h}_{k,z}$:
@lru_cache(maxsize=128) def h_bar(k, z): if k == 1: return 0 elif z <= K: return ((k - 1) * (K + 1 - p) + 1 - z) / mu elif z == K + 1: return ((k - 2) * (K + 1 - p) + 1) / mu @lru_cache(maxsize=128) def h_circ(k, u): return gamma(1, u) * h_bar() sum([gamma(z, u) * h_bar(k, z) f...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
The next objective is to implement $\bar{q}_{k\ell,mj}(t)$. This function depends on $q_{k\ell,z,v}(t)$, which depends on $\psi_{vt}[k,\ell]$: TODO
# TODO poisson.pmf(3,0)
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
Finally, we implement the remaining transition probabilities $P^{\uparrow}_{k,u}(t)$ and $P^{\downarrow}_{k,u}(t)$:
# @lru_cache(maxsize=128) def P_up(k, u, t): """Computes P(N_t- = k | N_0 = k, B_0 = u).""" return B_sf(u + t) / B_sf(u) @lru_cache(maxsize=128) def P_down(k, u, t): """Computes P(N_t- = 0 | N_0 = k, B_0 = u).""" return sum([binom.pmf(m, k, p) * Psi(t, m, k-m) for m in range(k+1)]) @lru_cache(maxsize=...
_____no_output_____
MIT
.ipynb_checkpoints/Hyperexponential Case-checkpoint.ipynb
Roshanmahes/Appointment-Scheduling
Reading and Writing filesSo far, we have typed all of our "data" into the code of our software (e.g. the names of the students, and their ages.Most of the time, this kind of data is stored in files. We need to read (and write) files so that we can create and use permanent copies of these data (and exchange these data...
studentfile = open("students.csv", "r") print(studentfile)
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Does the output of that print statement surprise you? What it tells you is that 'studentfile' is a Python "object" (again, we will discuss objects in more detail later, but you will start to see how they work now...)studentfile is an object of type "TextIOWrapper" (from the "io" Python library, which is automatically ...
print(studentfile.read())
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Now we need to talk about a feature of file input/output, called a "pointer". The pointer is the position where the code "is" in the file - is it at the beginning? is it at the end"? Is it at line 5?Where is the pointer now? Let's try the same command again!
print(studentfile.read())
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Nada de nada! That's because the pointer is at the end of the file - when we say file.read it tries to read starting from the end of the file...and of course, there is nothing there. To reset back to the beginning, we will use the "seek" function, and set it to position '0':
studentfile.seek(0) print(studentfile.read())
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
More refined file access - line-by-lineMost of the time, you do not want to read the enire file into memory (tell me why this can be very very bad!.... please)MOST of the time, a file will have one "record" per line. e.g. our CSV file has the "name,age" for one student per line. We want to read those lines one-at-a-...
studentfile.seek(0) # set it back to the beginning again for this lesson... print(studentfile.readlines())
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
You will see that this returns a list, which means we can use it in a FOR loop...
studentfile.seek(0) # set it back to the beginning again for this lesson... for line in studentfile.readlines(): print("the current record is", line)
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
We're getting closer to what we want! We have each record as a string in the format "Mark,50". What we want is to separate the "Mark" and the "50" so that we could put them into separate variables (e.g. *name* and *age*)There is a ***correct*** way to this, but you already know one way to solve this problem! In the ...
# put your amazing solution here!
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
OK, so now you have solved the problem using regular expressions, however... the solution isn't very "abstract". In another case, you might have a more complex record: Mark,50,190cm,95kg,163483,113mmhg,29mg/mlYour regular expression would start to get ugly! What is the one thing that is constant in this CSV file? ...
studentfile.seek(0) # set it back to the beginning again for this lesson... for line in studentfile.readlines(): print("the current record is", line) name, age = line.split(',') print("Name:", name, " Age:", age)
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Much better! But... *Still not quite right!!* What are all of those blank lines? We didn't ask for blank lines...Remember just a few minutes ago we looked at the output from readlines(): studentfile.seek(0) set it back to the beginning again for this lesson... print(studentfile.readlines()) ==> ['Ma...
studentfile.seek(0) # set it back to the beginning again for this lesson... for line in studentfile.readlines(): line = line.rstrip() print("the current record is", line) name, age = line.split(',') print("Name:", name, " Age:", age)
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
When you have finished with an open file, it is a very good idea to close it! studentfile.close() it's a good idea to close a file once you are finished with it! We are...
studentfile.close() # it's a good idea to close a file once you are finished with it! We are...
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Writing to a fileWriting to a file is very straightforward. Use the same "open" command that you have already learned, but using the "w" flag ("open for **w**rite), then write information to that open file using the *write()* method.Python will help you by creating the file if it doesn't exist. For example, the box ...
olderstudents = open("OLDERstudents.csv", "w") olderstudents.write("hello, I am writing stuff to a file!\nThis is very cool!") # the write function, using \n (newline) olderstudents.close() checkcontent = open("OLDERstudents.csv", "r") print(checkcontent.read()) # print the content of the file checkcontent.close()
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
Now you!* create the file OLDERstudents.csv* using the data from the original students.csv, make everyone 5 years older* write the new older student data to the OLDERstudents.csv file, in an identical format (Mark,55....)* do this again, but this time, create a "header line" (Student Name, Student Age) Student ...
# put your amazing code here!
_____no_output_____
CC-BY-4.0
Lesson 6 - File access in Python3.ipynb
mjmtnez/Accelerated_Intro_to_CompBio_Part_2
SymPy Symbolic ComputationFree, Open Source, Python- solve equations - simplify expressions- compute derivatives, integrals, limits- work with matrices, - plotting & printing- code gen - physics - statitics - combinatorics- number theory - geometry - logic---- Modules[SymPy Core](http://docs.sympy.org/latest/modules/c...
# declare variable first x, y = symbols('x y') # Declare expression expr = x + 3*y # Print expressions print("expr =", expr) print("expr + 1 =", expr + 1) print("expr - x =", expr - x) # auto-simplify print("x * expr =", x * expr)
expr = x + 3*y expr + 1 = x + 3*y + 1 expr - x = 3*y x * expr = x*(x + 3*y)
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
---- Substitution
x = symbols('x') expr = x + 1 print(expr) display(expr) # Evaluate expression at a point print("expr(2)=", expr.subs(x, 2)) # Replace sub expression with another sub expression # 1. For expressions with symmetry x, y = symbols('x y') expr2 = x ** y expr2 = expr2.subs(y, x**y) expr2 = expr2.subs(y, x**x) display(expr2)...
_____no_output_____
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
---- Equality & Equivalence
# do not use == between symbols and variables, will return false x = symbols('x') x+1==4 # Create a symbolic equality expression expr2 = Eq(x+1, 4) print(expr2) display(expr2) print("if x=3, then", expr2.subs(x,3)) # two equivalent formulas expr3 = (x + 1)**2 # we use pythons ** exponentiation (instead of ^) expr4 = ...
expr3
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
---- SymPy Types & Casting
print( "1 =", type(1) ) print( "1.0 =", type(1.0) ) print( "Integer(1) =", type(Integer(1)) ) print( "Integer(1)/Integer(3) =", type(Integer(1)/Integer(3)) ) print( "Rational(0.5) =", type(Rational(0.5)) ) print( "Rational(1/3) =", type(Rational(1,3)) ) #...
_____no_output_____
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
---- Evaluating Expressions
# evaluate as float using .evalf(), and N display( sqrt(8) ) display( sqrt(8).evalf() ) display( sympy.N(sqrt(8)) ) # evaluate as float to nearest n decimals display(sympy.pi) display(sympy.pi.evalf(100))
_____no_output_____
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
---- SymPy Types Number Class[Number](http://docs.sympy.org/latest/modules/core.htmlnumber) - [Float](http://docs.sympy.org/latest/modules/core.htmlfloat) - [Rational](http://docs.sympy.org/latest/modules/core.htmlrational) - [Integer](http://docs.sympy.org/latest/modules/core.htmlinteger) - [RealNumber](http://docs.sy...
# Rational Numbers expr_rational = Rational(1)/3 print("expr_rational") display( type(expr_rational) ) display( expr_rational ) eval_rational = expr_rational.evalf() print("eval_rational") display( type(eval_rational) ) display( eval_rational ) neval_rational = N(expr_rational) print("neval_rational") display( type(n...
expr_rational
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
 Complex Numbers
# Complex Numbers supported. expr_cplx = 2.0 + 2*sympy.I print("expr_cplx") display( type(expr_cplx) ) display( expr_cplx ) print("expr_cplx.evalf()") display( type(expr_cplx.evalf()) ) display( expr_cplx.evalf() ) print("float() - errors") print(" ") # this errors complex cannot be converted to float #display( floa...
_____no_output_____
MIT
notebooks/python-data-science/sympy/sympy.ipynb
sparkboom/my_jupyter_notes
This is statregistration.py but then for multiple .nlp's. Edited from Tobias' script: Calculates shifts from CPcorrected and create a shift corrected stack. The calculations implements the drift correction algorithm as described in section 4 of the paper. https://doi.org/10.1016/j.ultramic.2019.112913 https...
import numpy as np import matplotlib.pyplot as plt import dask.array as da from dask.distributed import Client, LocalCluster import scipy.ndimage as ndi import os import time import napari %gui qt from pyL5.lib.analysis.container import Container from pyL5.analysis.CorrectChannelPlate.CorrectChannelPlate import Cor...
_____no_output_____
MIT
StatRegistration_multiNLP.ipynb
thagusta/LEEM-analysis-1
Step 0: choose areaChoose the (rectangular) area on which to perform drift correction.
center = [dim//2 for dim in original.shape[1:]] extent = (center[0]-fftsize, center[0]+fftsize, center[1]-fftsize, center[1]+fftsize) extent viewer = napari.view_image(np.swapaxes(original, -1, -2), name='original') # create the square in napari center = np.array(original.shape[1:]) // 2 square = np.array([[center[1]+...
The extent in x,y is: (214, 726, 646, 1158) pixels, which makes the largest side/2 256 pixels.
MIT
StatRegistration_multiNLP.ipynb
thagusta/LEEM-analysis-1
Now starting the steps of the algorithm
def crop_and_filter_extent(images, extent, sigma=11, mode='nearest'): """Crop images to extent chosen and apply the filters. Cropping is initially with a margin of sigma, to prevent edge effects of the filters. extent = minx,maxx,miny,maxy of ROI""" result = images[:, extent[0]-sigma:extent[1]+sigma, ...
Saving stack as .png Now saving movie stack.mp4
MIT
StatRegistration_multiNLP.ipynb
thagusta/LEEM-analysis-1
Create a Class To create a class, use the keyword class:
class car: x = 5 print(car)
<class '__main__.car'>
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Object Creation
class car: x = 5 company="Maruti" p1 = car() print(p1.x) print(p1.company)
5 Maruti
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Object Creation & The self Parameter
class Jeep: # A simple class # attribute company = "Maruti" location = "India" # A sample method def test(self): print("I'm from", self.company) print("I'm made in ", self.location) # Object instantiation jimny = Jeep() # Accessing class attributes ...
Maruti I'm from Maruti I'm made in India
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
The self Parameter It does not have to be named *self* , you can call it whatever you like, but it has to be the first parameter of any function in the class:
class Car: def __init__(sampleobject, name, price): sampleobject.name = name sampleobject.price = price def myfunc(abc): print("Hello , my car is " + abc.name) p1 = Car("BMW", 1) p1.myfunc()
Hello , my car is BMW
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
The __init__() Function Note: The __init__() function is called automatically every time the class is being used to create a new object.
class Car: def __init__(self, company): self.company = company p1 = Car("Maruti" ) print(p1.company)
Maruti
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Modify Object Properties
class Car: def __init__(self, model, rate): self.model = model self.rate = rate def myfunc(self): print("Hello my name is " + self.model) p1 = Car("Swift", 500000) p1.myfunc() print(p1.model) print("Previous rate of my model was " , p1.rate) p1.rate ...
Hello my name is Swift Swift Previous rate of my model was 500000 New rate is 400000
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Delete Object Properties You can delete properties on objects by using the del keyword:
class Car: def __init__(self, model, rate): self.model = model self.rate = rate def myfunc(self): print("Hello my name is " + self.model) p1 = Car("Swift",500000 ) del p1.rate print(p1.rate)
_____no_output_____
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Delete Object You can delete objects by using the del keyword:
class Car: def __init__(self, model, rate): self.model = model self.rate = rate def myfunc(self): print("Hello my name is " + self.model) p1 = Car("Swift",500000 ) del p1 print(p1.rate)
_____no_output_____
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
The pass Statement
class Person: pass class Car: # Class Variable fav_car = 'Verna' # The init method or constructor def __init__(self, model, color): # Instance Variable self.model = model self.color = color # Objects of Dog class ...
Moderna details: Moderna is a Verna Model: swift Color: brown Buziga details: Buziga is a Verna Model: wagonR Color: black Accessing class variable using class name Verna
MIT
Ananthakrishnan_Python_Class&Objects.ipynb
VarunBhaaskar/Open-contributions
Lambda School Data Science - Survival Analysis![My normal approach is useless here, too.](https://imgs.xkcd.com/comics/probability.png)https://xkcd.com/881/The aim of survival analysis is to analyze the effect of different risk factors and use them to predict the duration of time between one event ("birth") and anoth...
!pip install lifelines import numpy as np import pandas as pd import matplotlib.pyplot as plt import lifelines # lifelines comes with some datasets to get you started playing around with it. # Most of the datasets are cleaned-up versions of real datasets. Here we will # use their Leukemia dataset comparing 2 different ...
_____no_output_____
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
You can you any Pandas DataFrame with lifelines. The only requirement is that the DataFrame includes features that describe:* a duration of time for the observation* a binary column regarding censorship (`1` if the death event was observed, `0` if the death event was not observed)Sometimes, you will have to engineer ...
leukemia.info() leukemia.describe() time = leukemia.t.values event = leukemia.status.values ax = lifelines.plotting.plot_lifetimes(time, event_observed=event) ax.set_xlim(0, 40) ax.grid(axis='x') ax.set_xlabel("Time in Months") ax.set_title("Lifelines for Survival of Leukemia Patients"); plt.plot();
_____no_output_____
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Kaplan-Meier survival estimate The Kaplan-Meier method estimates survival probability from observed survival times. It results in a step function that changes value only at the time of each event, and confidence intervals can be computer for the survival probabilities. The KM survival curve,a plot of KM survival proba...
kmf = lifelines.KaplanMeierFitter() kmf.fit(time, event_observed=event) !pip install -U matplotlib # Colab has matplotlib 2.2.3, we need >3 kmf.survival_function_.plot() plt.title('Survival Function Leukemia Patients'); print(f'Median Survival: {kmf.median_} months after treatment') kmf.survival_function_.plot.line()...
Median survival time with Treatment 1: 8.0 months Median survival time with Treatment 0: 23.0 months
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Cox Proportional Hazards Model -- Survival RegressionIt assumes the ratio of death event risks (hazard) of two groups remains about the same over time.This ratio is called the hazards ratio or the relative risk.All Cox regression requires is an assumption that ratio of hazards is constant over time across groups.*The ...
# Using Cox Proportional Hazards model cph = lifelines.CoxPHFitter() cph.fit(leukemia, 't', event_col='status') cph.print_summary()
<lifelines.CoxPHFitter: fitted with 42 observations, 12 censored> duration col = 't' event col = 'status' number of subjects = 42 number of events = 30 log-likelihood = -69.59 time fit was run = 2019-01-20 19:09:48 UTC --- coef exp(coef) se(coef) z p log(p) lower 0.95 upper ...
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Interpreting the Results`coef`: usually denoted with $b$, the coefficient`exp(coef)`: $e^{b}$, equals the estimate of the hazard ratio. Here, we can say that participants who received treatment 1 had ~4.5 times the hazard risk (risk of death) compared to those who received treatment 2. And for every unit the `logWBC` ...
cph.plot_covariate_groups(covariate='logWBC', groups=np.arange(1.5,5,.5)) cph.plot_covariate_groups(covariate='sex', groups=[0,1])
_____no_output_____
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Remember how the Cox model assumes the ratio of death events between groups remains constant over time?Well we can check for that.
cph.check_assumptions(leukemia) # We can see that the sex variable is not very useful by plotting the coefficients cph.plot() # Let's do what the check_assumptions function suggested cph = lifelines.CoxPHFitter() cph.fit(leukemia, 't', event_col='status', strata=['sex']) cph.print_summary() cph.baseline_cumulative_haza...
<lifelines.CoxPHFitter: fitted with 42 observations, 12 censored> duration col = 't' event col = 'status' strata = ['sex'] number of subjects = 42 number of events = 30 log-likelihood = -55.73 time fit was run = 2019-01-20 19:09:51 UTC --- coef exp(coef) se(coef) z ...
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Notice that this regression has `Likelihood ratio test = 74.90 on 2 df, log(p)=-37.45`, while the one that included `sex` had `Likelihood ratio test = 47.19 on 3 df, log(p)=-21.87`. The LRT is higher and log(p) is lower, meaning this is likely a better fitting model.
cph.plot() cph.compute_residuals(leukemia, kind='score') cph.predict_cumulative_hazard(leukemia[:5]) surv_func = cph.predict_survival_function(leukemia[:5]) exp_lifetime = cph.predict_expectation(leukemia[:5]) plt.plot(surv_func) exp_lifetime # lifelines comes with some datasets to get you started playing around wit...
_____no_output_____
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
These are the "lifelines" of the study participants as they attempt to avoid recidivism
recidivism_sample = recidivism.sample(n=25) duration = recidivism_sample.week.values arrested = recidivism_sample.arrest.values ax = lifelines.plotting.plot_lifetimes(duration, event_observed=arrested) ax.set_xlim(0, 78) ax.grid(axis='x') ax.vlines(52, 0, 25, lw=2, linestyles='--') ax.set_xlabel("Time in Weeks") ax.s...
<lifelines.StatisticalResult> test_name = proportional_hazard_test null_distribution = chi squared degrees_of_freedom = 1 --- test_statistic p log(p) age identity 12.06 <0.005 -7.57 ** km 11.03 <0.005 -7.02 ** log 13.07 <0.00...
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
The Intuition - Hazard and Survival Functions Hazard Function - the dangerous bathtubThe hazard function represents the *instantaneous* likelihood of failure. It can be treated as a PDF (probability density function), and with real-world data comes in three typical shapes.![Different hazard functions](https://upload.w...
# TODO - Live! (As time permits)
_____no_output_____
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
Assignment - Customer ChurnTreselle Systems, a data consulting service, [analyzed customer churn data using logistic regression](http://www.treselle.com/blog/customer-churn-logistic-regression-with-r/). For simply modeling whether or not a customer left this can work, but if we want to model the actual tenure of a cus...
import pandas as pd # Loading the data to get you started df = pd.read_csv( 'https://raw.githubusercontent.com/treselle-systems/' 'customer_churn_analysis/master/WA_Fn-UseC_-Telco-Customer-Churn.csv') df.head() df.info() # A lot of these are "object" - some may need to be fixed... pd.set_option('display.max_ro...
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning. FutureWarning)
MIT
module2-survival-analysis/LS_DS_232_Survival_Analysis.ipynb
macscheffer/DS-Unit-2-Sprint-3-Advanced-Regression
$$p(word|C_k)$$
def nk(word,given_tag,data): if word not in voc1: return 0 else: word_in_sen=[(word in dc['s{}'.format(i)]) and (tag[i]==given_tag) for i in range(len(data))] return sum(word_in_sen) nk('find',4,twitter) def n(given_tag): if given_tag==0: return len(text_0) elif given_tag...
_____no_output_____
MIT
Twitter Sentiment Analysis/Untitled2.ipynb
mmaleki/Deep-Learning-with-Tensorfow
MAT281 Aplicaciones de la Matemática en la Ingeniería Módulo 04 Laboratorio Clase 06: Proyectos de Machine Learning Instrucciones* Completa tus datos personales (nombre y rol USM) en siguiente celda.* La escala es de 0 a 4 considerando solo valores enteros.* Debes _pushear_ tus cambios a tu repositorio personal del ...
import pandas as pd import altair as alt import numpy as np from vega_datasets import data alt.themes.enable('opaque') %matplotlib inline gapminder = data.gapminder_health_income() gapminder.head()
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
1. Análisis exploratorio (1 pto)Como mínimo, realizar un `describe` del dataframe y una visualización adecuada, una _scatter matrix_ con los valores numéricos.
desc=gapminder.describe() print(desc) pd.plotting.scatter_matrix(gapminder, alpha=0.3, figsize=(9,9), diagonal='kde')
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
2. Preprocesamiento (1 pto) Aplicar un escalamiento a los datos antes de aplicar nuestro algoritmo de clustering. Para ello, definir la variable `X_raw` que corresponde a un `numpy.array` con los valores del dataframe `gapminder` en las columnas _income_, _health_ y _population_. Luego, definir la variable `X` que de...
from sklearn.preprocessing import StandardScaler X_raw = gapminder.drop('country', axis=1).values X = StandardScaler().fit_transform(X_raw)
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
3. Clustering (1 pto)
from sklearn.cluster import KMeans
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
Definir un _estimator_ `KMeans` con `k=3` y `random_state=42`, luego ajustar con `X` y finalmente, agregar los _labels_ obtenidos a una nueva columna del dataframe `gapminder` llamada `cluster`. Finalmente, realizar el mismo gráfico del principio pero coloreado por los clusters obtenidos.
k = 3 kmeans = KMeans(k, random_state=42) kmeans.fit(X) clusters = kmeans.labels_ gapminder['cluster']=clusters ##gapminder.head() colors_palette = {0: "orange", 1: "green", 2: "violet"} colors = [colors_palette[c] for c in list(gapminder['cluster'])] pd.plotting.scatter_matrix(gapminder, alpha=0.3, figsize=(9,9), c=co...
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
4. Regla del codo (1 pto) __¿Cómo escoger la mejor cantidad de _clusters_?__En este ejercicio hemos utilizado que el número de clusters es igual a 3. El ajuste del modelo siempre será mejor al aumentar el número de clusters, pero ello no significa que el número de clusters sea el apropiado. De hecho, si tenemos que aj...
elbow = pd.Series(name="inertia").rename_axis(index="k") for k in range(1, 10): kmeans = KMeans(n_clusters=k, random_state=42).fit(X) elbow.loc[k] = kmeans.inertia_ # Inertia: Sum of distances of samples to their closest cluster center elbow = elbow.reset_index() alt.Chart(elbow).mark_line(point=True).encode( ...
_____no_output_____
MIT
m04_machine_learning/m04_c06_ml_workflow/m04_c06_lab.ipynb
Crhlb/mat281_repositorio
03 ImageClustering using PCA, Kmeans, DBSCAN![Assets/dbscan_graph.png](Assets/dbscan_graph.png) Learning Objectives* Explore and interpret the image dataset* Apply Intel® Extension for Scikit-learn* patches to Principal Components Analysis (PCA), Kmeans,and DBSCAN algorithms and target GPU Library Dependencies: - **p...
from __future__ import print_function data_path = ['data'] # Notebook time start from datetime import datetime start_time = datetime.now() current_time = start_time.strftime("%H:%M:%S") print("Current Time =", current_time)
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Define image manipulation and Reading functions
from lab.Read_Transform_Images import *
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Actually read the images- [Back to Sections](Back_to_Sections)
resultsDict = {} #resultsDict = Read_Transform_Images(resultsDict,imagesFilenameList = imagesFilenameList) resultsDict = Read_Transform_Images(resultsDict) #resultsDict.keys()
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Display ImageGrid Random SamplingThis should give an idea of how closely or differently the various images appear. Notice that some of the collard lizard images have much differnet white balance and this will affect the clustering. For this dataset the images are clustered based on the similarity in RGB colorspace onl...
img_arr = [] ncols = 8 imageGrid=(ncols,3) for pil in random.sample(resultsDict['list_PIL_Images'], imageGrid[0]*imageGrid[1]) : img_arr.append(np.array(pil)) #displayImageGrid(img_arr, imageGrid=imageGrid) displayImageGrid2(img_arr, ncols=ncols)
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Review Python file prior to submission Set SYCL Device Context- [Back to Sections](Back-to-Sections)Paste this code in cell below and run it (twice) once to load, once to execute the cell:%load batch_clustering_Streamlined.py
%load batch_clustering_Streamlined.py
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Submit batch_clustering_Streamlined.py- [Back to Sections](Back_to_Sections)batch_clustering_Streamlined.py executed with a Python* command inside a shell script - run_clustering_streamlined.sh.run_clustering_streamlined.sh is submitted as a batch job to a node which has GPUs
#!python batch_kmeans.py # works on Windows ! chmod 755 q; chmod 755 run_clustering_streamlined.sh; if [ -x "$(command -v qsub)" ]; then ./q run_clustering_streamlined.sh; else ./run_clustering_streamlined.sh; fi
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Read Results of the Dictionary After GPU Computation- [Back to Sections](Back_to_Sections)
# read results from json file in results folder resultsDict = read_results_json() # get list_PIL_Images from Read_Tansform_Images resultsDict = Read_Transform_Images(resultsDict)
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Plot Kmeans Clusters Plot a histogram of the using GPU results- [Back to Sections](Back_to_Sections)
resultsDict.keys() #resultsDict = Compute_kmeans_db_histogram_labels(resultsDict, knee = 6, gpu_available = gpu_available) #knee = 5 counts = np.asarray(resultsDict['counts']) bins = np.asarray(resultsDict['bins']) plt.xlabel("Weight") plt.ylabel("Probability") plt.title("Histogram with Probability Plot}") slice = min(...
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Print Kmeans Related Data as a Sanity Check
print(resultsDict['bins']) print(resultsDict['counts']) resultsDict.keys()
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Display Similar ImagesVisually compare image which have been clustered by the allgorithm
clusterRank = 2 d = {i:cts for i, cts in enumerate(resultsDict['counts'])} sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse=True) id = sorted_d[clusterRank][0] indexCluster = np.where(np.asarray(resultsDict['km_labels']) == id )[0].tolist() img_arr = [] for idx in indexCluster: img_arr.append(np.a...
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
PlotPlot Seaborn Kmeans ClustersIndicates numbers of images that are close in color space
%matplotlib inline n_components = 4 columns = ['PC{:0d}'.format(c) for c in range(n_components)] data = pd.DataFrame(np.asarray(resultsDict['PCA_fit_transform'])[:,:n_components], columns = columns) #k_means = resultsDict['model'] data['cluster'] = resultsDict['km_labels'] data.head() # similarlyNamedImages = [9,6,6,...
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Find DBSCAN EPS parameterDensity-Based Spatial Clustering of Applications with Noise (DBSCAN) finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density.EPS: "epsilon" value in sklearn is the maximum distance between two samples for one to be considered ...
from sklearn.neighbors import NearestNeighbors PCA_images = resultsDict['PCA_fit_transform'] neighbors = NearestNeighbors(n_neighbors=2) #X = StandardScaler().fit_transform(PCA_images) neighbors_fit = neighbors.fit(PCA_images) distances, indices = neighbors_fit.kneighbors(PCA_images) distances = np.sort(distances, a...
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Use DBSCAN to find clusterswe will use initial estiamtes from KNN above (find elbow) to given initial trial for DBSCAN EPS values In the plot above, there is a plateau in the y values somewherre near 350 indicating that a cluster distance (aka EPS) might work well somewhere near this value. We used this value in the b...
#%%write_and_run lab/compute_DBSCANClusterRank.py def compute_DBSCANClusterRank(n, EPS): d = {index-1:int(cnt) for index, cnt in enumerate(counts )} sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse=True) for i in range(0, len(d)): idx = sorted_d[i][0] print('cluster = ', ...
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
DBSCAN Cluster PlotPlot a histogram of the using GPU results- [Back to Sections](Back_to_Sections) To indicate numbers of images in each cluster. color each point by its membership in a cluster
%matplotlib inline sns.set_context('notebook'); g = sns.pairplot(data[columns], hue="cluster", palette="Paired", diag_kws=dict(hue=None)); g.fig.suptitle("DBSCAN pairplot");
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials
Print Filenames of Outliers
print('Outlier/problematic images are: \n', [resultsDict['imagesFilenameList'][f] for f in list(data[data['cluster'] == -1].index)] )
_____no_output_____
MIT
03_scikit-learn-intelex_Image_Cluster/03_ImageClustering.ipynb
IntelSoftware/scikit-learn_essentials