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__* __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 pattern generator should be ready to run__**Note:** Make sure all other pins are disconnected. Step 5: Run and display waveformThe ` run()` method will execute all the samples, `show_waveform()` method is used to display the waveforms. Alternatively, we can also use `step()` method to single step the pattern. | 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$距离,其定义为:$$ L_p(x_i, x_j)=(\sum_{l=1}^{m}|x_i^{(l)}- x_j^{(l)}|^p)^{\frac{1}{p}} $$其中:$p>=1$;$m$为特征的维数;$l$为第几维。当$p=2$时,为欧氏距离:$ L_2(x_i, x_j)=(\sum_{l=1}^{m}|x_i^{(l)}- x_j^{(l)}|^2)^{\frac{1}{2}} $当$p=1$时,为曼哈顿距离:$ L_1(x_i, x_j)=\sum_{l=1}^{m}|x_i^{(l)}- x_j^{(l)}| $当$p=\infty$时,为各个维度下距离的最大值:$ L_\infty(x_i, x_j)=max|x_i^{(l)}- x_j^{(l)}| $+ **分类决策规则**:一般是采用多数表决的规则,即由输入的未知样本的k个邻近样本中的多数类决定未知样本的类。 **2 KDTree** K近邻算法的思想很简单,但存在的问题是:当样本数量较大时,为预测一个未知样本的类别标签,需要遍历计算其与所有样本之间的距离(线性搜索),这无疑会造成较大的时间开销。通过构造KDTree,减少计算距离的次数,提高算法效率。**2.1 KDTree构造** + **两个基本操作:**1) 计算划分维度: $ l=j \ \% \ m $。$\%$为取模运算;$j$的起始值为0,每完成一次划分$j=j+1$;$m$为特征的维数2) 计算划分点: 按$l$维的值对$X$从小到大排序,取中间点作为划分点。排序后中间点索引的计算方法为:$len(X)\ // \ 2$+ **示例:** 给定数据集$X = [[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]]$,构造一个kd树。1) 第1次划分: $ l_1=0 \ \% \ 2 = 0$,也就是划分维度为第0维;按第0维元素值对$X$排序的结果为$X = [[2, 3], [4, 7], [5, 4], [7, 2], [8, 1], [9, 6]]$;划分点的索引为$len(X)\ // \ 2 = 6 \ // \ 2 = 3$,对应$[7, 2]$,存储到根节点;将$[7, 2]$左侧的点存储到左子树,右侧的点存储到右子树。2) 第2次划分: $j = j + 1$,即$ l_2=1 \ \% \ 2 = 1$;对第1次划分得到的左右子树,分别进行同样的划分操作,得到新的左右子树。3) 第3次划分: $j = j + 1$,即$ l_3=2 \ \% \ 2 = 0$;划分后发现所有叶节点中只有一个点,因而无法继续划分,划分停止,得到最终的KDTree。注:可以发现上述过程,划分维度是交替进行的,因此可以称为交替维度划分法。除此之外,还可以采用最大方差法,即:每一次划分计算各个维度上的方差,取方差最大的维度作为该次的划分维度。 **2.2 KDTree搜索** + 上述的二维数据集构造的KDTree可以对应用如下二维平面的划分来表达,每一次划分即对应在该次的划分维度上根据划分点将平面切割。如下图所示,第$1$次划分在$l=0$维度的$x^{(1)}=7$处将平面切割为左右两个区域。+ **搜索过程**以寻找点(2.5, 4.5)的最邻近点为例:1) 按上述创建的KDTree从根节点开始判断,直至达到叶节点,可以得到(2.5, 4.5)的第一个候选最邻近点为(4, 7),对应的欧式距离$d_{min}$为2.915;2) 回溯。(4, 7)的根节点为(5, 4),计算(2.5, 4.5)与(5, 4)的距离为2.5503)继续向上回溯。(5, 4)的根节点为(7, 2),计算(2.5, 4.5)与(7, 2)的距离为5.148>1.581,因此不更新最邻近点与$d_{min}$。同样地,判断$d_l$和$d_{min}$的大小关系,发现$d_l= 4.5 > d_{min}=1.581$,因此不需要再进入(7, 2)的右子树进行搜索。本例中(7, 2)为整体树的根节点,因此到此搜索也就停止,最终得到的最邻近点为(2, 3),最邻近距离为1.581。 | 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树类"""
def __init__(self, X):
self.X = X
def create(X, depth=0):
"""递归创建kd树
Parameters
----------
X: list 样本
depth: int 树的深度 默认为0
"""
if not X:
return
# 交替轴法确定划分维度
k = len(X[0])
ax = depth % k
sort_X = sorted(X, key=lambda x: x[ax])
mid = len(X) // 2
return Node(seg_axis=ax,
seg_point=sort_X[mid],
left=create(sort_X[:mid], depth + 1),
right=create(sort_X[mid + 1:], depth + 1))
self.root = create(X, 0)
def query(self, x, k=1, p=2):
"""kd树查询目标点的k个最邻近点
Parameters
----------
x: list 目标点
k: int 最邻近点个数 默认为1
p: int 距离度量方法 默认为2 代表欧式距离
Return
------
dist: list k个最邻近点距离(由大到小排列)
ind: list 对应dist的k个最邻近点在X中的索引
"""
self.knn = [(-np.inf, None)] * k
def search_knn(node):
"""query方法的辅助方法。用于访问kd树的结点,并计算结点与目标的距离,
确定k个最邻近的点。
Parameters
----------
node: class kd树的结点
"""
if node is not None:
ax = node.seg_axis
ax_diff = abs(x[ax]-node.seg_point[ax]) # 目标点和结点在ax维度下的距离
if x[ax] < node.seg_point[ax]:
search_knn(node.left)
else:
search_knn(node.right)
# 计算目标点与结点的距离
d = np.linalg.norm(np.array(x)-np.array(node.seg_point), p)
# 利用堆结构存储距离和划分点信息
heapq.heappushpop(self.knn, (-d, node.seg_point))
# 回溯过程中,是否需要进入另一子区域的判断
if ax_diff < -self.knn[0][0]:
if x[ax] < node.seg_point[ax]:
search_knn(node.right)
else:
search_knn(node.left)
search_knn(self.root)
self.knn.sort(reverse=True) # 对k个邻近点进行排序(也可不加这行代码)
dist = []
ind = []
for item in self.knn:
dist.append(abs(item[0]))
ind.append(self.X.index(item[1]))
return dist, ind
class MyKNeighborsClassifier(KDTree):
"""K近邻分类器"""
def __init__(self, X, y, k=1, p=2):
super(MyKNeighborsClassifier, self).__init__(X) # 继承父类的构造方法
self.y = y
self.k = k
self.p = p
def kneighbors(self, x, k=1):
"""获取目标点的k个最邻近点"""
neigh_dist, neigh_ind = self.query(x, k)
return neigh_dist, neigh_ind
def predict(self, x):
"""预测目标点的分类标签"""
_, neigh_ind = self.query(x, self.k)
# 多数服从少数的投票方法
vote = {}
for i in neigh_ind:
vote[self.y[i]] = vote.get(self.y[i], 0) + 1
out = sorted(vote.items(), key=lambda s: s[1], reverse=True)
return out[0][0] | _____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]))
# sklearn
neigh = KNeighborsClassifier(n_neighbors=3, algorithm='kd_tree')
neigh.fit(X, y)
dist, ind = neigh.kneighbors(np.array([[2.5, 4.5]]), n_neighbors=3)
print('sklearn')
print('-------')
print('最邻近点的距离:', dist)
print('最邻近点的索引:', ind)
print('预测类别:', neigh.predict([[2.5, 4.5]])) | 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)
print('最邻近点的索引:', neigh_ind2)
print('预测类别:', clf2.predict([2, 3, 2, 3]))
# sklearn
neigh2 = KNeighborsClassifier(n_neighbors=3, algorithm='kd_tree')
neigh2.fit(X2, y2)
dist2, ind2 = neigh2.kneighbors(np.array([[2, 3, 2, 3]]), n_neighbors=3)
print('sklearn')
print('-------')
print('最邻近点的距离:', dist2)
print('最邻近点的索引:', ind2)
print('预测类别:', neigh2.predict([[2, 3, 2, 3]])) | 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** PRABHA KRAMADHATI 1. Load your Data and Take a Look **a.** **(`15 pts`)** Load the training data (found in the same github repo as this notebook) into this notebook using Pandas. **b.** **(`5 pts`)** Show the first 10 lines of the data. | %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 the link for the product page within the email. The company considers status=2 as a conversion, (statuses 0 and 1 are non-conversions). **a.** **(`10 pts`)** Create a new column called `conversion` that has a value of `1` when the email led to a conversion and is 0 otherwise. | 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 rate
df.isnull().sum()
df.dropna(subset=['Total_Past_Communications'])
df['con_version'] = df['conversion'].apply(lambda x: 'Converted(LinkCliked)' if x == 1 else 'Ignored/Read') | _____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_Communications` by `conversion`. **ii** **(`5 pts`)** How do conversions relate to the number of times a customer had been emailed? You can provide your answer as a comment in its own cell (remember a comment is preceded by a hash symbol `here is my comment`) **iii.** **(`3 pts`)** Set the title to something that briefly summarizes your key insight from the preceding question (3bii). Set the x-label to be `Email Status` and the y-label to be `Previous Emails` **iv** **(`1 pts`)** Prevent the default text `'Boxplot grouped by conversion'` from displaying in the title of the boxplot, and do not show extreme values / outliers. Then show your plot! | 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 made with the first 7-8 emails.
#75% of the converstion were made after the 30th email
#Median number of emails at which customers converted is 10 more than the median of non-converted emails.
| _____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, joining it to all of our numerical variables and generating a train-test split to train and test our model. **a.** **(`5 pts`)** Which columns are categorical columns and which are numerical? Create a list of categorical column names and a list of numerical column names. Ignore the following columns: `Email_ID`, `Email_Status`, `conversion`. You should have ten columns to categorize. Save each list to a variable (e.g., `my_var = ['a', 'b', 'c']`) | 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_Campaign_Type`. **Note/Warning:** This is a bit different than we did in class since we use the `drop_first` argument. `drop_first` means: Don't encode Campaign 1, just tell me how good Campaigns 2 & 3 are in relation to Campaign 1. This is necessary for the model to produce sensible results **ii.** Rename the columns of this dataframe to be `'Campaign_2','Campaign_3'` **iii.** Concatenate this dataframes to the email data dataframe. **iv.** Create a variable called `all_features` that is a list of all the variables we want to use in our model. This will be all numerical variables and the dummy variables `'Campaign_2','Campaign_3'`. | 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_encoded_df], axis=1)
df.head()
all_features=['Subject_Hotness_Score','Total_Past_Communications','Word_Count','Total_Links','Total_Images','Campaign_2','Campaign_3']
response='conversion'
sample_df = df[all_features + [response]]
sample_df.head() | _____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 simply pass `sm.add_constant(df[all_features])` instead of just `df[all_features]`. Finally, add the following argument to train_test_split: `random_state=42` | 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 vs positive coefficients). You can provide your answer as a comment (` Anything following a hash mark is a comment`) or in any other manner you like. | #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.
# Compared to campaign_1, campaign_2 is lot less likely than campaign_3 to lead to a converstion
| _____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 using your model on the specified data. Get predictions by applying the model you just fit to the _test_ data. Save the predictions to a variable. | 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: predictions and the actual value from the data. You already have both of these variables. *You may want to take a look at Chapter 8's Notebook for more details on this metric* | 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 : This notebook serves to test the prediction skill of deep neural networks in emotion recognition and forecast. The convolutional Long Short Time Memory neural network is used to deal with this spatial-temporal sequence problem. We use Pytorch as the deep learning framework. ** Many to one prediction.** Return Values : Time series and figures **This project is a joint venture between NLeSC and CWI** The method comes from the study by Shi et. al. (2015) Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting. | %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 dlacs
import dlacs.BBConvLSTM
import dlacs.ConvLSTM
import dlacs.preprocess
import dlacs.function
import dlacs.saveNetCDF
import dlacs.metric
# for visualization
import dlacs.visual
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm | _____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\\Data_CASE'
output_path = 'C:\\Users\\nosta\\ConvLSTM_emotion\\results'
model_path = 'C:\\Users\\nosta\\ConvLSTM_emotion\\models'
if __name__=="__main__":
print ('*********************** extract variables *************************')
data = np.load(os.path.join(datapath, "data_10s.npz"))
#data = np.load(os.path.join(datapath, "data_2s.npz"))
#data = np.load(os.path.join(datapath, "data_0.5s.npz"))
#################################################################################
######### data gallery #########
#################################################################################
sample = data["Samples"][:] # (batch_size, sample_size, channels)
label_c = data["Labels_c"][:] # (batch_size, sample_size, 2)
label = data["Labels"][:] # (batch_size, 2)
subject = data["Subject_id"][:] # (batch_size, 2)
video_label = data["Video_labels"][:] # (batch_size,1)
# leave-one-out training and testing
num_s = 2
sample_train = sample[np.where(subject!=num_s)[0],:,0:5]
sample_test = sample[np.where(subject==num_s)[0],:,0:5]
label_c_train = label_c[np.where(subject!=num_s)[0],:,:] / 10 # normalize
label_c_test = label_c[np.where(subject==num_s)[0],:,:] / 10 # normalize
#################################################################################
######### pre-processing #########
#################################################################################
# choose the target dimension for reshaping of the signals
batch_train_size, sample_size, channels = sample_train.shape
batch_test_size, _, _ = sample_test.shape
_, _, label_channels = label_c_train.shape
x_dim = 5
y_dim = 5
series_len = sample_size // (y_dim * x_dim)
# reshape the input and labels
sample_train_xy = np.reshape(sample_train,[batch_train_size, series_len, y_dim, x_dim, channels])
sample_test_xy = np.reshape(sample_test,[batch_test_size, series_len, y_dim, x_dim, channels])
label_c_train_xy = np.reshape(label_c_train,[batch_train_size, series_len, y_dim, x_dim, label_channels])
label_c_test_xy = np.reshape(label_c_test,[batch_test_size, series_len, y_dim, x_dim, label_channels])
#################################################################################
######### normalization #########
#################################################################################
print('================ extract individual variables =================')
sample_1 = sample_train_xy[:,:,:,:,0]
sample_2 = sample_train_xy[:,:,:,:,1]
sample_3 = sample_train_xy[:,:,:,:,2]
sample_4 = sample_train_xy[:,:,:,:,3]
sample_5 = sample_train_xy[:,:,:,:,4]
label_c_valance = label_c_train_xy[:,:,:,:,0]
label_c_arousal = label_c_train_xy[:,:,:,:,1]
label_c_test_valance = label_c_test_xy[:,:,:,:,0]
label_c_test_arousal = label_c_test_xy[:,:,:,:,1]
# using indicator for training
# video_label_3D = np.repeat(video_label[:,np.newaxis,:],series_len,1)
# video_label_4D = np.repeat(video_label_3D[:,:,np.newaxis,:],y_dim,2)
# video_label_xy = np.repeat(video_label_4D[:,:,:,np.newaxis,:],x_dim,3)
# video_label_xy.astype(float)
# first check of data shape
print(sample.shape)
print(label_c.shape)
print(label.shape)
print(subject.shape)
print(video_label.shape)
# check of reshape
print(label_c_train_xy.shape) | (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, 3, 3, 3, 2]
#hidden_channels = [2]
kernel_size = 3
# here we input a sequence and predict the next step only
learning_rate = 0.01
num_epochs = 20
# probability of dropout
p = 0.5 # 0.5 for Bernoulli (binary) distribution
print (torch.__version__)
# check if CUDA is available
use_cuda = torch.cuda.is_available()
print("Is CUDA available? {}".format(use_cuda))
# CUDA settings torch.__version__ must > 0.4
# !!! This is important for the model!!! The first option is gpu
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print ('******************* cross validation and testing data *********************')
# mini-batch
mini_batch_size = 64
# iterations
iterations = batch_train_size // mini_batch_size
if batch_train_size % mini_batch_size != 0:
extra_loop = "True"
iterations += 1
%%time
print ('******************* load exsited LSTM model *********************')
# load model parameters
model = dlacs.BBConvLSTM.BBConvLSTM(input_channels, hidden_channels, kernel_size).to(device)
model.load_state_dict(torch.load(os.path.join(model_path, 'BBconvlstm_emotion_hl_3_kernel_3_lr_0.01_epoch_20_mini_64_validSIC.pkl'),
map_location=device))
#model = torch.load(os.path.join(output_path, 'Barents','convlstm_emotion_hl_1_kernel_3_lr_0.01_epoch_500_validSIC.pkl'))
print(model)
# check the sequence length (dimension in need for post-processing)
_, sequence_len, height, width = sample_1.shape
for name, param in model.named_parameters():
if param.requires_grad:
print (name)
print (param.data)
print (param.size())
print ("=========================")
print('##############################################################')
print('############# preview model parameters matrix ###############')
print('##############################################################')
print('Number of parameter matrices: ', len(list(model.parameters())))
for i in range(len(list(model.parameters()))):
print(list(model.parameters())[i].size())
print ('******************* evaluation matrix *********************')
# The prediction will be evaluated through RMSE against climatology
# error score for temporal-spatial fields, without keeping spatial pattern
def RMSE(x,y):
"""
Calculate the RMSE. x is input series and y is reference series.
It calculates RMSE over the domain, not over time. The spatial structure
will not be kept.
Parameter
----------------------
x: input time series with the shape [time, lat, lon]
"""
x_series = x.reshape(x.shape[0],-1)
y_series = y.reshape(y.shape[0],-1)
rmse = np.sqrt(np.mean((x_series - y_series)**2,1))
rmse_std = np.sqrt(np.std((x_series - y_series)**2,1))
return rmse, rmse_std
# error score for temporal-spatial fields, keeping spatial pattern
def MAE(x,y):
"""
Calculate the MAE. x is input series and y is reference series.
It calculate MAE over time and keeps the spatial structure.
"""
mae = np.mean(np.abs(x-y),0)
return mae
def MSE(x, y):
"""
Calculate the MSE. x is input series and y is reference series.
"""
mse = np.mean((x-y)**2)
return mse
%%time
#################################################################################
######## prediction ########
#################################################################################
print('##############################################################')
print('################### start prediction loop ###################')
print('##############################################################')
# forecast array
pred_valance = np.zeros((batch_test_size, series_len, y_dim, x_dim),dtype=float)
pred_arousal = np.zeros((batch_test_size, series_len, y_dim, x_dim),dtype=float)
# calculate loss for each sample
hist_valance = np.zeros(batch_test_size)
hist_arousal = np.zeros(batch_test_size)
for n in range(batch_test_size):
# Clear stored gradient
model.zero_grad()
for timestep in range(sequence_len):
x_input = np.stack((sample_1[n,timestep,:,:],
sample_2[n,timestep,:,:],
sample_3[n,timestep,:,:],
sample_4[n,timestep,:,:],
sample_5[n,timestep,:,:]))
x_var_pred = torch.autograd.Variable(torch.Tensor(x_input).view(-1,input_channels,height,width),
requires_grad=False).to(device)
# make prediction
last_pred, _ = model(x_var_pred, timestep)
# GPU data should be transferred to CPU
pred_valance[n,timestep,:,:] = last_pred[0,0,:,:].cpu().data.numpy()
pred_arousal[n,timestep,:,:] = last_pred[0,1,:,:].cpu().data.numpy()
# compute the error for each sample
hist_valance[n] = MSE(label_c_test_valance[n,:,:,:], pred_valance[n,:,:,:])
hist_arousal[n] = MSE(label_c_test_arousal[n,:,:,:], pred_arousal[n,:,:,:])
# save prediction as npz file
np.savez_compressed(os.path.join(output_path,'BBConvLSTM_emotion_pred.npz'),
valance=pred_valance, arousal=pred_arousal)
# plot the error
print ("******************* Loss with time **********************")
fig00 = plt.figure()
plt.plot(hist_valance, 'r', label="Training loss - valance")
plt.plot(hist_arousal, 'b', label="Training loss - arousal")
plt.xlabel('Sample')
plt.ylabel('MSE Error')
plt.legend()
fig00.savefig(os.path.join(output_path,'BBConvLSTM_pred_mse_error.png'),dpi=150)
#####################################################################################
######## visualization of prediction and implement metrics ########
#####################################################################################
# compute mse
mse_valance = MSE(label_c_test_valance, pred_valance)
print(mse_valance)
mse_arousal = MSE(label_c_test_arousal, pred_arousal)
print(mse_arousal)
# save output as csv file
with open(os.path.join(output_path, "MSE_BBConvLSTM_emotion.csv"), "wt+") as fp:
writer = csv.writer(fp, delimiter=",")
writer.writerow(["emotion prediction"]) # write header
writer.writerow(["label valance"])
writer.writerow([mse_valance])
writer.writerow(["label arousal"])
writer.writerow([mse_arousal])
%%time
#################################################################################
######## prediction of single subject ########
#################################################################################
| _____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, GANs can provide useful data augmentation that substantially [improve classifier performance](https://arxiv.org/abs/1711.04340). - You have one type of data already labeled and would like to make predictions on [another related dataset for which you have no labels](https://www.nature.com/articles/s41598-019-52737-x). (You'll learn about the techniques for this use case in future notebooks!)- You want to protect the privacy of the people who provided their information so you can provide access to a [generator instead of real data](https://www.ahajournals.org/doi/full/10.1161/CIRCOUTCOMES.118.005122). - You have [input data with many missing values](https://arxiv.org/abs/1806.02920), where the input dimensions are correlated and you would like to train a model on complete inputs. - You would like to be able to identify a real-world abnormal feature in an image [for the purpose of diagnosis](https://link.springer.com/chapter/10.1007/978-3-030-00946-5_11), but have limited access to real examples of the condition. In this assignment, you're going to be acting as a bug enthusiast — more on that later. Learning Objectives1. Understand some use cases for data augmentation and why GANs suit this task.2. Implement a classifier that takes a mixed dataset of reals/fakes and analyze its accuracy. Getting Started Data AugmentationBefore you implement GAN-based data augmentation, you should know a bit about data augmentation in general, specifically for image datasets. It is [very common practice](https://arxiv.org/abs/1712.04621) to augment image-based datasets in ways that are appropriate for a given dataset. This may include having your dataloader randomly flipping images across their vertical axis, randomly cropping your image to a particular size, randomly adding a bit of noise or color to an image in ways that are true-to-life. In general, data augmentation helps to stop your model from overfitting to the data, and allows you to make small datasets many times larger. However, a sufficiently powerful classifier often still overfits to the original examples which is why GANs are particularly useful here. They can generate new images instead of simply modifying existing ones. CIFARThe [CIFAR-10 and CIFAR-100](https://www.cs.toronto.edu/~kriz/learning-features-2009-TR.pdf) datasets are extremely widely used within machine learning -- they contain many thousands of “tiny” 32x32 color images of different classes representing relatively common real-world objects like airplanes and dogs, with 10 classes in CIFAR-10 and 100 classes in CIFAR-100. In CIFAR-100, there are 20 “superclasses” which each contain five classes. For example, the “fish” superclass contains “aquarium fish, flatfish, ray, shark, trout”. For the purposes of this assignment, you’ll be looking at a small subset of these images to simulate a small data regime, with only 40 images of each class for training. InitializationsYou will begin by importing some useful libraries and packages and defining a visualization function that has been provided. You will also be re-using your conditional generator and functions code from earlier assignments. This will let you control what class of images to augment for your classifier. | 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 show_tensor_images(image_tensor, num_images=25, size=(3, 32, 32), nrow=5, show=True):
'''
Function for visualizing images: Given a tensor of images, number of images, and
size per image, plots and prints the images in an uniform grid.
'''
image_tensor = (image_tensor + 1) / 2
image_unflat = image_tensor.detach().cpu()
image_grid = make_grid(image_unflat[:num_images], nrow=nrow)
plt.imshow(image_grid.permute(1, 2, 0).squeeze())
if show:
plt.show() | _____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, a scalar
'''
def __init__(self, input_dim=10, im_chan=3, hidden_dim=64):
super(Generator, self).__init__()
self.input_dim = input_dim
# Build the neural network
self.gen = nn.Sequential(
self.make_gen_block(input_dim, hidden_dim * 4, kernel_size=4),
self.make_gen_block(hidden_dim * 4, hidden_dim * 2, kernel_size=4, stride=1),
self.make_gen_block(hidden_dim * 2, hidden_dim, kernel_size=4),
self.make_gen_block(hidden_dim, im_chan, kernel_size=2, final_layer=True),
)
def make_gen_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False):
'''
Function to return a sequence of operations corresponding to a generator block of DCGAN;
a transposed convolution, a batchnorm (except in the final layer), and an activation.
Parameters:
input_channels: how many channels the input feature representation has
output_channels: how many channels the output feature representation should have
kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)
stride: the stride of the convolution
final_layer: a boolean, true if it is the final layer and false otherwise
(affects activation and batchnorm)
'''
if not final_layer:
return nn.Sequential(
nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),
nn.BatchNorm2d(output_channels),
nn.ReLU(inplace=True),
)
else:
return nn.Sequential(
nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),
nn.Tanh(),
)
def forward(self, noise):
'''
Function for completing a forward pass of the generator: Given a noise tensor,
returns generated images.
Parameters:
noise: a noise tensor with dimensions (n_samples, input_dim)
'''
x = noise.view(len(noise), self.input_dim, 1, 1)
return self.gen(x)
def get_noise(n_samples, input_dim, device='cpu'):
'''
Function for creating noise vectors: Given the dimensions (n_samples, input_dim)
creates a tensor of that shape filled with random numbers from the normal distribution.
Parameters:
n_samples: the number of samples to generate, a scalar
input_dim: the dimension of the input vector, a scalar
device: the device type
'''
return torch.randn(n_samples, input_dim, device=device)
def combine_vectors(x, y):
'''
Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?)
Parameters:
x: (n_samples, ?) the first vector.
In this assignment, this will be the noise vector of shape (n_samples, z_dim),
but you shouldn't need to know the second dimension's size.
y: (n_samples, ?) the second vector.
Once again, in this assignment this will be the one-hot class vector
with the shape (n_samples, n_classes), but you shouldn't assume this in your code.
'''
return torch.cat([x, y], 1)
def get_one_hot_labels(labels, n_classes):
'''
Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?)
Parameters:
labels: (n_samples, 1)
n_classes: a single integer corresponding to the total number of classes in the dataset
'''
return F.one_hot(labels, n_classes) | _____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, bird, cat, deer, dog, frog, horse, ship, truck) | 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 number of images per forward/backward pass * lr: the learning rate * device: the device type | # 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, hidden_dim=32):
super(Classifier, self).__init__()
self.disc = nn.Sequential(
self.make_classifier_block(im_chan, hidden_dim),
self.make_classifier_block(hidden_dim, hidden_dim * 2),
self.make_classifier_block(hidden_dim * 2, hidden_dim * 4),
self.make_classifier_block(hidden_dim * 4, n_classes, final_layer=True),
)
def make_classifier_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False):
'''
Function to return a sequence of operations corresponding to a classifier block;
a convolution, a batchnorm (except in the final layer), and an activation (except in the final
Parameters:
input_channels: how many channels the input feature representation has
output_channels: how many channels the output feature representation should have
kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)
stride: the stride of the convolution
final_layer: a boolean, true if it is the final layer and false otherwise
(affects activation and batchnorm)
'''
if not final_layer:
return nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, stride),
nn.BatchNorm2d(output_channels),
nn.LeakyReLU(0.2, inplace=True),
)
else:
return nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, stride),
)
def forward(self, image):
'''
Function for completing a forward pass of the classifier: Given an image tensor,
returns an n_classes-dimension tensor representing fake/real.
Parameters:
image: a flattened image tensor with im_chan channels
'''
class_pred = self.disc(image)
return class_pred.view(len(class_pred), -1) | _____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 channels of the output image, a scalar
(MNIST is black-and-white, so 1 channel is your default)
hidden_dim: the inner dimension, a scalar
'''
def __init__(self, im_chan=3, hidden_dim=64):
super(Discriminator, self).__init__()
self.disc = nn.Sequential(
self.make_disc_block(im_chan, hidden_dim, stride=1),
self.make_disc_block(hidden_dim, hidden_dim * 2),
self.make_disc_block(hidden_dim * 2, hidden_dim * 4),
self.make_disc_block(hidden_dim * 4, 1, final_layer=True),
)
def make_disc_block(self, input_channels, output_channels, kernel_size=4, stride=2, final_layer=False):
'''
Function to return a sequence of operations corresponding to a discriminator block of the DCGAN;
a convolution, a batchnorm (except in the final layer), and an activation (except in the final layer).
Parameters:
input_channels: how many channels the input feature representation has
output_channels: how many channels the output feature representation should have
kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)
stride: the stride of the convolution
final_layer: a boolean, true if it is the final layer and false otherwise
(affects activation and batchnorm)
'''
if not final_layer:
return nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, stride),
nn.BatchNorm2d(output_channels),
nn.LeakyReLU(0.2, inplace=True),
)
else:
return nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, stride),
)
def forward(self, image):
'''
Function for completing a forward pass of the discriminator: Given an image tensor,
returns a 1-dimension tensor representing fake/real.
Parameters:
image: a flattened image tensor with dimension (im_chan)
'''
disc_pred = self.disc(image)
return disc_pred.view(len(disc_pred), -1)
def train_generator():
gen = Generator(generator_input_dim).to(device)
gen_opt = torch.optim.Adam(gen.parameters(), lr=lr)
discriminator_input_dim = cifar100_shape[0] + n_classes
disc = Discriminator(discriminator_input_dim).to(device)
disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)
def weights_init(m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
torch.nn.init.normal_(m.weight, 0.0, 0.02)
if isinstance(m, nn.BatchNorm2d):
torch.nn.init.normal_(m.weight, 0.0, 0.02)
torch.nn.init.constant_(m.bias, 0)
gen = gen.apply(weights_init)
disc = disc.apply(weights_init)
criterion = nn.BCEWithLogitsLoss()
cur_step = 0
mean_generator_loss = 0
mean_discriminator_loss = 0
for epoch in range(n_epochs):
# Dataloader returns the batches and the labels
for real, labels in dataloader:
cur_batch_size = len(real)
# Flatten the batch of real images from the dataset
real = real.to(device)
# Convert the labels from the dataloader into one-hot versions of those labels
one_hot_labels = get_one_hot_labels(labels.to(device), n_classes).float()
image_one_hot_labels = one_hot_labels[:, :, None, None]
image_one_hot_labels = image_one_hot_labels.repeat(1, 1, cifar100_shape[1], cifar100_shape[2])
### Update discriminator ###
# Zero out the discriminator gradients
disc_opt.zero_grad()
# Get noise corresponding to the current batch_size
fake_noise = get_noise(cur_batch_size, z_dim, device=device)
# Combine the vectors of the noise and the one-hot labels for the generator
noise_and_labels = combine_vectors(fake_noise, one_hot_labels)
fake = gen(noise_and_labels)
# Combine the vectors of the images and the one-hot labels for the discriminator
fake_image_and_labels = combine_vectors(fake.detach(), image_one_hot_labels)
real_image_and_labels = combine_vectors(real, image_one_hot_labels)
disc_fake_pred = disc(fake_image_and_labels)
disc_real_pred = disc(real_image_and_labels)
disc_fake_loss = criterion(disc_fake_pred, torch.zeros_like(disc_fake_pred))
disc_real_loss = criterion(disc_real_pred, torch.ones_like(disc_real_pred))
disc_loss = (disc_fake_loss + disc_real_loss) / 2
disc_loss.backward(retain_graph=True)
disc_opt.step()
# Keep track of the average discriminator loss
mean_discriminator_loss += disc_loss.item() / display_step
### Update generator ###
# Zero out the generator gradients
gen_opt.zero_grad()
# Pass the discriminator the combination of the fake images and the one-hot labels
fake_image_and_labels = combine_vectors(fake, image_one_hot_labels)
disc_fake_pred = disc(fake_image_and_labels)
gen_loss = criterion(disc_fake_pred, torch.ones_like(disc_fake_pred))
gen_loss.backward()
gen_opt.step()
# Keep track of the average generator loss
mean_generator_loss += gen_loss.item() / display_step
if cur_step % display_step == 0 and cur_step > 0:
print(f"Step {cur_step}: Generator loss: {mean_generator_loss}, discriminator loss: {mean_discriminator_loss}")
show_tensor_images(fake)
show_tensor_images(real)
mean_generator_loss = 0
mean_discriminator_loss = 0
cur_step += 1
def train_classifier():
criterion = nn.CrossEntropyLoss()
n_epochs = 10
validation_dataloader = DataLoader(
CIFAR100(".", train=False, download=True, transform=transform),
batch_size=batch_size)
display_step = 10
batch_size = 512
lr = 0.0002
device = 'cuda'
classifier = Classifier(cifar100_shape[0], n_classes).to(device)
classifier_opt = torch.optim.Adam(classifier.parameters(), lr=lr)
cur_step = 0
for epoch in range(n_epochs):
for real, labels in tqdm(dataloader):
cur_batch_size = len(real)
real = real.to(device)
labels = labels.to(device)
### Update classifier ###
# Get noise corresponding to the current batch_size
classifier_opt.zero_grad()
labels_hat = classifier(real.detach())
classifier_loss = criterion(labels_hat, labels)
classifier_loss.backward()
classifier_opt.step()
if cur_step % display_step == 0:
classifier_val_loss = 0
classifier_correct = 0
num_validation = 0
for val_example, val_label in validation_dataloader:
cur_batch_size = len(val_example)
num_validation += cur_batch_size
val_example = val_example.to(device)
val_label = val_label.to(device)
labels_hat = classifier(val_example)
classifier_val_loss += criterion(labels_hat, val_label) * cur_batch_size
classifier_correct += (labels_hat.argmax(1) == val_label).float().sum()
print(f"Step {cur_step}: "
f"Classifier loss: {classifier_val_loss.item() / num_validation}, "
f"classifier accuracy: {classifier_correct.item() / num_validation}")
cur_step += 1
| _____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 different species of bugs: bees, beetles, butterflies, caterpillar, and more. Luckily, you found a great dataset with a lot of animal species and objects, and you trained your classifier on that.But the bug classes don't do as well as you would like. Now your plan is to train a GAN on the same data so it can generate new bugs to make your classifier better at distinguishing between all of your favorite bugs!You will fine-tune your model by augmenting the original real data with fake data and during that process, observe how to increase the accuracy of your classifier with these fake, GAN-generated bugs. After this, you will prove your worth as a bug master. Sampling RatioSuppose that you've decided that although you have this pre-trained general generator and this general classifier, capable of identifying 100 classes with some accuracy (~17%), what you'd really like is a model that can classify the five different kinds of bugs in the dataset. You'll fine-tune your model by augmenting your data with the generated images. Keep in mind that both the generator and the classifier were trained on the same images: the 40 images per class you painstakingly found so your generator may not be great. This is the caveat with data augmentation, ultimately you are still bound by the real data that you have but you want to try and create more. To make your models even better, you would need to take some more bug photos, label them, and add them to your training set and/or use higher quality photos.To start, you'll first need to write some code to sample a combination of real and generated images. Given a probability, `p_real`, you'll need to generate a combined tensor where roughly `p_real` of the returned images are sampled from the real images. Note that you should not interpolate the images here: you should choose each image from the real or fake set with a given probability. For example, if your real images are a tensor of `[[1, 2, 3, 4, 5]]` and your fake images are a tensor of `[[-1, -2, -3, -4, -5]]`, and `p_real = 0.2`, two potential return values are `[[1, -2, 3, -4, -5]]` or `[[-1, 2, -3, -4, -5]]`In addition, we will expect the images to remain in the same order to maintain their alignment with their labels (this applies to the fake images too!). Optional hints for combine_sample1. This code probably shouldn't be much longer than 3 lines2. You can index using a set of booleans which have the same length as your tensor3. You want to generate an unbiased sample, which you can do (for example) with `torch.rand(length_reals) > p`.4. There are many approaches here that will give a correct answer here. You may find [`torch.rand`](https://pytorch.org/docs/stable/generated/torch.rand.html) or [`torch.bernoulli`](https://pytorch.org/docs/master/generated/torch.bernoulli.html) useful. 5. You don't want to edit an argument in place, so you may find [`cur_tensor.clone()`](https://pytorch.org/docs/stable/tensors.html) useful too, which makes a copy of `cur_tensor`. | # 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: a tensor of real images, length (x)
fake: a tensor of fake images, length (x)
p_real: the probability the images are sampled from the real set
'''
#### START CODE HERE ####
assert real.device == fake.device
assert p_real>=0 and p_real<=1
assert real.shape == fake.shape
device = real.device
chosen = torch.rand(real.shape[0], device=device) < p_real
target_images = torch.zeros((real.shape), device=device)
target_images[chosen] = real[chosen]
target_images[~chosen] = fake[~chosen]
#### END CODE HERE ####
return target_images
n_test_samples = 9999
test_combination = combine_sample(
torch.ones(n_test_samples, 1),
torch.zeros(n_test_samples, 1),
0.3
)
# Check that the shape is right
assert tuple(test_combination.shape) == (n_test_samples, 1)
# Check that the ratio is right
assert torch.abs(test_combination.mean() - 0.3) < 0.05
# Make sure that no mixing happened
assert test_combination.median() < 1e-5
test_combination = combine_sample(
torch.ones(n_test_samples, 10, 10),
torch.zeros(n_test_samples, 10, 10),
0.8
)
# Check that the shape is right
assert tuple(test_combination.shape) == (n_test_samples, 10, 10)
# Make sure that no mixing happened
assert torch.abs((test_combination.sum([1, 2]).median()) - 100) < 1e-5
test_reals = torch.arange(n_test_samples)[:, None].float()
test_fakes = torch.zeros(n_test_samples, 1)
test_saved = (test_reals.clone(), test_fakes.clone())
test_combination = combine_sample(test_reals, test_fakes, 0.3)
# Make sure that the sample isn't biased
assert torch.abs((test_combination.mean() - 1500)) < 100
# Make sure no inputs were changed
assert torch.abs(test_saved[0] - test_reals).sum() < 1e-3
assert torch.abs(test_saved[1] - test_fakes).sum() < 1e-3
test_fakes = torch.arange(n_test_samples)[:, None].float()
test_combination = combine_sample(test_reals, test_fakes, 0.3)
# Make sure that the order is maintained
assert torch.abs(test_combination - test_reals).sum() < 1e-4
if torch.cuda.is_available():
# Check that the solution matches the input device
assert str(combine_sample(
torch.ones(n_test_samples, 10, 10).cuda(),
torch.zeros(n_test_samples, 10, 10).cuda(),
0.8
).device).startswith("cuda")
print("Success!") | 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 takes a very long time to run, you may need to hard-code the solution it finds. When you're training a generator, you will often have to look at different checkpoints and choose one that does the best (either empirically or using some evaluation method). Here, you are given four generator checkpoints: `gen_1.pt`, `gen_2.pt`, `gen_3.pt`, `gen_4.pt`. You'll also have some scratch area to write whatever code you'd like to solve this problem, but you must return a `p_real` and an image name of your selected generator checkpoint. You can hard-code/brute-force these numbers if you would like, but you are encouraged to try to solve this problem in a more general way. In practice, you would also want a test set (since it is possible to overfit on a validation set), but for simplicity you can just focus on the validation set. | # 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.pt",
"gen_3.pt",
"gen_4.pt"
]
p_real = [0.1*x for x in range(1,10)]
best_so_far = 0
#### START CODE HERE ####
for p in p_real:
for gen in gen_names:
avg_acc = eval_augmentation(p, gen, n_test=3)
if avg_acc > best_so_far:
best_so_far = avg_acc
best_p_real = p
best_gen_name = gen
#### END CODE HERE ####
return best_p_real, best_gen_name
def augmented_train(p_real, gen_name):
gen = Generator(generator_input_dim).to(device)
gen.load_state_dict(torch.load(gen_name))
classifier = Classifier(cifar100_shape[0], n_classes).to(device)
classifier.load_state_dict(torch.load("class.pt"))
criterion = nn.CrossEntropyLoss()
batch_size = 256
train_set = torch.load("insect_train.pt")
val_set = torch.load("insect_val.pt")
dataloader = DataLoader(
torch.utils.data.TensorDataset(train_set["images"], train_set["labels"]),
batch_size=batch_size,
shuffle=True
)
validation_dataloader = DataLoader(
torch.utils.data.TensorDataset(val_set["images"], val_set["labels"]),
batch_size=batch_size
)
display_step = 1
lr = 0.0002
n_epochs = 20
classifier_opt = torch.optim.Adam(classifier.parameters(), lr=lr)
cur_step = 0
best_score = 0
for epoch in range(n_epochs):
for real, labels in dataloader:
real = real.to(device)
# Flatten the image
labels = labels.to(device)
one_hot_labels = get_one_hot_labels(labels.to(device), n_classes).float()
### Update classifier ###
# Get noise corresponding to the current batch_size
classifier_opt.zero_grad()
cur_batch_size = len(labels)
fake_noise = get_noise(cur_batch_size, z_dim, device=device)
noise_and_labels = combine_vectors(fake_noise, one_hot_labels)
fake = gen(noise_and_labels)
target_images = combine_sample(real.clone(), fake.clone(), p_real)
labels_hat = classifier(target_images.detach())
classifier_loss = criterion(labels_hat, labels)
classifier_loss.backward()
classifier_opt.step()
# Calculate the accuracy on the validation set
if cur_step % display_step == 0 and cur_step > 0:
classifier_val_loss = 0
classifier_correct = 0
num_validation = 0
with torch.no_grad():
for val_example, val_label in validation_dataloader:
cur_batch_size = len(val_example)
num_validation += cur_batch_size
val_example = val_example.to(device)
val_label = val_label.to(device)
labels_hat = classifier(val_example)
classifier_val_loss += criterion(labels_hat, val_label) * cur_batch_size
classifier_correct += (labels_hat.argmax(1) == val_label).float().sum()
accuracy = classifier_correct.item() / num_validation
if accuracy > best_score:
best_score = accuracy
cur_step += 1
return best_score
def eval_augmentation(p_real, gen_name, n_test=20):
total = 0
for i in range(n_test):
total += augmented_train(p_real, gen_name)
return total / n_test
best_p_real, best_gen_name = find_optimal()
performance = eval_augmentation(best_p_real, best_gen_name)
print(f"Your model had an accuracy of {performance:0.1%}")
assert performance > 0.51
print("Success!") | 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_labels = combine_vectors(fake_noise, one_hot_labels)
gen = Generator(generator_input_dim).to(device)
gen.load_state_dict(torch.load(best_gen_name))
fake = gen(noise_and_labels)
show_tensor_images(torch.cat([train_images.cpu(), fake.cpu()])) | _____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/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:527: 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_quint8 = np.dtype([("quint8", np.uint8, 1)])
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:528: 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_qint16 = np.dtype([("qint16", np.int16, 1)])
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:529: 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_quint16 = np.dtype([("quint16", np.uint16, 1)])
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:530: 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_qint32 = np.dtype([("qint32", np.int32, 1)])
/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:535: 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_resource = np.dtype([("resource", np.ubyte, 1)])
| 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_size=32):
"""Strip large constant values from graph_def."""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
tensor = n.attr['value'].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
tensor.tensor_content = b"<stripped %d bytes>"%size
return strip_def
def show_graph(graph_def, max_const_size=32):
"""Visualize TensorFlow graph."""
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = strip_consts(graph_def, max_const_size=max_const_size)
code = """
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
""".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
iframe = """
<iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
""".format(code.replace('"', '"'))
display(HTML(iframe))
show_graph(tf.get_default_graph()) | _____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 apart and either 260um or 520um in diameter.- `p2p.implants.ArgusII`: The A60 array has 60 electrodes arranged in a 6x10 grid. Electrodes are 525um apart and 200um in diameter.If you are running this code in a Jupyter Notebook, you can see what arguments these objects take by starting to type the object's name, then hitting Shift+TAB: argus = p2p.implants.ArgusII(Shift+TAB If you want to see more of the documentation, hit TAB again while still holding down Shift (so it's Shift+TAB+TAB). | # 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.- `'joblib'`: Use JobLib for paralellization. Specify the number of jobs via `n_jobs`.- `'dask'`: Use Dask for parallelization. Specify the number of jobs via `n_jobs` | # 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 layer (GCL), where the ganglion cell bodies live.- `set_bipolar_cell_layer`: Coming soon. In `set_optic_fiber_layer`, you can specify parameters such as the spatial sampling rate (`s_sample` in microns), or the dimensions of the retinal grid to simulate: | # 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, x_range=(-3500, 1500),
n_axons=501, n_rho=801, rho_range=(4, 45),
sensitivity_rule='decay', decay_const=5.0,
contribution_rule='max') | 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 temporal sensitivity as described in Horsager et al. (IOVS, 2009).You can also create your own custom model (see [0.3-add-your-own-model.ipynb](0.3-add-your-own-model.ipynb)). | # 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.- `PulseTrain`: A pulse train made from individual biphasic pulses with a specific amplitude, frequency, and duration.- `image2pulsetrain`: Converts an image to a series of pulse trains (pixel-by-pixel).- `video2pulsetrain`: Converts a video to a series of pulse trains (pixel-by-pixel). | # 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. Basic Plotting To begin start by investigating the introductory notebooks: 1. [Introduction](Introduction.ipynb) - If you're new to `bqplot`, get started with our Introduction notebook2. [Basic Plotting](Basic Plotting/Basic Plotting.ipynb) - which demonstrates some basic `bqplot` plotting commands and how to use them3. [Pyplot](Basic Plotting/Pyplot.ipynb) - which introduces the simpler `pyplot` API Marks Move to exploring the different `Marks` that you can use to represent your data. You have two options for rendering marks:* Object Model, which is a verbose API but gives you full flexibility and customizability* Pyplot, which is a simpler API (similar to matplotlib's pyplot) and sets meaningul defaults for the user1. Bars: Bar mark ([Object Model](Marks/Object Model/Bars.ipynb), [Pyplot](Marks/Pyplot/Bars.ipynb))* Bins: Backend histogram mark ([Object Model](Marks/Object Model/Bins.ipynb), [Pyplot](Marks/Pyplot/Bins.ipynb))* Boxplot: Boxplot mark ([Object Model](Marks/Object Model/Boxplot.ipynb), [Pyplot](Marks/Pyplot/Boxplot.ipynb))* Candles: OHLC mark ([Object Model](Marks/Object Model/Candles.ipynb), [Pyplot](Marks/Pyplot/Candles.ipynb))* FlexLine: Flexible lines mark ([Object Model](Marks/Object Model/Flexline.ipynb), Pyplot)* Graph: Network mark ([Object Model](Marks/Object Model/Graph.ipynb), Pyplot)* GridHeatMap: Grid heatmap mark ([Object Model](Marks/Object Model/GridHeatMap.ipynb), [Pyplot](Marks/Pyplot/GridHeatMap.ipynb))* HeatMap: Heatmap mark ([Object Model](Marks/Object Model/HeatMap.ipynb), [Pyplot](Marks/Pyplot/HeatMap.ipynb))* Hist: Histogram mark ([Object Model](Marks/Object Model/Hist.ipynb), [Pyplot](Marks/Pyplot/Hist.ipynb))* Image: Image mark ([Object Model](Marks/Object Model/Image.ipynb), [Pyplot](Marks/Pyplot/Image.ipynb))* Label: Label mark ([Object Model](Marks/Object Model/Label.ipynb), [Pyplot](Marks/Pyplot/Label.ipynb))* Lines: Lines mark ([Object Model](Marks/Object Model/Lines.ipynb), [Pyplot](Marks/Pyplot/Lines.ipynb))* Map: Geographical map mark ([Object Model](Marks/Object Model/Map.ipynb), [Pyplot](Marks/Pyplot/Map.ipynb))* Market Map: Tile map mark ([Object Model](Marks/Object Model/Market Map.ipynb), Pyplot)* Pie: Pie mark ([Object Model](Marks/Object Model/Pie.ipynb), [Pyplot](Marks/Pyplot/Pie.ipynb))* Scatter: Scatter mark ([Object Model](Marks/Object Model/Scatter.ipynb), [Pyplot](Marks/Pyplot/Scatter.ipynb)) Interactions Learn how to use `bqplot` interactions to convert your plots into interactive applications: 13. [Mark Interactions](Interactions/Mark Interactions.ipynb) - which describes the mark specific interactions and how to use them14. [Interaction Layer](Interactions/Interaction Layer.ipynb) - which describes the use of the interaction layers, including selectors and how they can be used for facilitating better interaction Advanced Plotting Once you've mastered the basics of `bqplot`, you can use these notebooks to learn about some of it's more advanced features. 15. [Plotting Dates](Advanced Plotting/Plotting Dates.ipynb)16. [Advanced Plotting](Advanced Plotting/Advanced Plotting.ipynb)17. [Animations](Advanced Plotting/Animations.ipynb)18. [Axis Properties](Advanced Plotting/Axis Properties.ipynb) Applications Finally, we have a collection of notebooks that demonstrate how to use `bqplot` and `ipywidgets` to create advanced interactive applications. 19. [Wealth of Nations](Applications/Wealth of Nations.ipynb) - a recreation of [Hans Rosling's famous TED Talk](http://www.ted.com/talks/hans_rosling_shows_the_best_stats_you_ve_ever_seen) Help For more help, - Reach out to us via the `ipywidgets` gitter chat [](https://gitter.im/ipython/ipywidgets?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)- Or take a look at a talk given on Interactive visualizations in Jupyter at PyData | 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. | _____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 this guide, you will fit these all together to train models.TensorFlow also includes the [tf.Keras API](keras/overview.ipynb), a high-level neural network API that provides useful abstractions to reduce boilerplate. However, in this guide, you will use basic classes. Setup | 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 variables to fit the data. - Evaluate your results.For illustration purposes, in this guide you'll develop a simple linear model, $f(x) = x * W + b$, which has two variables: $W$ (weights) and $b$ (bias).This is the most basic of machine learning problems: Given $x$ and $y$, try to find the slope and offset of a line via [simple linear regression](https://en.wikipedia.org/wiki/Linear_regressionSimple_and_multiple_linear_regression). DataSupervised learning uses *inputs* (usually denoted as *x*) and *outputs* (denoted *y*, often called *labels*). The goal is to learn from paired inputs and outputs so that you can predict the value of an output from an input.Each input of your data, in TensorFlow, is almost always represented by a tensor, and is often a vector. In supervised training, the output (or value you'd like to predict) is also a tensor.Here is some data synthesized by adding Gaussian (Normal) noise to points along a line. | # 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(x, y, c="b")
plt.show() | _____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.Variable` to represent all weights in a model. A `tf.Variable` stores a value and provides this in tensor form as needed. See the [variable guide](./variable.ipynb) for more details.Use `tf.Module` to encapsulate the variables and the computation. You could use any Python object, but this way it can be easily saved.Here, you define both *w* and *b* as variables. | 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.b
model = MyModel()
# List the variables tf.modules's built-in variable aggregation.
print("Variables:", model.variables)
# Verify the model works
assert model(3.0).numpy() == 15.0 | _____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 matches the target output. The goal is to minimize this difference during training. Define the standard L2 loss, also known as the "mean squared" error: | # 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 gradientsFor this example, you can train the model using [gradient descent](https://en.wikipedia.org/wiki/Gradient_descent).There are many variants of the gradient descent scheme that are captured in `tf.keras.optimizers`. But in the spirit of building from first principles, here you will implement the basic math yourself with the help of `tf.GradientTape` for automatic differentiation and `tf.assign_sub` for decrementing a value (which combines `tf.assign` and `tf.sub`): | # 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, db = t.gradient(current_loss, [model.w, model.b])
# Subtract the gradient scaled by the learning rate
model.w.assign_sub(learning_rate * dw)
model.b.assign_sub(learning_rate * db) | _____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 update
Ws.append(model.w.numpy())
bs.append(model.b.numpy())
current_loss = loss(y, model(x))
print("Epoch %2d: W=%1.2f b=%1.2f, loss=%2.5f" %
(epoch, Ws[-1], bs[-1], current_loss))
print("Starting: W=%1.2f b=%1.2f, loss=%2.5f" %
(model.w, model.b, loss(y, model(x))))
# Do the training
training_loop(model, x, y)
# Plot it
plt.plot(epochs, Ws, "r",
epochs, bs, "b")
plt.plot([TRUE_W] * len(epochs), "r--",
[TRUE_B] * len(epochs), "b--")
plt.legend(["W", "b", "True W", "True b"])
plt.show()
# Visualize how the trained model performs
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 |
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):
return self.w * x + self.b
keras_model = MyModelKeras()
# Reuse the training loop with a Keras model
training_loop(keras_model, x, y)
# You can also save a checkpoint using Keras's built-in support
keras_model.save_weights("my_checkpoint") | _____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 less code to use Keras implementations of L2 loss and gradient descent, again as a shortcut. Keras losses and optimizers can be used outside of these convenience functions, too, and the previous example could have used them. | 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(learning_rate=0.1),
# Keras comes with built-in MSE error
# However, you could use the loss function
# defined above
loss=tf.keras.losses.mean_squared_error,
) | _____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 details: PEP8 Practices: https://www.python.org/dev/peps/pep-0008/ Check PEP8: http://pep8online.com Python Reference: https://www.py4e.com/lessons Do use Google efficiently, and refer to StackOverflow for clarifying any programming doubts. If you're still stuck, feel free to ask a TA to help you.Each task in the assignment comprises of at least two cells. There are function definitions wherein you will name the function(s), and write code to solve the problem at hand. You will call the function(s) in the last cell of each task, and check your output.We encourage you to play around and learn as much as possible, and be as creative as you can get. More than anything, have fun doing these assignments. Enjoy! Important* **Only the imports and functions must be present when you upload this notebook to GitHub for verification.** * **Do not upload it until you want to get it verified. Do not change function names or add extra cells or code, or remove anything.*** **For your rough work and four showing your code to TAs, use a different notebook with the name Module2Playground.ipynb and copy only the final functions to this notebook for verification.** Module 3Scope: Algorithmic Thinking, Programming Imports - Always Execute First!Import any modules and turn on any magic here: | 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
Create a program to randomly generate the orders of each customer as a string of numbers
(corresponding to the item) and calculate the cost of the order. For example, if the generated
string is 5712335, the program should understand that the customer has ordered 1 burger, 1
portion of nuggets, 2 portions of fries, 2 medium drinks and 1 salad. It should then compute the
cost ($17.50). The final cost is calculated after considering discounts for combo offers and
adding 18% GST.
The combo offers are:
A) 1 Burger + 1 Portion of Fries + 1 Drink -> 20% discount
B) 1 Burger + 1 Portion of Nuggets + 1 Salad + 1 Drink -> 35% discount
The final cost of the 5712335 order is $13.4225. The profit gained each day has to be recorded for
30 days and plotted for analysis.
Note:
- There will be at least 20 customers and not more than 50 customers per day. Each customer
orders at least 3 items and not more than 7 items.
- If there is a possibility of availing multiple combo offers in an order, the program
should select the offer with maximum discount.
"""
def generate_order():
"""
Function 1: generate_order()
Return: A randomly generated order string
"""
import random
s=random.randint(3,7)
num_list=[]
for i in range(s):
num_list.append(random.randint(0,7))
# print(num_list)
list_to_str="".join(map(str,num_list))
# list_to_str=" ".join(map(str,num_list))
return list_to_str
generate_order()
def compute_cost(order):
"""
Function 2: compute_cost(order)
Parameters: order (String)
Return: Final cost of order
"""
int_list=[]
for ch in order:
int_list.append(int(ch))
# print(int_list)
l=[4.25,2.50,2.00,1.25,1.50,1.75,3.75]
total=0
for i in int_list:
for j in range(len(l)):
if i==j+1:
total=total+l[j]
# print(total)
discount=0
if all(x in int_list for x in [1,3,5]) or all(x in int_list for x in [1,3,4]) or all(x in int_list for x in [1,3,6]):
discount=total*0.8
if all(x in int_list for x in [1,2,7,4]) or all(x in int_list for x in [1,2,7,5]) or all(x in int_list for x in [1,2,7,6]):
discount=total*0.65
if all(x in int_list for x in [1,2,7,3,4] or all(x in int_list for x in [1,2,7,3,5]) or all(x in int_list for x in [1,2,7,3,6])):
discount=total*0.65
else:
discount=total
# print(discount)
sum=discount*1.18
return sum
order=generate_order()
compute_cost(order)
def simulate_restaurant():
"""
Function 3: simulate_restaurant()
Purpose: Simulate the restaurant's operation using the previously declared functions,
based on the constraints mentioned in the question
Output: Plot of profit over 30 days
"""
import random
import matplotlib.pyplot as plt
profit=[]
t=list(range(1,31))
# print(t)
daily=0
total=0
for i in range(0,30):
n=random.randint(20,51)
daily=0
for j in range(0,n):
x=generate_order()
daily+=compute_cost(x)
profit.append(daily)
print(profit)
plt.scatter(profit,t)
simulate_restaurant() | [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, 459.6099999999999, 289.09999999999997, 597.0800000000002, 335.7099999999999, 441.90999999999997, 369.34000000000003, 467.86999999999995]
| MIT | Module3 (1).ipynb | Manassss/pythonassignments |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License.  Train and explain models locally and deploy model and scoring explainer_**This notebook illustrates how to use the Azure Machine Learning Interpretability SDK to deploy a locally-trained model and its corresponding scoring explainer to Azure Container Instances (ACI) as a web service.**_Problem: IBM employee attrition classification with scikit-learn (train and explain a model locally and use Azure Container Instances (ACI) for deploying your model and its corresponding scoring explainer as a web service.)--- Table of Contents1. [Introduction](Introduction)1. [Setup](Setup)1. [Run model explainer locally at training time](Explain) 1. Apply feature transformations 1. Train a binary classification model 1. Explain the model on raw features 1. Generate global explanations 1. Generate local explanations1. [Visualize explanations](Visualize)1. [Deploy model and scoring explainer](Deploy)1. [Next steps](Next) IntroductionThis notebook showcases how to train and explain a classification model locally, and deploy the trained model and its corresponding explainer to Azure Container Instances (ACI).It demonstrates the API calls that you need to make to submit a run for training and explaining a model to AMLCompute, download the compute explanations remotely, and visualizing the global and local explanations via a visualization dashboard that provides an interactive way of discovering patterns in model predictions and downloaded explanations. It also demonstrates how to use Azure Machine Learning MLOps capabilities to deploy your model and its corresponding explainer.We will showcase one of the tabular data explainers: TabularExplainer (SHAP) and follow these steps:1. Develop a machine learning script in Python which involves the training script and the explanation script.2. Run the script locally.3. Use the interpretability toolkit’s visualization dashboard to visualize predictions and their explanation. If the metrics and explanations don't indicate a desired outcome, loop back to step 1 and iterate on your scripts.5. After a satisfactory run is found, create a scoring explainer and register the persisted model and its corresponding explainer in the model registry.6. Develop a scoring script.7. Create an image and register it in the image registry.8. Deploy the image as a web service in Azure. SetupMake sure you go through the [configuration notebook](../../../../configuration.ipynb) first if you haven't. | # 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 ImportError:
from urllib.request import urlretrieve
import zipfile
zipfilename = outdirname + '.zip'
urlretrieve('https://publictestdatasets.blob.core.windows.net/data/' + zipfilename, zipfilename)
with zipfile.ZipFile(zipfilename, 'r') as unzip:
unzip.extractall('.')
attritionData = pd.read_csv('./WA_Fn-UseC_-HR-Employee-Attrition.csv')
from sklearn.model_selection import train_test_split
import joblib
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from interpret.ext.blackbox import TabularExplainer
os.makedirs('./outputs', exist_ok=True)
# Dropping Employee count as all values are 1 and hence attrition is independent of this feature
attritionData = attritionData.drop(['EmployeeCount'], axis=1)
# Dropping Employee Number since it is merely an identifier
attritionData = attritionData.drop(['EmployeeNumber'], axis=1)
attritionData = attritionData.drop(['Over18'], axis=1)
# Since all values are 80
attritionData = attritionData.drop(['StandardHours'], axis=1)
# Converting target variables from string to numerical values
target_map = {'Yes': 1, 'No': 0}
attritionData["Attrition_numerical"] = attritionData["Attrition"].apply(lambda x: target_map[x])
target = attritionData["Attrition_numerical"]
attritionXData = attritionData.drop(['Attrition_numerical', 'Attrition'], axis=1)
# Creating dummy columns for each categorical feature
categorical = []
for col, value in attritionXData.iteritems():
if value.dtype == 'object':
categorical.append(col)
# Store the numerical columns in a list numerical
numerical = attritionXData.columns.difference(categorical)
# We create the preprocessing pipelines for both numeric and categorical data.
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())])
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
('onehot', OneHotEncoder(handle_unknown='ignore'))])
transformations = ColumnTransformer(
transformers=[
('num', numeric_transformer, numerical),
('cat', categorical_transformer, categorical)])
# Append classifier to preprocessing pipeline.
# Now we have a full prediction pipeline.
clf = Pipeline(steps=[('preprocessor', transformations),
('classifier', RandomForestClassifier())])
# Split data into train and test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(attritionXData,
target,
test_size=0.2,
random_state=0,
stratify=target)
# Preprocess the data and fit the classification model
clf.fit(x_train, y_train)
model = clf.steps[-1][1]
model_file_name = 'log_reg.pkl'
# Save model in the outputs folder so it automatically get uploaded
with open(model_file_name, 'wb') as file:
joblib.dump(value=clf, filename=os.path.join('./outputs/',
model_file_name))
# Explain predictions on your local machine
tabular_explainer = TabularExplainer(model,
initialization_examples=x_train,
features=attritionXData.columns,
classes=["Not leaving", "leaving"],
transformations=transformations)
# Explain overall model predictions (global explanation)
# Passing in test dataset for evaluation examples - note it must be a representative sample of the original data
# x_train can be passed as well, but with more examples explanations it will
# take longer although they may be more accurate
global_explanation = tabular_explainer.explain_global(x_test)
from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer, save
# ScoringExplainer
scoring_explainer = TreeScoringExplainer(tabular_explainer)
# Pickle scoring explainer locally
save(scoring_explainer, exist_ok=True)
# Register original model
run.upload_file('original_model.pkl', os.path.join('./outputs/', model_file_name))
original_model = run.register_model(model_name='local_deploy_model',
model_path='original_model.pkl')
# Register scoring explainer
run.upload_file('IBM_attrition_explainer.pkl', 'scoring_explainer.pkl')
scoring_explainer_model = run.register_model(model_name='IBM_attrition_explainer', model_path='IBM_attrition_explainer.pkl') | _____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 notebook.
# In production scenario user would choose their dependencies
import pkg_resources
available_packages = pkg_resources.working_set
sklearn_ver = None
pandas_ver = None
for dist in available_packages:
if dist.key == 'scikit-learn':
sklearn_ver = dist.version
elif dist.key == 'pandas':
pandas_ver = dist.version
sklearn_dep = 'scikit-learn'
pandas_dep = 'pandas'
if sklearn_ver:
sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)
if pandas_ver:
pandas_dep = 'pandas=={}'.format(pandas_ver)
# Specify CondaDependencies obj
# The CondaDependencies specifies the conda and pip packages that are installed in the environment
# the submitted job is run in. Note the remote environment(s) needs to be similar to the local
# environment, otherwise if a model is trained or deployed in a different environment this can
# cause errors. Please take extra care when specifying your dependencies in a production environment.
myenv = CondaDependencies.create(pip_packages=['pyyaml', sklearn_dep, pandas_dep] + azureml_pip_packages,
pin_sdk_version=False)
with open("myenv.yml","w") as f:
f.write(myenv.serialize_to_string())
with open("myenv.yml","r") as f:
print(f.read())
from azureml.core.model import Model
# Retrieve scoring explainer for deployment
scoring_explainer_model = Model(ws, 'IBM_attrition_explainer')
from azureml.core.webservice import Webservice
from azureml.core.model import InferenceConfig
from azureml.core.webservice import AciWebservice
from azureml.core.model import Model
from azureml.core.environment import Environment
aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,
memory_gb=1,
tags={"data": "IBM_Attrition",
"method" : "local_explanation"},
description='Get local explanations for IBM Employee Attrition data')
myenv = Environment.from_conda_specification(name="myenv", file_path="myenv.yml")
inference_config = InferenceConfig(entry_script="score_local_explain.py", environment=myenv)
# Use configs and models generated above
service = Model.deploy(ws, 'model-scoring-deploy-local', [scoring_explainer_model, original_model], inference_config, aciconfig)
try:
service.wait_for_deployment(show_output=True)
except WebserviceException as e:
print(e.message)
print(service.get_logs())
raise
import requests
import json
# Create data to test service with
sample_data = '{"Age":{"899":49},"BusinessTravel":{"899":"Travel_Rarely"},"DailyRate":{"899":1098},"Department":{"899":"Research & Development"},"DistanceFromHome":{"899":4},"Education":{"899":2},"EducationField":{"899":"Medical"},"EnvironmentSatisfaction":{"899":1},"Gender":{"899":"Male"},"HourlyRate":{"899":85},"JobInvolvement":{"899":2},"JobLevel":{"899":5},"JobRole":{"899":"Manager"},"JobSatisfaction":{"899":3},"MaritalStatus":{"899":"Married"},"MonthlyIncome":{"899":18711},"MonthlyRate":{"899":12124},"NumCompaniesWorked":{"899":2},"OverTime":{"899":"No"},"PercentSalaryHike":{"899":13},"PerformanceRating":{"899":3},"RelationshipSatisfaction":{"899":3},"StockOptionLevel":{"899":1},"TotalWorkingYears":{"899":23},"TrainingTimesLastYear":{"899":2},"WorkLifeBalance":{"899":4},"YearsAtCompany":{"899":1},"YearsInCurrentRole":{"899":0},"YearsSinceLastPromotion":{"899":0},"YearsWithCurrManager":{"899":0}}'
headers = {'Content-Type':'application/json'}
# Send request to service
print("POST to url", service.scoring_uri)
resp = requests.post(service.scoring_uri, sample_data, headers=headers)
# Can covert back to Python objects from json string if desired
print("prediction:", resp.text)
result = json.loads(resp.text)
# Plot the feature importance for the prediction
import numpy as np
import matplotlib.pyplot as plt; plt.rcdefaults()
labels = json.loads(sample_data)
labels = labels.keys()
objects = labels
y_pos = np.arange(len(objects))
performance = result["local_importance_values"][0][0]
plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.ylabel('Feature impact - leaving vs not leaving')
plt.title('Local feature importance for prediction')
plt.show()
service.delete() | _____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 hackathon we will pull data from those APIs to make visualizations. How to run the notebook This notebook can be executed on your own machine after installing Jupyter. Please install the Python 3 version of anaconda: https://www.anaconda.com/download/. After having that set up you can install Jupyter with:```bashconda install jupyter```For these examples we also require the [Swagger API](https://swagger.io/specification/) client `bravado`.```bashconda install -c conda-forge bravado```And the popular data analysis libraries pandas, matplotlib and seaborn:```conda install pandas matplotlib seaborn```Then clone this repo:```git clone https://github.com/mskcc/cbsp-hackathon```And run Jupyter in this folder```cd cbsp-hackathon/0-introductionjupyter```That should open Jupyter in a new browser window and you should be able to open this notebook using the web interface. You can then follow along with the next steps. How to use the notebook The notebook consists of cells which can be executed by clicking on one and pressing shift+f. In the toolbar at the top there is a dropdown which indicates what type of cell you have selected e.g. `Code` or [Markdown](https://en.wikipedia.org/wiki/Markdown). The former will be executed as raw Python code the latter is a markup language and will be run through a Markdown parser. Both generate HTML that will be printed directly to the notebook page.There a few keyboard shortcuts that are good to know. That is: `b` creates a new cell below the one you've selected and `a` above the one you selected. Editing a cell can be done with a single click for a code cell and a double click for a Markdown cell. A complete list of all keyboard shortcuts can be found by pressing the keyboard icon in the toolbar at the top. Give it a shot by editing one of the cells and pressing shift+f. Using the REST APIs All [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) we will be using in this tutorial have their REST APIs defined following the [Open API / Swagger specification](https://swagger.io/specification/). This allows us to use `bravado` to connect to them directly, and explore the API interactively.For example this is how to connect to the [cBioPortal](https://www.cbioportal.org) API: | 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': '2019-05-07 00:00:00',
'methylationHm27SampleCount': None,
'miRnaSampleCount': None,
'mrnaMicroarraySampleCount': None,
'mrnaRnaSeqSampleCount': None,
'mrnaRnaSeqV2SampleCount': None,
'name': 'MSK-IMPACT Clinical Sequencing Cohort (MSKCC, Nat Med 2017)',
'pmid': '28481359',
'publicStudy': True,
'rppaSampleCount': None,
'sequencedSampleCount': None,
'shortName': 'MSK-IMPACT',
'status': 0,
'studyId': 'msk_impact_2017'}
| 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 mentions there are 10,000 patients sequenced. Can we find this data in the cBioPortal? | 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 genes or all genes). An example for the `acc_tcga` study is given for a molecular profile (`acc_tcga_mutations`) and a collection of samples (`msk_impact_2017_all`). We can use the same approach for the `msk_impact_2017` study. This will take a few seconds. You can use the command `%%time` to time a cell): | %%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',
'linkMsa': '[Not Available]',
'linkPdb': '[Not Available]',
'linkXvar': '[Not Available]',
'molecularProfileId': 'msk_impact_2017_mutations',
'mutationStatus': 'NA',
'mutationType': 'Frame_Shift_Ins',
'ncbiBuild': 'GRCh37',
'normalAltCount': None,
'normalRefCount': None,
'patientId': 'P-0008845',
'proteinChange': 'D96Gfs*11',
'proteinPosEnd': 96,
'proteinPosStart': 96,
'referenceAllele': 'NA',
'refseqMrnaId': 'NM_001001890.2',
'sampleId': 'P-0008845-T01-IM5',
'startPosition': 36252994,
'studyId': 'msk_impact_2017',
'tumorAltCount': 98,
'tumorRefCount': 400,
'uniquePatientKey': 'UC0wMDA4ODQ1Om1za19pbXBhY3RfMjAxNw',
'uniqueSampleKey': 'UC0wMDA4ODQ1LVQwMS1JTTU6bXNrX2ltcGFjdF8yMDE3',
'validationStatus': 'NA',
'variantAllele': 'CC',
'variantType': 'INS'}
| 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 `gene` information, we'll use the `DETAILED` projection instead, so let's update the previous statement: | %%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='21q22.12', entrezGeneId=861, hugoGeneSymbol='RUNX1', length=261534, type='protein-coding'),
'keyword': 'RUNX1 truncating',
'linkMsa': '[Not Available]',
'linkPdb': '[Not Available]',
'linkXvar': '[Not Available]',
'molecularProfileId': 'msk_impact_2017_mutations',
'mutationStatus': 'NA',
'mutationType': 'Frame_Shift_Ins',
'ncbiBuild': 'GRCh37',
'normalAltCount': None,
'normalRefCount': None,
'patientId': 'P-0008845',
'proteinChange': 'D96Gfs*11',
'proteinPosEnd': 96,
'proteinPosStart': 96,
'referenceAllele': 'NA',
'refseqMrnaId': 'NM_001001890.2',
'sampleId': 'P-0008845-T01-IM5',
'startPosition': 36252994,
'studyId': 'msk_impact_2017',
'tumorAltCount': 98,
'tumorRefCount': 400,
'uniquePatientKey': 'UC0wMDA4ODQ1Om1za19pbXBhY3RfMjAxNw',
'uniqueSampleKey': 'UC0wMDA4ODQ1LVQwMS1JTTU6bXNrX2ltcGFjdF8yMDE3',
'validationStatus': 'NA',
'variantAllele': 'CC',
'variantType': 'INS'}
| 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 to do a sanity check. We see that the number of patients is indeed 10,336. But the number of samples with a mutation in TP53 is 4,561 instead of 4,985. Can you spot why they differ?Next question:- How many samples have a TP53 mutation?For this exercise it might be useful to use a [pandas dataframe](https://pandas.pydata.org/) to be able to do grouping operations. You can convert the mutations result to a dataframe like this: | 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 the mutations by the gene name and count the number of unique samples in TP53: | 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 (2017)',pad=25) | _____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 cancer related information about a particular mutation. Similarly to cBioPortal it provides a REST API following the [Swagger / OpenAPI specification](https://swagger.io/specification/). | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.