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
Step 4: Setup the pattern generatorThe pattern generator will work at the default frequency of 10MHz. This can be modified using a `frequency` argument in the `setup()` method.
pattern_generator.setup(up_counter, stimulus_group_name='stimulus', analysis_group_name='analysis')
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ
__Set the loopback connections using jumper wires on the Arduino Interface__![](./images/pattern_generator_wiring.png)* __Output pins D0, D1 and D2 are connected to pins D19, D18 and D17 respectively__ * __Loopback/Input pins D19, D18 and D17 are observed using the trace analyzer as shown below__* __After setup, the pa...
pattern_generator.run() pattern_generator.show_waveform()
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ
Step 6: Stop the pattern generatorCalling `stop()` will clear the logic values on output pins; however, the waveform will be recorded locally in the pattern generator instance.
pattern_generator.stop()
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ
**K近邻** **1** 介绍K近邻算法的基本原理**2** 介绍K近邻算法的KDTree实现方法**3** 通过简单案例和鸢尾花分类案例,对比分析本文算法和sklearn的结果。
from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier import numpy as np import heapq
_____no_output_____
MIT
algorithms/KNearestNeighbor.ipynb
viga111/machine-learning
**1 K近邻算法** K近邻算法多用于分类任务,本文仅就其分类问题进行讨论。**基本思想**:给定一个已知标签的数据集,对一个输入的未知标签的样本,计算其与数据集中各样本之间的距离,找出与之距离最小的$k$个样本;统计这$k$个样本的类别,以多数服从少数的原则,最终确定未知样本的分类标签。算法的三个基本要素如下:+ **$k$值:** $k$值越大,模型越简单;反之,越复杂。试想:若$k$取数据集的样本总数$n$,那么无论输入的未知样本是什么,最终得到的其分类标签都是数据集中占比最大的那一类的标签,这样的模型是非常简单的。+ **距离度量方法**:不同的距离度量确定的最邻近点通常是不同的。一般选择$Minkowski$距离,其定义...
class Node(object): """kd树中的一个节点""" def __init__(self, seg_axis, seg_point, left=None, right=None): self.seg_axis = seg_axis # int 划分维度 self.seg_point = seg_point # list 划分点 self.left = left # class 左子树 self.right = right # class 右子树 class KDTree(object): """kd树类""" ...
_____no_output_____
MIT
algorithms/KNearestNeighbor.ipynb
viga111/machine-learning
**3 案例** **3.1 简单案例**
# 数据准备 X = [[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]] y = [0, 0, 1, 1, 2, 2] # 本文算法 clf = MyKNeighborsClassifier(X, y, k=3) neigh_dist, neigh_ind = clf.kneighbors([2.5, 4.5], k=3) print('本文算法') print('-------') print('最邻近点的距离:', neigh_dist) print('最邻近点的索引:', neigh_ind) print('预测类别:', clf.predict([2.5, 4.5])) # sk...
sklearn ------- 最邻近点的距离: [[1.58113883 2.54950976 2.91547595]] 最邻近点的索引: [[0 1 3]] 预测类别: [0]
MIT
algorithms/KNearestNeighbor.ipynb
viga111/machine-learning
**3.2 鸢尾花分类**
# 数据准备 iris = load_iris() X2 = iris.data y2 = iris.target # 本文算法 X2_copy = X2.copy().tolist() # 转换成本文算法要求的数据类型 y2_copy = y2.copy().tolist() clf2 = MyKNeighborsClassifier(X2_copy, y2_copy, k=3) neigh_dist2, neigh_ind2 = clf2.kneighbors([2, 3, 2, 3], 3) print('本文算法') print('-------') print('最邻近点的距离:', neigh_dist2) prin...
sklearn ------- 最邻近点的距离: [[3.73764632 3.75366488 3.75898923]] 最邻近点的索引: [[ 8 38 42]] 预测类别: [0]
MIT
algorithms/KNearestNeighbor.ipynb
viga111/machine-learning
ISMT E-111 Coding Challenge Spring 2021 Make sure to include any relevant code when providing all answers :) Save this as a `.ipynb` file with all results visible and send it to Vasya when you're done. Challenge is out of 150 points * **100 points for the main challenge** * **50 bonus points for extra credit** P...
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('codingdata.csv') df.shape df.head(10)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
2. Define and describe your target variableThe `email status` column contains three values with the following definitions. `0=ignored` `1=read` and `2=converted`* Ignored means that the customer did not interact with the email* Read means that a customer opened the email* Converted means that the customer clicked on...
df['conversion'] = df['Email_Status'].apply(lambda x: 1 if x == 2 else 0) df.tail(10)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **b.** **(`10 pts`)** How many conversions are in this dataset?
print('total conversions: %i out of %i' % (df.conversion.sum(), df.shape[0]))
total conversions: 2373 out of 68353
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **c.** **(`10 pts`)** What percent of all emails resulted in a conversion?
print('conversion rate: %0.2f%%' % (df.conversion.sum() / df.shape[0] * 100.0))
conversion rate: 3.47%
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
3 Exploration       **a.** The `Email_Campaign_Type` column captures the campaign under which the email was sent. A campaign is a marketing strategy.            **i.** **(`15 pts`)** Which campaign led to the most conversions?
most_conversions_df=pd.DataFrame( df.groupby( by='Email_Campaign_Type' )['conversion'].sum() ) most_conversions_df #CAMPAIGN 3 has the most number of converstions
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
            **ii.** **(`15 pts`)** Which campaign has the highest conversion rate?
