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
Plot function f for all values of `x_new`. Run the code below.
# Run this code: %matplotlib inline import matplotlib.pyplot as plt plt.plot(x_new, f(x_new))
_____no_output_____
MIT
module-2/Intro-Scipy/your-code/main.ipynb
Skye-FY/daft-miami-0120-labs
Next create a function that will generate a cubic interpolation function. Name the function `g`.
# Your code here: # Run this code: plt.plot(x_new, g(x_new))
_____no_output_____
MIT
module-2/Intro-Scipy/your-code/main.ipynb
Skye-FY/daft-miami-0120-labs
Bonus Challenge - The Binomial DistributionThe binomial distribution allows us to calculate the probability of k successes in n trials for a random variable with two possible outcomes (which we typically label success and failure). The probability of success is typically denoted by p and the probability of failure is...
# Your code here:
_____no_output_____
MIT
module-2/Intro-Scipy/your-code/main.ipynb
Skye-FY/daft-miami-0120-labs
* Do a simulation for the last event: do a function that simulate 8 tries and return a 1 if the result is 5 exactly 3 times and 0 if not. Now launch your simulation.
# Your code here:
_____no_output_____
MIT
module-2/Intro-Scipy/your-code/main.ipynb
Skye-FY/daft-miami-0120-labs
* Launch 10 simulations and represent the result in a bar plot. Now launch 1000 simulations and represent it. What do you see?
# Your code here:
_____no_output_____
MIT
module-2/Intro-Scipy/your-code/main.ipynb
Skye-FY/daft-miami-0120-labs
Plot data from example patient's time-series
df = pd.read_csv('/tmp/mp_data.csv') # load in this patient's deathtime from the actual experiment df_offset = pd.read_csv('/tmp/mp_death.csv') # get censoring information df_censor = pd.read_csv('/tmp/mp_censor.csv')
_____no_output_____
MIT
notebooks/mp-plot-patient-data.ipynb
alistairewj/mortality-prediction
Experiment A: First 24 hours
# define the patient iid = 200001 iid2 = 200019 T_WINDOW = 24 time_dict = {iid: 24, iid2: 24} df_pat = df.loc[df['icustay_id']==iid, :].set_index('hr') deathtime = df_offset.loc[df_offset['icustay_id']==iid, 'deathtime_hours'].values # Two subplots, the axes array is 1-d f, axarr = plt.subplots(2, sharex=True, figsi...
_____no_output_____
MIT
notebooks/mp-plot-patient-data.ipynb
alistairewj/mortality-prediction
Experiment B: Random time
# generate a random time dictionary T_WINDOW=4 df_tmp=df_offset.copy().merge(df_censor, how='left', left_on='icustay_id', right_on='icustay_id') time_dict = mp.generate_times(df_tmp, T=2, seed=111, censor=True) # define the patient iid = 200001 iid2 = 200019 df_pat = df.loc[df['icustay_id']==iid, :].set_index('hr')...
_____no_output_____
MIT
notebooks/mp-plot-patient-data.ipynb
alistairewj/mortality-prediction
Both 24 hours and 4 hour window
# generate a random time dictionary T_WINDOW=4 df_tmp=df_offset.copy().merge(df_censor, how='left', left_on='icustay_id', right_on='icustay_id') time_dict = mp.generate_times(df_tmp, T=2, seed=111, censor=True) # define the patient iid = 200001 iid2 = 200019 df_pat = df.loc[df['icustay_id']==iid, :].set_index('hr')...
_____no_output_____
MIT
notebooks/mp-plot-patient-data.ipynb
alistairewj/mortality-prediction
Fairseq in Amazon SageMaker: Pre-trained English to French translation modelIn this notebook, we will show you how to serve an English to French translation model using pre-trained model provided by the [Fairseq toolkit](https://github.com/pytorch/fairseq) PermissionsRunning this notebook requires permissions in addit...
%%sh wget https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 tar xvjf wmt14.v2.en-fr.fconv-py.tar.bz2 > /dev/null cd wmt14.en-fr.fconv-py mv model.pt checkpoint_best.pt tar czvf wmt14.en-fr.fconv-py.tar.gz checkpoint_best.pt dict.en.txt dict.fr.txt bpecodes README.md > /dev/null
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
The pre-trained model has been downloaded and converted. The next step is upload the data to Amazon S3 in order to make it available for running the inference. Upload data to Amazon S3
import sagemaker sagemaker_session = sagemaker.Session() region = sagemaker_session.boto_session.region_name account = sagemaker_session.boto_session.client("sts").get_caller_identity().get("Account") bucket = sagemaker_session.default_bucket() prefix = "sagemaker/DEMO-pytorch-fairseq/pre-trained-models" role = sage...
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
Build Fairseq serving containerNext we need to register a Docker image in Amazon SageMaker that will contain the Fairseq code and that will be pulled at inference time to perform the of the precitions from the pre-trained model we downloaded.
%%sh chmod +x create_container.sh ./create_container.sh pytorch-fairseq-serve
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
The Fairseq serving image has been pushed into Amazon ECR, the registry from which Amazon SageMaker will be able to pull that image and launch both training and prediction. Hosting the pre-trained model for inferenceWe first needs to define a base JSONPredictor class that will help us with sending predictions to the ...
from sagemaker.predictor import RealTimePredictor, json_serializer, json_deserializer class JSONPredictor(RealTimePredictor): def __init__(self, endpoint_name, sagemaker_session): super(JSONPredictor, self).__init__( endpoint_name, sagemaker_session, json_serializer, json_deserializer ...
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
We can now use the Model class to deploy the model artificats (the pre-trained model), and deploy it on a CPU instance. Let's use a `ml.m5.xlarge`.
from sagemaker import Model algorithm_name = "pytorch-fairseq-serve" image = "{}.dkr.ecr.{}.amazonaws.com/{}:latest".format(account, region, algorithm_name) model = Model( model_data=trained_model_location, role=role, image=image, predictor_cls=JSONPredictor, ) predictor = model.deploy(initial_instanc...
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
Now it's your time to play. Input a sentence in English and get the translation in French by simply calling predict.
import html result = predictor.predict("I love translation") # Some characters are escaped HTML-style requiring to unescape them before printing print(html.unescape(result))
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
Once you're done with getting predictions, remember to shut down your endpoint as you no longer need it. Delete endpoint
model.sagemaker_session.delete_endpoint(predictor.endpoint)
_____no_output_____
Apache-2.0
advanced_functionality/fairseq_translation/fairseq_sagemaker_pretrained_en2fr.ipynb
Amirosimani/amazon-sagemaker-examples
SSD Evaluation TutorialThis is a brief tutorial that explains how compute the average precisions for any trained SSD model using the `Evaluator` class. The `Evaluator` computes the average precisions according to the Pascal VOC pre-2010 or post-2010 detection evaluation algorithms. You can find details about these com...
from keras import backend as K from keras.models import load_model from keras.optimizers import Adam from imageio import imread import numpy as np from matplotlib import pyplot as plt from models.keras_ssd300 import ssd_300 from keras_loss_function.keras_ssd_loss import SSDLoss from keras_layers.keras_layer_AnchorBoxe...
_____no_output_____
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
1. Load a trained SSDEither load a trained model or build a model and load trained weights into it. Since the HDF5 files I'm providing contain only the weights for the various SSD versions, not the complete models, you'll have to go with the latter option when using this implementation for the first time. You can then...
# 1: Build the Keras model K.clear_session() # Clear previous models from memory. model = ssd_300(image_size=(img_height, img_width, 3), n_classes=n_classes, mode=model_mode, l2_regularization=0.0005, scales=[0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05], # Th...
WARNING: Logging before flag parsing goes to stderr. W1121 16:15:06.265161 140201693157120 deprecation_wrapper.py:119] From /home/vision/msmith/localDrive/msmith/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:95: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_def...
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
Or 1.2. Load a trained modelWe set `model_mode` to 'inference' above, so the evaluator expects that you load a model that was built in 'inference' mode. If you're loading a model that was built in 'training' mode, change the `model_mode` parameter accordingly.
# TODO: Set the path to the `.h5` file of the model to be loaded. model_path = 'ssd300_dropout_pascal_07+12_epoch-114_loss-4.3685_val_loss-4.5034.h5' # We need to create an SSDLoss object in order to pass that to the model loader. ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0) K.clear_session() # Clear previous model...
_____no_output_____
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
2. Create a data generator for the evaluation datasetInstantiate a `DataGenerator` that will serve the evaluation dataset during the prediction phase.
ROOT_PATH = '/usr/local/data/msmith/APL/Datasets/PASCAL/' # The directories that contain the images. VOC_2007_images_dir = p.join(ROOT_PATH,'VOCdevkit/VOC2007/JPEGImages/') VOC_2012_images_dir = p.join(ROOT_PATH,'VOCdevkit/VOC2012/JPEGImages/') # The directories that contain the annotations. VOC_2007_annotat...
Processing image set 'val.txt': 100%|██████████| 5823/5823 [00:43<00:00, 134.57it/s] Loading images into memory: 100%|██████████| 5823/5823 [01:06<00:00, 87.20it/s]
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
3. Run the evaluationNow that we have instantiated a model and a data generator to serve the dataset, we can set up the evaluator and run the evaluation.The evaluator is quite flexible: It can compute the average precisions according to the Pascal VOC pre-2010 algorithm, which samples 11 equidistant points of the prec...
evaluator = Evaluator(model=model, n_classes=n_classes, data_generator=dataset, model_mode=model_mode) results = evaluator(img_height=img_height, img_width=img_width, batch_size=2, data_generat...
Number of images in the evaluation dataset: 5823 Producing predictions batch-wise: 100%|██████████| 2912/2912 [02:39<00:00, 11.19it/s] Matching predictions to ground truth, class 1/20.: 100%|██████████| 9115/9115 [00:00<00:00, 21509.26it/s] Matching predictions to ground truth, class 2/20.: 100%|██████████| 4937/4937 ...
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
4. Visualize the resultsLet's take a look:
for i in range(1, len(average_precisions)): print("{:<14}{:<6}{}".format(classes[i], 'AP', round(average_precisions[i], 3))) print() print("{:<14}{:<6}{}".format('','mAP', round(mean_average_precision, 3))) m = max((n_classes + 1) // 2, 2) n = 2 fig, cells = plt.subplots(m, n, figsize=(n*8,m*8)) for i in range(m):...
_____no_output_____
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
5. Advanced use`Evaluator` objects maintain copies of all relevant intermediate results like predictions, precisions and recalls, etc., so in case you want to experiment with different parameters, e.g. different IoU overlaps, there is no need to compute the predictions all over again every time you make a change to a ...
evaluator.get_num_gt_per_class(ignore_neutral_boxes=True, verbose=False, ret=False) evaluator.match_predictions(ignore_neutral_boxes=True, matching_iou_threshold=0.5, border_pixels='include', ...
_____no_output_____
Apache-2.0
ssd300_evaluation.ipynb
mdsmith-cim/ssd_keras
[![Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb) Tutorial 2: Differential Equations**Week 0, Day 4: Calculus****By Neuromatch Academy**__Content...
# @title Video 1: Why do we care about differential equations? from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bi...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
--- Setup
# Imports import numpy as np import matplotlib.pyplot as plt # @title Figure Settings import IPython.display as ipd from matplotlib import gridspec import ipywidgets as widgets # interactive display %config InlineBackend.figure_format = 'retina' # use NMA plot style plt.style.use("https://raw.githubusercontent.com/...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
--- Section 1: Population differential equation
# @title Video 2: Population differential equation from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/p...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
This video covers our first example of a differential equation: a differential equation which models the change in population. Click here for text recap of video To get an intuitive feel of a differential equations, we will start with a population differential equation, which models the change in population [1], that i...
# @markdown Execute the code to plot the rate of change of population as a function of population p = np.arange(0, 100, 0.1) with plt.xkcd(): dpdt = 0.3*p fig = plt.figure(figsize=(6, 4)) plt.plot(p, dpdt) plt.xlabel(r'Population $p(t)$ (millions)') plt.ylabel(r'$\frac{d}{dt}p(t)=\alpha p(t)$') plt.show()...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 1.1: Exact solution of the population equation Section 1.1.1: Initial conditionThe linear population differential equation is known as an initial value differential equation because we need an initial population value to solve it. Here we will set our initial population at time 0 to 1:\begin{align*}&p(0)=1.\\...
# @markdown Execute code to plot the exact solution t = np.arange(0, 10, 0.1) # Time from 0 to 10 years in 0.1 steps with plt.xkcd(): p = np.exp(0.3 * t) fig = plt.figure(figsize=(6, 4)) plt.plot(t, p) plt.ylabel('Population (millions)') plt.xlabel('time (years)') plt.show()
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 1.2: Parameters of the differential equation*Estimated timing to here from start of tutorial: 12 min*One of the goals when designing a differential equation is to make it generalisable. Which means that the differential equation will give reasonable solutions for different countries with different birth rates ...
# @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( alpha=widgets.FloatSlider(.3, min=-1., max=1., step=.1, layout=my_layout) ) def Pop_widget(alpha): plot_dPdt(alpha=alpha) plt.show() # to_remove explanation """ 1. Negative values of alpha result in...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
The population differential equation is an over-simplification and has some very obvious limitations: 1. Population growth is not exponential as there are limited number of resources so the population will level out at some point.2. It does not include any external factors on the populations like weather, predators and...
# @title Video 3: The leaky integrate and fire model from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
This video covers the Leaky Integrate and Fire model (a linear differential equation which describes the membrane potential of a single neuron). Click here for text recap of full LIF equation from video The Leaky Integrate and Fire Model is a linear differential equation that describes the membrane potential ($V$) of a...
# @markdown Make sure you execute this cell to plot the relationship between dV/dt and V # Parameter definition E_L = -75 tau_m = 10 # Range of Values of V V = np.arange(-90, 0, 1) dV = -(V - E_L) / tau_m with plt.xkcd(): fig = plt.figure(figsize=(6, 4)) plt.plot(V, dV) plt.hlines(0, min(V), max(V), colors='bl...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 2.1.1: Exact Solution of the LIF model without inputThe LIF model has the exact solution:\begin{align*}V(t)=&\ E_L+(V_{reset}-E_L)e^{\frac{-t}{\tau_m}}\\\end{align*}where $\tau_m$ is the time constant, $V$ is the membrane potential, $E_L$ is the resting potential, and $V_{reset}$ is the initial membrane poten...
#@markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( V_reset=widgets.FloatSlider(-77., min=-91., max=-61., step=2, layout=my_layout) ) def V_reset_widget(V_reset): plot_V_no_input(V_reset) # to_remove explanation """ 1. Initi...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 2.2: LIF with input*Estimated timing to here from start of tutorial: 24 min*We will re-introduce the input $I$ and membrane resistance $R_m$ giving the original equation:\begin{align}\tau_m\frac{dV}{dt} = -(V-E_L) + \color{blue}{R_mI}\,\end{align}The input can be other neurons or sensory information. Interact...
# @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( I=widgets.FloatSlider(3., min=0., max=20., step=2, layout=my_layout) ) def Pop_widget(I): plot_dVdt(I=I) plt.show() # to_remove explanation """ dV/dt becomes bigger and ...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 2.2.1: LIF exact solutionThe LIF with a constant input has a known exact solution:\begin{align*}V(t)=&\ E_L+R_mI+(V_{reset}-E_L-R_mI)e^{\frac{-t}{\tau_m}}\\\text{which is written as:}\\\begin{matrix}\text{"Current membrane} \\ \text{potential"}\end{matrix}=&\text{"Resting potential"}+\begin{matrix}\text{"Reset...
# @markdown Make sure you execute this cell to see the exact solution dt = 0.5 t_rest = 0 t = np.arange(0, 1000, dt) tau_m = 10 R_m = 10 V_reset = E_L = -75 I = 10 V = E_L + R_m*I + (V_reset - E_L - R_m*I) * np.exp(-(t)/tau_m) with plt.xkcd(): fig = plt.figure(figsize=(6, 4)) plt.plot(t,V) plt.ylabel('V (mV...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 2.3: Maths is one thing, but neuroscience matters*Estimated timing to here from start of tutorial: 30 min*
# @title Video 4: Adding firing to the LIF from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.ht...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
This video first recaps the introduction of input to the leaky integrate and fire model and then delves into how we add spiking behavior (or firing) to the model. Click here for text recap of video While the mathematics of the exact solution is exact, it is not biologically valid as a neuron spikes and definitely does ...
# @markdown Make sure you execute this cell to be able to hear the neuron I = 3 t = np.arange(0, 1000, dt) Spike, Spike_time, V = Exact_Integrate_and_Fire(I, t) plot_IF(t, V, I, Spike_time) ipd.Audio(V, rate=len(V))
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Manipulate the input into the LIF to see the impact of input on the firing pattern (rate).* What is the effect of $I$ on spiking?* Is this biologically valid?
# @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( I=widgets.FloatSlider(3, min=2.0, max=4., step=.1, layout=my_layout) ) def Pop_widget(I): Spike, Spike_time, V = Exact_Integrate_and_Fire(I, t) plot_IF(t, V, I, Spike_time)...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
Section 2.4 Firing Rate as a function of Input*Estimated timing to here from start of tutorial: 38 min*The firing frequency of a neuron plotted as a function of current is called an input-output curve (F–I curve). It is also known as a transfer function, which you came across in the previous tutorial. This function is...
# @markdown *Execture this cell to visualize the FI curve* I_range = np.arange(2.0, 4.0, 0.1) Spike_rate = np.ones(len(I_range)) for i, I in enumerate(I_range): Spike_rate[i], _, _ = Exact_Integrate_and_Fire(I, t) with plt.xkcd(): fig = plt.figure(figsize=(6, 4)) plt.plot(I_range,Spike_rate) plt.xlabel('Input...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
The LIF model is a very nice differential equation to start with in computational neuroscience as it has been used as a building block for many papers that simulate neuronal response.__Strengths of LIF model:__+ Has an exact solution;+ Easy to interpret;+ Great to build network of neurons.__Weaknesses of the LIF model...
# @title Video 5: Summary from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page=...
_____no_output_____
CC-BY-4.0
tutorials/W0D4_Calculus/W0D4_Tutorial2.ipynb
ofou/course-content
K-means clustering demo 1. Different distance metrics
from math import sqrt def manhattan(v1,v2): res=0 dimensions=min(len(v1),len(v2)) for i in range(dimensions): res+=abs(v1[i]-v2[i]) return res def euclidean(v1,v2): res=0 dimensions=min(len(v1),len(v2)) for i in range(dimensions): res+=pow(abs(v1[i]-v2[i]),2) return...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
2. K-means clustering algorithm
import random # k-means clustering def kcluster(rows,distance=euclidean,k=4): # Determine the minimum and maximum values for each point ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] # Create k randomly placed centroids clusters=[[random.random(...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
3. Toy demo: clustering papers by title 3.1. Data preparationThe input is a list of Computer Science paper titles from file [titles.txt](titles.txt).
file_name = "titles.txt" f = open(file_name, "r", encoding="utf-8") i = 0 for line in f: print("document", i, ": ", line.strip()) i += 1
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
To compare documents written in Natural Language, we need to decide how to decide which attributes of a document are important. The simplest possible model is called a **bag of words**: that is we consider each word in a document as a separate and independent dimension. First, we collect all different words occuring a...
import re # Returns dictionary of word counts for a text def get_word_counts(text, all_words): wc={} words = get_words(text) # Loop over all the entries for word in words: if (word not in stopwords) and (word in all_words): wc[word] = wc.get(word,0)+1 return wc # splits text ...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
Some words of the document should be ignored. These are words that are very commonly used in all documents no matter the topic of the document: ''the'', ''it'', ''and'' etc. These words are called **stop words**. Which words to consider as stop words is application-dependent. One of possible stop words collection is gi...
stop_words_file = "stop_words.txt" f = open(stop_words_file, "r", encoding="utf-8") stopwords = [] for line in f: stopwords.append(line.strip()) f.close() print(stopwords[:20])
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
We collect all unique words and for each document we will count how many times each word is present.
file_name = "titles.txt" f = open(file_name, "r", encoding="utf-8") documents = [] doc_id = 1 all_words = {} # transfer content of a file into a list of lines lines = [line for line in f] # create a dictionary of all words and their total counts for line in lines: doc_words = get_words(line) for w in doc_wor...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
Now we want to convert each document into a numeric vector:
out = open(file_name.split('.')[0] + "_vectors.txt", "w") # write a header which contains the words themselves for w in unique_words: out.write('\t' + w) out.write('\n') # print_word_matrix to file for i in range(len(documents)): vector = get_word_vector(unique_words, documents[i][1]) out.write(documents[...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
Our data now looks like this matrix:
doc_vectors_file = "titles_vectors.txt" f = open(doc_vectors_file, "r", encoding="utf-8") s = f.read() print(s) # This function will read document vectors file and produce 2D data matrix, # plus the names of the rows and the names of the columns. def read_vector_file(file_name): f = open(file_name) lines=[line...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
As the result of all this, we have the matrix where the rows are document vectors.Each vector dimension represents a unique word in the collection.The value in each dimension represents the count of this word in a particular document. 3.2. Clustering documents Performing k-means clustering.
doc_vectors_file = "titles_vectors.txt" docs,words,data=read_vector_file(doc_vectors_file) num_clusters=2 print('Searching for {} clusters:'.format(num_clusters)) clust=kcluster(data,distance=pearson,k=num_clusters) print() print ('Document clusters') print ('=================') for i in range(num_clusters): prin...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
Does this grouping make sense?
for d in documents: print(d)
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
3.3. Clustering words by their occurrence in documentsWe may consider that the words are similar if they occur in the same document. We say that the words are connected - they belong to the same topic, they occur in a similar context.If we want to cluster words by their occurrences in the documents, all we need to do ...
rdata=rotatematrix(data) num_clusters = 3 print ('Grouping words into {} clusters:'.format(num_clusters)) clust=kcluster(rdata,distance=cosine,k=num_clusters) print() print ('word clusters:') print("=============") for i in range(num_clusters): print("cluster {}".format(i+1)) print ([words[r] for r in clust[i]]...
_____no_output_____
MIT
kmeans_clustering_demo.ipynb
lyb770/labs_ml_clustering
Using Named Entity Recognition (NER) **Named entities** are noun phrases that refer to specific locations, people, organizations, and so on. With **named entity recognition**, you can find the named entities in your texts and also determine what kind of named entity they are.Here’s the list of named entity types from ...
import nltk from nltk.tokenize import word_tokenize lotr_quote = "It's a dangerous business, Frodo, going out your door." words_in_lotr_quote = word_tokenize(lotr_quote) print(words_in_lotr_quote) lotr_pos_tags = nltk.pos_tag(words_in_lotr_quote) print(lotr_pos_tags) tree = nltk.ne_chunk(lotr_pos_tags)
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
Now take a look at the visual representation:
tree.draw()
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
Here’s what you get: See how Frodo has been tagged as a PERSON? You also have the option to use the parameter binary=True if you just want to know what the named entities are but not what kind of named entity they are:
tree = nltk.ne_chunk(lotr_pos_tags, binary=True) tree.draw()
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
Now all you see is that Frodo is an NE: That’s how you can identify named entities! But you can take this one step further and extract named entities directly from your text. Create a string from which to extract named entities. You can use this quote from The War of the Worlds:
quote = """ Men like Schiaparelli watched the red planet—it is odd, by-the-bye, that for countless centuries Mars has been the star of war—but failed to interpret the fluctuating appearances of the markings they mapped so well. All that time the Martians must have been getting ready. During the opposition of 1894 a gr...
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
Now create a function to extract named entities:
def extract_ne(quote): words = word_tokenize(quote, language='english') tags = nltk.pos_tag(words) tree = nltk.ne_chunk(tags, binary=True) tree.draw() return set( " ".join(i[0] for i in t) for t in tree if hasattr(t, "label") and t.label() == "NE" )
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
With this function, you gather all named entities, with no repeats. In order to do that, you tokenize by word, apply part of speech tags to those words, and then extract named entities based on those tags. Because you included binary=True, the named entities you’ll get won’t be labeled more specifically. You’ll just kn...
extract_ne(quote)
_____no_output_____
MIT
NLP/8.Using Named Entity Recognition (NER).ipynb
SuryaReginaAA/Learn
Closed-Loop EvaluationIn this notebook you are going to evaluate Urban Driver to control the SDV with a protocol named *closed-loop* evaluation.**Note: this notebook assumes you've already run the [training notebook](./train.ipynb) and stored your model successfully (or that you have stored a pre-trained one).****Note...
import matplotlib.pyplot as plt import numpy as np import torch from prettytable import PrettyTable from l5kit.configs import load_config_data from l5kit.data import LocalDataManager, ChunkedDataset from l5kit.dataset import EgoDatasetVectorized from l5kit.vectorization.vectorizer_builder import build_vectorizer fro...
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Prepare data path and load cfgBy setting the `L5KIT_DATA_FOLDER` variable, we can point the script to the folder where the data lies.Then, we load our config file with relative paths and other configurations (rasteriser, training params ...).
# set env variable for data from l5kit.data import get_dataset_path os.environ["L5KIT_DATA_FOLDER"], project_path = get_dataset_path() dm = LocalDataManager(None) # get config cfg = load_config_data("./config.yaml")
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Load the model
model_path = project_path + "/urban_driver_dummy_model.pt" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = torch.load(model_path).to(device) model = model.eval() torch.set_grad_enabled(False)
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Load the evaluation dataDifferently from training and open loop evaluation, this setting is intrinsically sequential. As such, we won't be using any of PyTorch's parallelisation functionalities.
# ===== INIT DATASET eval_cfg = cfg["val_data_loader"] eval_zarr = ChunkedDataset(dm.require(eval_cfg["key"])).open() vectorizer = build_vectorizer(cfg, dm) eval_dataset = EgoDatasetVectorized(cfg, eval_zarr, vectorizer) print(eval_dataset)
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Define some simulation propertiesWe define here some common simulation properties such as the length of the simulation and how many scene to simulate.**NOTE: these properties have a significant impact on the execution time. We suggest you to increase them only if your setup includes a GPU.**
num_scenes_to_unroll = 10 num_simulation_steps = 50
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Closed-loop simulationWe define a closed-loop simulation that drives the SDV for `num_simulation_steps` steps while using the log-replayed agents.Then, we unroll the selected scenes.The simulation output contains all the information related to the scene, including the annotated and simulated positions, states, and tra...
# ==== DEFINE CLOSED-LOOP SIMULATION sim_cfg = SimulationConfig(use_ego_gt=False, use_agents_gt=True, disable_new_agents=True, distance_th_far=500, distance_th_close=50, num_simulation_steps=num_simulation_steps, start_frame_index=0, show_info=True) sim_loop = Clos...
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Closed-loop metrics**Note: for a detailed explanation of CLE metrics, please refer again to our [planning notebook](../planning/closed_loop_test.ipynb)**
metrics = [DisplacementErrorL2Metric(), DistanceToRefTrajectoryMetric(), CollisionFrontMetric(), CollisionRearMetric(), CollisionSideMetric()] validators = [RangeValidator("displacement_error_l2", DisplacementErrorL2Metric, max_value=30), RangeValidator("distan...
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Quantitative evaluationWe can now compute the metric evaluation, collect the results and aggregate them.
cle_evaluator.evaluate(sim_outs) validation_results = cle_evaluator.validation_results() agg = ValidationCountingAggregator().aggregate(validation_results) cle_evaluator.reset()
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Reporting errors from the closed-loopWe can now report the metrics and plot them.
fields = ["metric", "value"] table = PrettyTable(field_names=fields) values = [] names = [] for metric_name in agg: table.add_row([metric_name, agg[metric_name].item()]) values.append(agg[metric_name].item()) names.append(metric_name) print(table) plt.bar(np.arange(len(names)), values) plt.xticks(np.ara...
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
Qualitative evaluation Visualise the closed-loopWe can visualise the scenes we have obtained previously. **The policy is now in full control of the SDV as this moves through the annotated scene.**
output_notebook() mapAPI = MapAPI.from_cfg(dm, cfg) for sim_out in sim_outs: # for each scene vis_in = simulation_out_to_visualizer_scene(sim_out, mapAPI) show(visualize(sim_out.scene_id, vis_in))
_____no_output_____
Apache-2.0
examples/urban_driver/closed_loop_test.ipynb
ronamit/l5kit
import torch import numpy as np from matplotlib import pyplot as plt torch.manual_seed(0) np.random.seed(0) class Environment: def __init__(self): self.constant_function_details = {'value':np.random.randint(10, 90)} self.uniform_function_details = {'min': 25, 'max': 75} self.gaussian_function_detai...
_____no_output_____
MIT
DQN_practice.ipynb
AmanPriyanshu/Reinforcement-Learning
Model:
def model_generator(): model = torch.nn.Sequential( torch.nn.Linear(2, 4), torch.nn.ReLU(), torch.nn.Linear(4, 8), torch.nn.ReLU(), torch.nn.Linear(8, 4), torch.nn.Softmax(dim=1), ) return model class Agent: def __init__(self): sel...
_____no_output_____
MIT
DQN_practice.ipynb
AmanPriyanshu/Reinforcement-Learning
Trapezoidal Method
# params stored in txt sys = MultiModeSystem(params={"dir":"data/"}) x_0 = np.array([1,0,0,1]) ts = np.linspace(0, 10, 101) X = sys.trapezoidal(x_0, ts) fig, ax = plot_full_evolution(X, ts, labels=["$q_a$","$p_a$","$q_b$","$p_b$"]) ax.legend()
_____no_output_____
MIT
demos/basic/multimode/MultiModeSystem.ipynb
Phionx/quantumnetworks
Forward Euler
# params stored in txt sys = MultiModeSystem(params={"dir":"data/"}) x_0 = np.array([1,0,0,1]) ts = np.linspace(0, 10, 10001) X = sys.forward_euler(x_0, ts) fig, ax = plot_full_evolution(X, ts, labels=["$q_a$","$p_a$","$q_b$","$p_b$"]) ax.legend() u = sys.eval_u(0) sys.eval_Jf(x_0, u) sys.eval_Jf_numerical(x_0, u) # pa...
[[-9.42477796e-03 6.28318531e+00 0.00000000e+00 1.25663706e-02 0.00000000e+00 0.00000000e+00] [-6.28318531e+00 -9.42477796e-03 -1.25663706e-02 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 1.25663706e-02 -2.19911486e-02 1.25663706e+01 0.00000000e+00 1.25663706e-02] [-1.25663706e-02...
MIT
demos/basic/multimode/MultiModeSystem.ipynb
Phionx/quantumnetworks
Linearization
omegas = [2*np.pi*1,2*np.pi*2,2*np.pi*1] kappas = [2*np.pi*0.001,2*np.pi*0.005,2*np.pi*0.001] gammas = [2*np.pi*0.002,2*np.pi*0.002,2*np.pi*0.002] kerrs = [2*np.pi*0.001, 2*np.pi*0.001, 2*np.pi*0.001] couplings = [[0,1,2*np.pi*0.002],[1,2,2*np.pi*0.002]] sys = MultiModeSystem(params={"omegas":omegas, "kappas":kappas, "...
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in true_divide
MIT
demos/basic/multimode/MultiModeSystem.ipynb
Phionx/quantumnetworks
Getting Started with Azure Machine LearningAzure Machine Learning (*Azure ML*) is a cloud-based service for creating and managing machine learning solutions. It's designed to help data scientists leverage their existing data processing and model development skills and frameworks, and help them scale their workloads to...
import azureml.core print("Ready to use Azure ML", azureml.core.VERSION)
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
Connect to Your WorkspaceAll experiments and associated resources are managed within you Azure ML workspace. You can connect to an existing workspace, or create a new one using the Azure ML SDK.In most cases, you should store the workspace configuration in a JSON configuration file. This makes it easier to reconnect w...
from azureml.core import Workspace ws = Workspace.from_config() print(ws.name, "loaded")
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
Run an ExperimentOne of the most fundamentals tasks that data scientists need to perform is to create and run experiments that process and analyze data. In this exercise, you'll learn how to use an Azure ML *experiment* to run Python code and record values extracted from data. In this case, you'll use a simple dataset...
from azureml.core import Experiment import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # Create an Azure ML experiment in your workspace experiment = Experiment(workspace = ws, name = "diabetes-experiment") # Start logging data from the experiment run = experiment.start_logging() print("Starting ...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
View Experiment ResultsAfter the experiment has been finished, you can use the **run** object to get information about the run and its outputs:
import json # Get run details details = run.get_details() print(details) # Get logged metrics metrics = run.get_metrics() print(json.dumps(metrics, indent=2)) # Get output files files = run.get_file_names() print(json.dumps(files, indent=2))
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
In Jupyter Notebooks, you can use the **RunDetails** widget to get a better visualization of the run details, while the experiment is running or after it has finished.
from azureml.widgets import RunDetails RunDetails(run).show()
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
Note that the **RunDetails** widget includes a link to view the run in Azure Machine Learning studio. Click this to open a new browser tab with the run details (you can also just open [Azure Machine Learning studio](https://ml.azure.com) and find the run on the **Experiments** page). When viewing the run in Azure Machi...
import os, shutil # Create a folder for the experiment files folder_name = 'diabetes-experiment-files' experiment_folder = './' + folder_name os.makedirs(folder_name, exist_ok=True) # Copy the data file into the experiment folder shutil.copy('data/diabetes.csv', os.path.join(folder_name, "diabetes.csv"))
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
Now we'll create a Python script containing the code for our experiment, and save it in the experiment folder.> **Note**: running the following cell just *creates* the script file - it doesn't run it!
%%writefile $folder_name/diabetes_experiment.py from azureml.core import Run import pandas as pd import os # Get the experiment run context run = Run.get_context() # load the diabetes dataset data = pd.read_csv('diabetes.csv') # Count the rows and log the result row_count = (len(data)) run.log('observations', row_co...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
This code is a simplified version of the inline code used before. However, note the following:- It uses the `Run.get_context()` method to retrieve the experiment run context when the script is run.- It loads the diabetes data from the folder where the script is located.- It creates a folder named **outputs** and writes...
import os import sys from azureml.core import Experiment, RunConfiguration, ScriptRunConfig from azureml.widgets import RunDetails # create a new RunConfig object experiment_run_config = RunConfiguration() # Create a script config src = ScriptRunConfig(source_directory=experiment_folder, script...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
As before, you can use the widget or the link to the experiment in [Azure Machine Learning studio](https://ml.azure.com) to view the outputs generated by the experiment, and you can also write code to retrieve the metrics and files it generated:
# Get logged metrics metrics = run.get_metrics() for key in metrics.keys(): print(key, metrics.get(key)) print('\n') for file in run.get_file_names(): print(file)
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
View Experiment Run HistoryNow that you've run experiments multiple times, you can view the history in [Azure Machine Learning studio](https://ml.azure.com) and explore each logged run. Or you can retrieve an experiment by name from the workspace and iterate through its runs using the SDK:
from azureml.core import Experiment, Run diabetes_experiment = ws.experiments['diabetes-experiment'] for logged_run in diabetes_experiment.get_runs(): print('Run ID:', logged_run.id) metrics = logged_run.get_metrics() for key in metrics.keys(): print('-', key, metrics.get(key))
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
Use MLflowMLflow is an open source platform for managing machine learning processes. It's commonly (but not exclusively) used in Databricks environments to coordinate experiments and track metrics. In Azure Machine Learning experiments, you can use MLflow to track metrics instead of the native log functionality if you...
from azureml.core import Experiment import pandas as pd import mlflow # Set the MLflow tracking URI to the workspace mlflow.set_tracking_uri(ws.get_mlflow_tracking_uri()) # Create an Azure ML experiment in your workspace experiment = Experiment(workspace=ws, name='diabetes-mlflow-experiment') mlflow.set_experiment(ex...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
After running the code above, you can use the link that is displayed to view the experiment in Azure Machine Learning studio. Then select the latest run of tghe experiment and view it **Metrics** tab to see the logged metric. Use MLflow in an Experiment ScriptYou can also use MLflow to track metrics in an experiment sc...
import os, shutil # Create a folder for the experiment files folder_name = 'mlflow-experiment-files' experiment_folder = './' + folder_name os.makedirs(folder_name, exist_ok=True) # Copy the data file into the experiment folder shutil.copy('data/diabetes.csv', os.path.join(folder_name, "diabetes.csv")) %%writefile $f...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
When you use MLflow tracking in an Azure ML experiment script, the MLflow tracking URI is set automatically when you start the experiment run. However, the environment in which the script is to be run must include the required **mlflow** packages.
from azureml.core import Experiment, RunConfiguration, ScriptRunConfig from azureml.core.conda_dependencies import CondaDependencies from azureml.widgets import RunDetails # create a new RunConfig object experiment_run_config = RunConfiguration() # Ensure the required packages are installed packages = CondaDependenci...
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
As usual, you can get the logged metrics from the experiment run when it's finished.
# Get logged metrics metrics = run.get_metrics() for key in metrics.keys(): print(key, metrics.get(key))
_____no_output_____
MIT
labs/Getting_Started_with_Azure_ML.ipynb
PeakIndicatorsHub/Getting-Started-On-Azure-ML
IntroductionImplementation of the cTAKES BoW method with relation pairs (f.e. CUI-Relationship-CUI) (added to the BoW cTAKES orig. pairs (Polarity-CUI)), evaluated against the annotations from: > Gehrmann, Sebastian, et al. "Comparing deep learning and concept extraction based methods for patient phenotyping from clin...
# imported packages import multiprocessing import collections import itertools import re import os # xml and xmi from lxml import etree # arrays and dataframes import pandas import numpy from pandasql import sqldf # classifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.ensemble import G...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Define variables and parameters
# variables and parameters # filenames input_directory = '../data/interim/cTAKES_output' input_filename = '../data/raw/annotations.csv' results_filename = '../reports/ctakes_relationgram_bow_tfidf_results.csv' plot_filename_1 = '../reports/ctakes_relationgram_bow_tfidf_boxplot_1.png' plot_filename_2 = '../reports/ctake...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Load and prepare data Load and parse xmi data
%load_ext ipycache %%cache --read 2.6-JS-ctakes-relationgram-bow-tfidf_cache.pkl X def ctakes_xmi_to_df(xmi_path): records = [] tree = etree.parse(xmi_path) root = tree.getroot() mentions = [] for mention in root.iterfind('*[@{http://www.omg.org/XMI}id][@typeID][@polarity]'): if 'on...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Load annotations and classification data
# read and parse csv file data = pandas.read_csv(input_filename) # data = data[0:100] # for testing # X = X[0:100] # for testing data.head() # groups: the subject ids # used in order to ensure that # "patients’ notes stay within the set, so that all discharge notes in the # test set are from patients not previously...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Define classifiers
# dictionary of classifiers (sklearn estimators) classifiers = collections.OrderedDict() def tokenizer(text): pattern = r'[\s]+' # match any sequence of whitespace characters repl = r' ' # replace with space temp_text = re.sub(pattern, repl, text) return temp_text.lower().split(' ') # lower-case and ...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Run and evaluate
results = evaluation.run_evaluation(X=X, y=y, groups=groups, conditions=conditions, classifiers=classifiers, n_splits=n_splits, ...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
Save and plot results
# save results results_df = pandas.DataFrame(results) results_df.to_csv(results_filename) results_df.head(100) ## load results for plotting # import pandas # results = pandas.read_csv('output/results.csv') # plot and save axs = results_df.groupby('name').boxplot(column='AUROC', by='condition', rot=90, figsize=(...
_____no_output_____
MIT
notebooks/2.6-JS-ctakes-relationgram-bow-tfidf.ipynb
jonasspenger/clinical.notes.phenotyping
___ ___ Principal Component AnalysisLet's discuss PCA! Since this isn't exactly a full machine learning algorithm, but instead an unsupervised learning algorithm, we will just have a lecture on this topic, but no full machine learning project (although we will walk through the cancer set with PCA). PCA ReviewMake sure...
import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns %matplotlib inline
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
The DataLet's work with the cancer data set again since it had so many features.
from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer.keys() print(cancer['DESCR']) df = pd.DataFrame(cancer['data'],columns=cancer['feature_names']) #(['DESCR', 'data', 'feature_names', 'target_names', 'target']) df.head()
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
PCA VisualizationAs we've noticed before it is difficult to visualize high dimensional data, we can use PCA to find the first two principal components, and visualize the data in this new, two-dimensional space, with a single scatter-plot. Before we do this though, we'll need to scale our data so that each feature has ...
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(df) scaled_data = scaler.transform(df)
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
PCA with Scikit Learn uses a very similar process to other preprocessing functions that come with SciKit Learn. We instantiate a PCA object, find the principal components using the fit method, then apply the rotation and dimensionality reduction by calling transform().We can also specify how many components we want to ...
from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(scaled_data)
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
Now we can transform this data to its first 2 principal components.
x_pca = pca.transform(scaled_data) scaled_data.shape x_pca.shape
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
Great! We've reduced 30 dimensions to just 2! Let's plot these two dimensions out!
plt.figure(figsize=(8,6)) plt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['target'],cmap='plasma') plt.xlabel('First principal component') plt.ylabel('Second Principal Component')
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
Clearly by using these two components we can easily separate these two classes. Interpreting the components Unfortunately, with this great power of dimensionality reduction, comes the cost of being able to easily understand what these components represent.The components correspond to combinations of the original featur...
pca.components_
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises
In this numpy matrix array, each row represents a principal component, and each column relates back to the original features. we can visualize this relationship with a heatmap:
df_comp = pd.DataFrame(pca.components_,columns=cancer['feature_names']) plt.figure(figsize=(12,6)) sns.heatmap(df_comp,cmap='plasma',)
_____no_output_____
MIT
res/Machine Learning Sections/Principal-Component-Analysis/Principal Component Analysis.ipynb
Calvibert/machine-learning-exercises