pd.DataFrame( df.groupby( by='Email_Campaign_Type' )['conversion'].count() ) conversion_rate = df.groupby( by='Email_Campaign_Type' )['conversion'].sum() / df.groupby( by='Email_Campaign_Type' )['conversion'].count() * 100.0 pd.DataFrame(conversion_rate) #CAMPAIGN 1 has the highest conversion ra...
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **b**.`Total_Past_Communications` is a count of the number of times the customer has been contacted prior to the current email.             **i.** **(`11 pts`)** Create a box plot showing the distribution of `Total_Past_Comm...
ax = df[['con_version', 'Total_Past_Communications']].boxplot( by='con_version', showfliers=False, figsize=(7,5) ) ax.set_xlabel('Email Status') ax.set_ylabel('Previous Emails') ax.set_title('First couple of contacts unlikely to lead to conversion') plt.suptitle("") plt.show() #Almost no converstions were...
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
***You're done! You can relax and submit this assignment! If you're feeling ambitious, you can try your hand at the _extra credit_ portion below. *** Extra Credit: Build, Interpret and Assess a Machine Learning Model to Predict Conversion Rate**1. Data Cleaning & Prep** We'll be encoding a categorical variable, joi...
df.dtypes categorical_var=['Email_Type','Email_Source_Type','Customer_Location','Email_Campaign_Type','Time_Email_sent_Category'] numerical_var=['Subject_Hotness_Score','Total_Past_Communications','Word_Count','Total_Links','Total_Images']
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **b.** **(`2.5 pts`)** A few of the columns have missing values. Let's just drop them. To do that you can run `df.dropna(inplace=True)` where `df` is the name of your dataframe. That's it, this one's easy, no tricks.
df.dropna(inplace=True)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **c.** **(`10 pts`)** Add Dummy Variables! (Hint: Follow the code in chapter 4)            **i.** Using `pd.get_dummies(, drop_first=True)`, create a new dataframe that contains the dummy-variable version of `Email_Campaig...
df['Email_Campaign_Type'].unique() Email_Campaign_Type_encoded_df = pd.get_dummies(df['Email_Campaign_Type'], drop_first=True) Email_Campaign_Type_encoded_df.columns = ['Campaign_%s' % x for x in Email_Campaign_Type_encoded_df.columns] Email_Campaign_Type_encoded_df.head() df = pd.concat([df, Email_Campaign_Type_encode...
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **d.** **(`7.5 pts`)** Split the dataframe into 80% training data and 20% testing data using the `train_test_split` function (see section 3 of the notebook from Chapter 8 for an example of how to do this.) When you pass the data to be split, be sure to add an intercept! To do this s...
from sklearn.model_selection import train_test_split import statsmodels.api as sm x_train, x_test, y_train, y_test = train_test_split(sm.add_constant(df[all_features]), df[response], test_size=0.2, random_state=42)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
**2. Build, interpret and score a logistic regression model!**       **a.** **(`5 pts`)** Build a Logistic Regression using statsmodels (statsmodels.api) as in Chapter 3. Only include the *train* data you created in question 1d.
x_train.head() logit = sm.Logit( y_train, x_train ) fit = logit.fit() fit.summary()
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **b.** **(`10 pts`)** Take a look at the model summary and interpret the results. Remember that `Campaign_2` & `Campaign_3` are encoded in relation to `Campaign_1`, when interpretting them remember to mention that their effect is relative to `Campaign_1` (think in terms of negative v...
#Word count and total images have no corelation to conversion. #Total links and Total past communications have some positive corelation with conversion. #The coefficent of the subject hotness score indicates a positive co-relation with conversion but the p value indicates that this co-relation may not be significant. #...
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **c.** **(`5 pts`)** Use your model to get predictions using the test data. Remember that your fit model is the result of the `.fit()` call (e.g., `my_fit = my_model.fit()`). The resulting object has a `.predict` method (e.g., `my_fit.predict()`) that will generate predictions usin...
x_pred=fit.predict(x_test)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
      **d.** **(`5 pts`)** The ROC AUC score informs you as to how good your model is at telling which emails are more likely to result in conversions than others. You can use the Scikit-Learn function `sklearn.metrics.roc_auc_score` to compute this. This function has two inputs: predicti...
from sklearn.metrics import roc_auc_score roc_auc_score(y_test, x_pred)
_____no_output_____
MIT
CodingChallenge_S2021.ipynb
pkramadhati/ISMTE111
Copyright Netherlands eScience Center and Centrum Wiskunde & Informatica ** Function : Emotion recognition and forecast with ConvLSTM** ** Author : Yang Liu & Tianyi Zhang** ** First Built : 2020.05.17 ** ** Last Update : 2020.05.22 ** ** Library : Pytorth, Numpy, os, DLACs, matplotlib **Description ...
%matplotlib inline import sys import numbers # for data loading import os # for pre-processing and machine learning import numpy as np import csv #import sklearn #import scipy import torch import torch.nn.functional sys.path.append("C:\\Users\\nosta\\ConvLSTM_emotion\\Scripts\\DLACs") #sys.path.append("../") import ...
_____no_output_____
Apache-2.0
tests/BBConvLSTM_emotion_predict.ipynb
geek-yang/NEmo
The testing device is Dell Inspirion 5680 with Intel Core i7-8700 x64 CPU and Nvidia GTX 1060 6GB GPU.Here is a benchmark about cpu v.s. gtx 1060 https://www.analyticsindiamag.com/deep-learning-tensorflow-benchmark-intel-i5-4210u-vs-geforce-nvidia-1060-6gb/
################################################################################# ######### datapath ######## ################################################################################# # please specify data path datapath = 'C:\\Users\\nosta\\ConvLSTM_emotion...
(3690, 1000, 8) (3690, 1000, 2) (3690, 2) (3690, 1) (3690, 1) (3567, 40, 5, 5, 2)
Apache-2.0
tests/BBConvLSTM_emotion_predict.ipynb
geek-yang/NEmo
Procedure for LSTM ** We use Pytorth to implement LSTM neural network with time series of climate data. **
print ('******************* create basic dimensions for tensor and network *********************') # specifications of neural network input_channels = 5 hidden_channels = [4, 3, 2] # number of channels & hidden layers, the channels of last layer is the channels of output, too #hidden_channels = [3...
_____no_output_____
Apache-2.0
tests/BBConvLSTM_emotion_predict.ipynb
geek-yang/NEmo
Data Augmentation GoalsIn this notebook you're going to build a generator that can be used to help create data to train a classifier. There are many cases where this might be useful. If you are interested in any of these topics, you are welcome to explore the linked papers and articles! - With smaller datasets, GAN...
import torch import torch.nn.functional as F import matplotlib.pyplot as plt from torch import nn from tqdm.auto import tqdm from torchvision import transforms from torchvision.utils import make_grid from torch.utils.data import DataLoader torch.manual_seed(0) # Set for our testing purposes, please do not change! def ...
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Generator
class Generator(nn.Module): ''' Generator Class Values: input_dim: the dimension of the input vector, a scalar im_chan: the number of channels of the output image, a scalar (CIFAR100 is in color (red, green, blue), so 3 is your default) hidden_dim: the inner dimension, ...
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
TrainingNow you can begin training your models.First, you will define some new parameters:* cifar100_shape: the number of pixels in each CIFAR image, which has dimensions 32 x 32 and three channel (for red, green, and blue) so 3 x 32 x 32* n_classes: the number of classes in CIFAR100 (e.g. airplane, automobile, bi...
cifar100_shape = (3, 32, 32) n_classes = 100
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
And you also include the same parameters from previous assignments: * criterion: the loss function * n_epochs: the number of times you iterate through the entire dataset when training * z_dim: the dimension of the noise vector * display_step: how often to display/visualize the images * batch_size: the nu...
# Note: n_epochs need to be much larger! # I just changed so it would be a small file when I upload to Github n_epochs = 1 z_dim = 64 display_step = 500 batch_size = 64 lr = 0.0002 device = 'cuda'
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Then, you want to set your generator's input dimension. Recall that for conditional GANs, the generator's input is the noise vector concatenated with the class vector.
generator_input_dim = z_dim + n_classes
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
ClassifierFor the classifier, you will use the same code that you wrote in an earlier assignment (the same as previous code for the discriminator as well since the discriminator is a real/fake classifier).
class Classifier(nn.Module): ''' Classifier Class Values: im_chan: the number of channels of the output image, a scalar n_classes: the total number of classes in the dataset, an integer scalar hidden_dim: the inner dimension, a scalar ''' def __init__(self, im_chan, n_classes...
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Pre-training (Optional)You are provided the code to pre-train the models (GAN and classifier) given to you in this assignment. However, this is intended only for your personal curiosity -- for the assignment to run as intended, you should not use any checkpoints besides the ones given to you.
# This code is here for you to train your own generator or classifier # outside the assignment on the full dataset if you'd like -- for the purposes # of this assignment, please use the provided checkpoints class Discriminator(nn.Module): ''' Discriminator Class Values: im_chan: the number of channe...
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Tuning the ClassifierAfter two courses, you've probably had some fun debugging your GANs and have started to consider yourself a bug master. For this assignment, your mastery will be put to the test on some interesting bugs... well, bugs as in insects.As a bug master, you want a classifier capable of classifying diffe...
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: combine_sample def combine_sample(real, fake, p_real): ''' Function to take a set of real and fake images of the same length (x) and produce a combined tensor with length (x) and sampled at the target probability Parameters: real:...
Success!
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Now you have a challenge: find a `p_real` and a generator image such that your classifier gets an average of a 51% accuracy or higher on the insects, when evaluated with the `eval_augmentation` function. **You'll need to fill in `find_optimal` to find these parameters to solve this part!** Note that if your answer take...
# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: find_optimal def find_optimal(): # In the following section, you can write the code to choose your optimal answer # You can even use the eval_augmentation function in your code if you'd like! gen_names = [ "gen_1.pt", "gen_2.p...
Your model had an accuracy of 52.0% Success!
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
You'll likely find that the worst performance is when the generator is performing alone: this corresponds to the case where you might be trying to hide the underlying examples from the classifier. Perhaps you don't want other people to know about your specific bugs!
accuracies = [] p_real_all = torch.linspace(0, 1, 21) for p_real_vis in tqdm(p_real_all): accuracies += [eval_augmentation(p_real_vis, best_gen_name, n_test=4)] plt.plot(p_real_all.tolist(), accuracies) plt.ylabel("Accuracy") _ = plt.xlabel("Percent Real Images")
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Here's a visualization of what the generator is actually generating, with real examples of each class above the corresponding generated image.
examples = [4, 41, 80, 122, 160] train_images = torch.load("insect_train.pt")["images"][examples] train_labels = torch.load("insect_train.pt")["labels"][examples] one_hot_labels = get_one_hot_labels(train_labels.to(device), n_classes).float() fake_noise = get_noise(len(train_images), z_dim, device=device) noise_and_la...
_____no_output_____
MIT
MOOCS/GAN_Specialization/Course 3 - Apply GANs/Week 1/C3W1_GANs4Augmentation.ipynb
itismesam/Courses-1
Lab-02-3 linear regression tensorflow.org
# From https://www.tensorflow.org/get_started/get_started import tensorflow as tf
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/ubuntu/.local...
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
Variable
# Model parameters W = tf.Variable([.3], tf.float32) b = tf.Variable([-.3], tf.float32) # Model input and output x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32)
WARNING:tensorflow:From /home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer.
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
Our Model
linear_model = x * W + b # cost/loss function loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
_____no_output_____
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
Minimize
# optimizer optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss)
WARNING:tensorflow:From /home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead.
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
X and Y data
# training data x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3]
_____no_output_____
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
Fit the line
# training loop init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong for i in range(1000): sess.run(train, {x: x_train, y: y_train})
_____no_output_____
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
evaluate training accuracy
# evaluate training accuracy curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss)) # Functions to show the Graphs import numpy as np from IPython.display import clear_output, Image, display, HTML def strip_consts(graph_def, max_const_si...
_____no_output_____
MIT
03_TensorBoard/lab-02-3-linear_regression_tensorflow.org.ipynb
jetsonworld/TensorFlow_On_JetsonNano
pulse2percept: Example UsageThis notebook illustrates a simple used-case of the software.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pulse2percept as p2p
/home/mbeyeler/anaconda3/lib/python3.5/site-packages/skvideo/__init__.py:356: UserWarning: avconv/avprobe not found in path: warnings.warn("avconv/avprobe not found in path: " + str(path), UserWarning) 2018-08-15 14:30:31,105 [pulse2percept] [INFO] Welcome to pulse2percept
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
1. Setting up the Simulation 1.1 Setting up the ImplantAll retinal implants live in the `implants` module.You can either create your own `p2p.implants.ElectrodeArray`, or choose from one of the pre-defined types:- `p2p.implants.ArgusI`: The A16 array has 16 electrodes arranged in a 4x4 grid. Electrodes are 800um apar...
# Load an Argus II array argus = p2p.implants.ArgusI(x_center=-800, y_center=-400, h=0, rot=np.deg2rad(-35), eye='RE')
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
1.2 Starting the Simulation FrameworkAll simulations revolve around the `p2p.Simulation` object, which starts a new simulation framework.Once an implant `argus` has been passed, it cannot be changed.You can also specify on which backend to run the simulation via `engine`:- `'serial'`: Run a single-thread computation.-...
# Start the simulation framework sim = p2p.Simulation(argus, engine='joblib', n_jobs=1)
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
1.3 Specifying the Retinal Model The `p2p.Simulation` object allows you access every layer of the retinal model via setter functions:- `set_optic_fiber_layer`: Specify parameters of the optic fiber layer (OFL), where the ganglion cell axons live.- `set_ganglion_cell_layer`: Specify parameters of the ganglion cell laye...
# Set parameters of the optic fiber layer (OFL) # In previous versions of the model, this used to be called the `Retina` # object, which created a spatial grid and generated the axtron streak map. # Set the spatial sampling step (microns) of the retinal grid s_sample = 100 sim.set_optic_fiber_layer(sampling=s_sample, ...
2018-08-15 14:30:31,260 [pulse2percept.retina] [INFO] Loading file "./retina_RE_s100_a501_r801_5000x5000.npz".
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
In `set_ganglion_cell_layer`, you can choose from one of the available ganglion cell models:- `'latest'`: The latest ganglion cell model for epiretinal and subretinal devices (experimental).- `'Nanduri2012'`: A model of temporal sensitivity as described in Nanduri et al. (IOVS, 2012).- `'Horsager2009'`: A model of temp...
# Set parameters of the ganglion cell layer (GCL) # In previous versions of the model, this used to be called `TemporalModel`. # Set the temporal sampling step (seconds) t_sample = 0.01 / 1000 sim.set_ganglion_cell_layer('Nanduri2012', tsample=t_sample)
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
1.4 Specifying the input stimulus All stimulation protocols live in `p2p.stimuli`. You can choose from the following:- `MonophasicPulse`: A single monophasic pulse of either cathodic (negative) or anodic (positive) current.- `BiphasicPulse`: A single biphasic pulse going either cathodic-first or anodic-first.- `PulseT...
# Send a pulse train to two specific electrodes, set all others to zero stim = { 'C1': p2p.stimuli.PulseTrain(t_sample, freq=50, amp=20, dur=0.5), 'B3': p2p.stimuli.PulseTrain(t_sample, freq=50, amp=20, dur=0.5) }
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
We can visualize the specified electrode array and its location on the retina with respect to the optic disc:
p2p.viz.plot_fundus(argus, stim, upside_down=False);
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
2. Running the Simulation Simulations are run by passing an input stimulus `stim` to `p2p.pulse2percept`. Output is a `p2p.utils.TimeSeries` objects that contains the brightness changes over time for each pixel.
# Run a simulation # - tol: ignore pixels whose efficient current is smaller than 10% of the max # - layers: simulate ganglion cell layer (GCL) and optic fiber layer (OFL), # but ignore inner nuclear layer (INL) for now percept = sim.pulse2percept(stim, tol=0.1, layers=['GCL', 'OFL'])
2018-08-15 14:30:32,377 [pulse2percept.api] [INFO] Starting pulse2percept... 2018-08-15 14:30:33,885 [pulse2percept.api] [INFO] tol=10.0%, 2089/2601 px selected 2018-08-15 14:30:58,988 [pulse2percept.api] [INFO] Done.
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
3. Analyzing Output You can look at the brightness time course of every pixel, or you can simply plot the brightest frame in the whole brightness "movie":
frame = p2p.get_brightest_frame(percept) plt.figure(figsize=(8, 5)) plt.imshow(frame.data, cmap='gray') plt.colorbar()
_____no_output_____
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
Finally, you can also dump the percept to file, by creating MP4 or MOV videos (requires Scikit-Video).
# This requires ffmpeg or libav-tools p2p.files.save_video(percept, 'percept.mp4', fps=30)
2018-08-15 14:31:00,422 [pulse2percept.files] [INFO] Saved video to file 'percept.mp4'.
BSD-3-Clause
examples/notebooks/0.0-example-usage.ipynb
jonluntzel/pulse2percept
Regular Expressions ExercisesLets download the complete works of sherlock holmes and do some detective work using REGEX.For many of these exercises it is helpful to compile a regular expression p and then use p.findall() followed by some additional simple python processing to answer the questionsstart by importing re
import re
_____no_output_____
Apache-2.0
Re/REGEX_Exercises.ipynb
reddyprasade/Natural-Language-Processing
now lets download [sherlock holmes](https://sherlock-holm.es/stories/plain-text/cnus.txt) If we open that file we will get access to the complete works of Sherlock Holmes
text = '' with open('Data/cnus.txt','r') as f: text = " ".join([l.strip() for l in f.readlines()]) text[2611:3000]
_____no_output_____
Apache-2.0
Re/REGEX_Exercises.ipynb
reddyprasade/Natural-Language-Processing
bqplot `bqplot` is a [Grammar of Graphics](https://www.cs.uic.edu/~wilkinson/TheGrammarOfGraphics/GOG.html) based interactive plotting framework for the Jupyter notebook. The library offers a simple bridge between `Python` and `d3.js` allowing users to quickly and easily build complex GUI's with layered interactions. ...
from IPython.display import YouTubeVideo YouTubeVideo('eVET9IYgbao')
_____no_output_____
MIT
02-bqplot/examples/Index.ipynb
dushyantkhosla/dataviz
Copyright 2020 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Basic training loops View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook In the previous guides, you have learned about [tensors](./tensor.ipynb), [variables](./variable.ipynb), [gradient tape](autodiff.ipynb), and [modules](./intro_to_modules.ipynb). In thi...
import tensorflow as tf
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Solving machine learning problemsSolving a machine learning problem usually consists of the following steps: - Obtain training data. - Define the model. - Define a loss function. - Run through the training data, calculating loss from the ideal value - Calculate gradients for that loss and use an *optimizer* to adjust ...
# The actual line TRUE_W = 3.0 TRUE_B = 2.0 NUM_EXAMPLES = 1000 # A vector of random x values x = tf.random.normal(shape=[NUM_EXAMPLES]) # Generate some noise noise = tf.random.normal(shape=[NUM_EXAMPLES]) # Calculate y y = x * TRUE_W + TRUE_B + noise # Plot all the data import matplotlib.pyplot as plt plt.scatter...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Tensors are usually gathered together in *batches*, or groups of inputs and outputs stacked together. Batching can confer some training benefits and works well with accelerators and vectorized computation. Given how small this dataset is, you can treat the entire dataset as a single batch. Define the modelUse `tf.Va...
class MyModel(tf.Module): def __init__(self, **kwargs): super().__init__(**kwargs) # Initialize the weights to `5.0` and the bias to `0.0` # In practice, these should be randomly initialized self.w = tf.Variable(5.0) self.b = tf.Variable(0.0) def __call__(self, x): return self.w * x + self....
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
The initial variables are set here in a fixed way, but Keras comes with any of a number of [initalizers](https://www.tensorflow.org/api_docs/python/tf/keras/initializers) you could use, with or without the rest of Keras. Define a loss functionA loss function measures how well the output of a model for a given input ma...
# This computes a single loss value for an entire batch def loss(target_y, predicted_y): return tf.reduce_mean(tf.square(target_y - predicted_y))
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Before training the model, you can visualize the loss value by plotting the model's predictions in red and the training data in blue:
plt.scatter(x, y, c="b") plt.scatter(x, model(x), c="r") plt.show() print("Current loss: %1.6f" % loss(model(x), y).numpy())
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Define a training loopThe training loop consists of repeatedly doing three tasks in order:* Sending a batch of inputs through the model to generate outputs* Calculating the loss by comparing the outputs to the output (or label)* Using gradient tape to find the gradients* Optimizing the variables with those gradientsFo...
# Given a callable model, inputs, outputs, and a learning rate... def train(model, x, y, learning_rate): with tf.GradientTape() as t: # Trainable variables are automatically tracked by GradientTape current_loss = loss(y, model(x)) # Use GradientTape to calculate the gradients with respect to W and b dw,...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
For a look at training, you can send the same batch of *x* an *y* through the training loop, and see how `W` and `b` evolve.
model = MyModel() # Collect the history of W-values and b-values to plot later Ws, bs = [], [] epochs = range(10) # Define a training loop def training_loop(model, x, y): for epoch in epochs: # Update the model with the single giant batch train(model, x, y, learning_rate=0.1) # Track this before I upd...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
The same solution, but with KerasIt's useful to contrast the code above with the equivalent in Keras.Defining the model looks exactly the same if you subclass `tf.keras.Model`. Remember that Keras models inherit ultimately from module.
class MyModelKeras(tf.keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) # Initialize the weights to `5.0` and the bias to `0.0` # In practice, these should be randomly initialized self.w = tf.Variable(5.0) self.b = tf.Variable(0.0) def __call__(self, x, **kwargs): retur...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Rather than write new training loops each time you create a model, you can use the built-in features of Keras as a shortcut. This can be useful when you do not want to write or debug Python training loops.If you do, you will need to use `model.compile()` to set the parameters, and `model.fit()` to train. It can be le...
keras_model = MyModelKeras() # compile sets the training paramaeters keras_model.compile( # By default, fit() uses tf.function(). You can # turn that off for debugging, but it is on now. run_eagerly=False, # Using a built-in optimizer, configuring as an object optimizer=tf.keras.optimizers.SGD(le...
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
Keras `fit` expects batched data or a complete dataset as a NumPy array. NumPy arrays are chopped into batches and default to a batch size of 32.In this case, to match the behavior of the hand-written loop, you should pass `x` in as a single batch of size 1000.
print(x.shape[0]) keras_model.fit(x, y, epochs=10, batch_size=1000)
_____no_output_____
Apache-2.0
site/en/guide/basic_training_loops.ipynb
jcjveraa/docs-2
65 Python Basics2 These assignments aim to get you acquainted with Python, which is an important requirement for all the research done at Solarillion Foundation. Apart from teaching you Python, these assignments also aim to make you a better programmer and cultivate better coding practices. Visit these links for more d...
from IPython import get_ipython ipy = get_ipython() if ipy is not None: ipy.run_line_magic("load_ext", "pycodestyle_magic") ipy.run_line_magic("pycodestyle_on", "")
_____no_output_____
MIT
Module3 (1).ipynb
Manassss/pythonassignments
Burger Mania
""" Imagine that you are a restaurant's cashier and are trying to keep records for analysing profits. Your restaurant sells 7 different items: 1. Burgers - $4.25 2. Nuggets - $2.50 3. French Fries - $2.00 4. Small Drink - $1.25 5. Medium Drink - $1.50 6. Large Drink - $1.75 7. Salad - $3.75...
[296.4749999999999, 571.8722499999999, 574.955, 422.1449999999999, 551.6499999999999, 609.1749999999998, 449.97825000000006, 583.02325, 640.8137500000001, 233.97925, 377.01, 551.119, 565.0872499999999, 615.37, 273.76, 438.901, 605.93, 446.03999999999985, 386.745, 613.01, 319.78, 396.47999999999985, 682.9250000000002, 4...
MIT
Module3 (1).ipynb
Manassss/pythonassignments
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.png) Train and expl...
# Check core SDK version number import azureml.core print("SDK version:", azureml.core.VERSION)
_____no_output_____
MIT
how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb
angeltorresoa/MachineLearningNotebooks
Initialize a WorkspaceInitialize a workspace object from persisted configuration
from azureml.core import Workspace ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n')
_____no_output_____
MIT
how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb
angeltorresoa/MachineLearningNotebooks
ExplainCreate An Experiment: **Experiment** is a logical container in an Azure ML Workspace. It hosts run records which can include run metrics and output artifacts from your experiments.
from azureml.core import Experiment experiment_name = 'explain_model_at_scoring_time' experiment = Experiment(workspace=ws, name=experiment_name) run = experiment.start_logging() # Get IBM attrition data import os import pandas as pd outdirname = 'dataset.6.21.19' try: from urllib import urlretrieve except ImportE...
_____no_output_____
MIT
how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb
angeltorresoa/MachineLearningNotebooks
VisualizeVisualize the explanations
from interpret_community.widget import ExplanationDashboard ExplanationDashboard(global_explanation, clf, datasetX=x_test)
_____no_output_____
MIT
how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb
angeltorresoa/MachineLearningNotebooks
Deploy Deploy Model and ScoringExplainer.Please note that you must indicate azureml-defaults with verion >= 1.0.45 as a pip dependency, because it contains the functionality needed to host the model as a web service.
from azureml.core.conda_dependencies import CondaDependencies # azureml-defaults is required to host the model as a web service. azureml_pip_packages = [ 'azureml-defaults', 'azureml-core', 'azureml-telemetry', 'azureml-interpret' ] # Note: this is to pin the scikit-learn and pandas versions to be same as ...
_____no_output_____
MIT
how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb
angeltorresoa/MachineLearningNotebooks
THIS IS MARKDOWNIt's great
n=10 #define an integer x=np.arange(n,dtype=float) #define an array print(x)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
MIT
my_first_python_notebook.ipynb
PetersonZou/astr-119-session-5
Computation Biology Summer Program Hackathon This [Jupyter notebook](https://jupyter.org/) gives examples on how to use the various [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) web services from the [Knowledge Systems Group](https://www.mskcc.org/research-areas/labs/nikolaus-schultz). In this ...
from bravado.client import SwaggerClient cbioportal = SwaggerClient.from_url('https://www.cbioportal.org/api/api-docs', config={"validate_requests":False,"validate_responses":False}) print(cbioportal)
SwaggerClient(https://www.cbioportal.org/api)
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
You can now explore the API by using code completion, press `Tab` after typing `cbioportal.`:
cbioportal.B_Studies
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
This will give a dropdown with all the different APIs, similar to how you can see them here on the cBioPortal website: https://www.cbioportal.org/api/swagger-ui.html/.You can also get the parameters to a specific endpoint by pressing shift+tab twice after typing the name of the specific endpoint e.g.:
cbioportal.A_Cancer_Types.getCancerTypeUsingGET(
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
That shows one of the parameters is `cancerTypeId` of type `string`, the example `acc` is mentioned:
acc = cbioportal.A_Cancer_Types.getCancerTypeUsingGET(cancerTypeId='acc').result() print(acc)
TypeOfCancer(cancerTypeId='acc', clinicalTrialKeywords='adrenocortical carcinoma', dedicatedColor='Purple', name='Adrenocortical Carcinoma', parent='adrenal_gland', shortName='ACC')
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
You can see that the JSON output returned by the cBioPortal API gets automatically converted into an object called `TypeOfCancer`. This object can be explored interactively as well by pressing tab after typing `acc.`:
acc.dedicatedColor
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
cBioPortal API [cBioPortal](https://www.cbioportal.org) stores cancer genomics data from a large number of published studies. Let's figure out:- how many studies are there?- how many cancer types do they span?- how many samples in total?- which study has the largest number of samples?
studies = cbioportal.B_Studies.getAllStudiesUsingGET().result() cancer_types = cbioportal.A_Cancer_Types.getAllCancerTypesUsingGET().result() print("In total there are {} studies in cBioPortal, spanning {} different types of cancer.".format( len(studies), len(cancer_types) ))
In total there are 256 studies in cBioPortal, spanning 855 different types of cancer.
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
To get the total number of samples in each study we have to look a bit more at the response of the studies endpoint:
dir(studies[0])
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
We can sum the `allSampleCount` values of each study in cBioPortal:
print("The total number of samples in all studies is: {}".format(sum([x.allSampleCount for x in studies])))
The total number of samples in all studies is: 77901
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Let's see which study has the largest number of samples:
sorted_studies = sorted(studies, key=lambda x: x.allSampleCount) sorted_studies[-1]
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Make it as little easier to read using pretty print:
from pprint import pprint pprint(vars(sorted_studies[-1])['_Model__dict'])
{'allSampleCount': 10945, 'cancerType': None, 'cancerTypeId': 'mixed', 'citation': 'Zehir et al. Nat Med 2017', 'cnaSampleCount': None, 'completeSampleCount': None, 'description': 'Targeted sequencing of 10,000 clinical cases using the ' 'MSK-IMPACT assay', 'groups': 'PUBLIC', 'importDate': '201...
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Now that we've answered the inital questions we can dig a little deeper into this specific study:- How many patients are in this study?- What gene is most commonly mutated across the different samples?- Does this study span one or more types of cancer?The description of the study with id `msk_impact_2017` study mention...
patients = cbioportal.C_Patients.getAllPatientsInStudyUsingGET(studyId='msk_impact_2017').result() print("The msk_impact_2017 study spans {} patients".format(len(patients)))
The msk_impact_2017 study spans 10336 patients
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Now let's try to figure out what gene is most commonly mutated. For this we can check the endpoints in the group `K_Mutations`. When looking at these endpoints it seems that a study can have multiple molecular profiles. This is because samples might have been sequenced using different assays (e.g. targeting a subset of...
%%time mutations = cbioportal.K_Mutations.getMutationsInMolecularProfileBySampleListIdUsingGET( molecularProfileId='msk_impact_2017_mutations', sampleListId='msk_impact_2017_all' ).result()
CPU times: user 10.9 s, sys: 407 ms, total: 11.3 s Wall time: 14.8 s
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
We can explore what the mutation data structure looks like:
pprint(vars(mutations[0])['_Model__dict'])
{'aminoAcidChange': None, 'center': 'NA', 'driverFilter': '', 'driverFilterAnnotation': '', 'driverTiersFilter': '', 'driverTiersFilterAnnotation': '', 'endPosition': 36252995, 'entrezGeneId': 861, 'fisValue': 1.4013e-45, 'functionalImpactScore': '[Not Available]', 'gene': None, 'keyword': 'RUNX1 truncating'...
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
It seems that the `gene` field is not filled in. To keep the response size of the API small, the API uses a parameter called `projection` that indicates whether or not to return all fields of an object or only a portion of the fields. By default it will use the `SUMMARY` projection. But because in this case we want to ...
%%time mutations = cbioportal.K_Mutations.getMutationsInMolecularProfileBySampleListIdUsingGET( molecularProfileId='msk_impact_2017_mutations', sampleListId='msk_impact_2017_all', projection='DETAILED' ).result()
CPU times: user 14.4 s, sys: 549 ms, total: 14.9 s Wall time: 20.8 s
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
You can see the response time is slightly slower. Let's check if the gene field is filled in now:
pprint(vars(mutations[0])['_Model__dict'])
{'aminoAcidChange': None, 'center': 'NA', 'driverFilter': '', 'driverFilterAnnotation': '', 'driverTiersFilter': '', 'driverTiersFilterAnnotation': '', 'endPosition': 36252995, 'entrezGeneId': 861, 'fisValue': 1.4013e-45, 'functionalImpactScore': '[Not Available]', 'gene': Gene(chromosome='21', cytoband='21q2...
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Now that we have the gene field we can check what gene is most commonly mutated:
from collections import Counter mutation_counts = Counter([m.gene.hugoGeneSymbol for m in mutations]) mutation_counts.most_common(5)
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
We can verify that these results are correct by looking at the study view of the MSK-IMPACT study on the cBioPortal website: https://www.cbioportal.org/study/summary?id=msk_impact_2017. Note that the website uses the REST API we've been using in this hackathon, so we would expect those numbers to be the same, but good ...
import pandas as pd mdf = pd.DataFrame.from_dict([ # python magic that combines two dictionaries: dict( m.__dict__['_Model__dict'], **m.__dict__['_Model__dict']['gene'].__dict__['_Model__dict']) # create one item in the list for each mutation for m in mutations ])
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
The DataFrame is a data type originally from `Matlab` and `R` that makes it easier to work with columnar data. Pandas brings that data type to Python. There are also several performance optimizations by it using the data types from [numpy](https://www.numpy.org/).Now that you have the data in a Dataframe you can group ...
sample_count_per_gene = mdf.groupby('hugoGeneSymbol')['uniqueSampleKey'].nunique() print("There are {} samples with a mutation in TP53".format( sample_count_per_gene['TP53'] ))
There are 4561 samples with a mutation in TP53
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
It would be nice to visualize this result in context of the other genes by plotting the top 10 most mutated genes. For this you can use the matplotlib interface that integrates with pandas.First inline plotting in the notebook:
%matplotlib inline sample_count_per_gene.sort_values(ascending=False).head(10).plot(kind='bar')
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
Make it look a little nicer by importing seaborn:
import seaborn as sns sns.set_style("white") sns.set_context('notebook') sample_count_per_gene.sort_values(ascending=False).head(10).plot(kind='bar') sns.despine(trim=False)
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
You can further change the plot a bit by using the arguments to the plot function or using the matplotlib interface directly:
import matplotlib.pyplot as plt sample_count_per_gene.sort_values(ascending=False).head(10).plot( kind='bar', ylim=[0,5000], color='green' ) sns.despine(trim=False) plt.xlabel('') plt.xticks(rotation=300) plt.ylabel('Number of samples',labelpad=20) plt.title('Number of mutations in genes in MSK-IMPACT (201...
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
A further extension of this plot could be to color the bar chart by the type of mutation in that sample (`mdf.mutationType`) and to include copy number alterations (see `L. Discrete Copy Number Alterations` endpoints). Genome Nexus API [Genome Nexus](https://www.genomenexus.org) is a web service that aggregates all ca...
from bravado.client import SwaggerClient gn = SwaggerClient.from_url('https://www.genomenexus.org/v2/api-docs', config={"validate_requests":False, "validate_responses":False, "validate_swagger_spec":False}) print(gn)
SwaggerClient(https://www.genomenexus.org/)
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
To look up annotations for a single variant, one can use the following endpoint:
variant = gn.annotation_controller.fetchVariantAnnotationByGenomicLocationGET( genomicLocation='7,140453136,140453136,A,T', # adds extra annotation resources, not included in default response: fields='hotspots mutation_assessor annotation_summary'.split() ).result()
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
You can see a lot of information is provided for that particular variant if you type tab after `variant.`:
variant.
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon
For this example we will focus on the hotspot annotation and ignore the others. [Cancer hotspots](https://www.cancerhotspots.org/) is a popular web resource which indicates whether particular variants have been found to be recurrently mutated in large scale cancer genomics data.The example variant above is a hotspot:
variant.hotspots
_____no_output_____
MIT
0-introduction/cbsp_hackathon.ipynb
jxu8/cbsp-hackathon