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
**Expected Output**: **gradients["dxt"][1][2]** = 3.23055911511 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = -0.0639...
def lstm_backward(da, caches): """ Implement the backward pass for the RNN with LSTM-cell (over a whole sequence). Arguments: da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x) dc -- Gradients w.r.t the memory states, numpy-array of shape (n_a, m, T_x) caches -- ca...
gradients["dx"][1][2] = [-0.00173313 0.08287442 -0.30545663 -0.43281115] gradients["dx"].shape = (3, 10, 4) gradients["da0"][2][3] = -0.095911501954 gradients["da0"].shape = (5, 10) gradients["dWf"][3][1] = -0.0698198561274 gradients["dWf"].shape = (5, 8) gradients["dWi"][1][2] = 0.102371820249 gradients["dWi"].shape ...
MIT
Course-5-Sequence-Models/week1/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb
xnone/coursera-deep-learning
Azure ML & Azure Databricks notebooks by Parashar Shah.Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. ![04ACI](files/tables/image2.JPG) Model Building
import os import pprint import numpy as np from pyspark.ml import Pipeline, PipelineModel from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler from pyspark.ml.classification import LogisticRegression from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml.tuning import C...
_____no_output_____
MIT
how-to-use-azureml/azure-databricks/03.Build_model_runHistory.ipynb
keerthiadu/MachineLearningNotebooks
Define Model
label = "income" dtypes = dict(train.dtypes) dtypes.pop(label) si_xvars = [] ohe_xvars = [] featureCols = [] for idx,key in enumerate(dtypes): if dtypes[key] == "string": featureCol = "-".join([key, "encoded"]) featureCols.append(featureCol) tmpCol = "-".join([key, "tmp"]) ...
_____no_output_____
MIT
how-to-use-azureml/azure-databricks/03.Build_model_runHistory.ipynb
keerthiadu/MachineLearningNotebooks
Model Evaluation
##unzip the model to dbfs (as load() seems to require that) and load it. if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs): shutil.rmtree(model_dbfs) shutil.unpack_archive(best_model_file_name, model_dbfs) model_p_best = PipelineModel.load(model_name) # make prediction pred = model_p_best.transform(test) ...
_____no_output_____
MIT
how-to-use-azureml/azure-databricks/03.Build_model_runHistory.ipynb
keerthiadu/MachineLearningNotebooks
Model Persistence
##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd! model_p_best.write().overwrite().save(model_name) print("saved model to {}".format(model_dbfs)) %sh ls -la /dbfs/AdultCensus_runHistory.mml/* dbutils.notebook.exit("success")
_____no_output_____
MIT
how-to-use-azureml/azure-databricks/03.Build_model_runHistory.ipynb
keerthiadu/MachineLearningNotebooks
**Installing the transformers library**
!cat /proc/meminfo !df -h !pip install transformers
Collecting transformers [?25l Downloading https://files.pythonhosted.org/packages/d8/f4/9f93f06dd2c57c7cd7aa515ffbf9fcfd8a084b92285732289f4a5696dd91/transformers-3.2.0-py3-none-any.whl (1.0MB)  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1.0MB 9.0MB/s [?25hRequirement already satisfied: regex!=2019.12.17 in /usr/loca...
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Importing the tools**
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_score import torch import transformers as ppb from sklearn.preprocessing import L...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Importing the dataset from Drive**
from google.colab import drive drive.mount('/content/gdrive') df=pd.read_csv('gdrive/My Drive/Total_cleaned.csv',delimiter=';') df1=pd.read_csv('gdrive/My Drive/Final_DUP.csv',delimiter=';') df2=pd.read_csv('gdrive/My Drive/Final_NDUP.csv',delimiter=';') df[3]
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Loading the Pre-trained BERT model**
model_class, tokenizer_class, pretrained_weights = (ppb.BertModel, ppb.BertTokenizer, 'bert-base-uncased') tokenizer = tokenizer_class.from_pretrained(pretrained_weights) model = model_class.from_pretrained(pretrained_weights) model_class, tokenizer_class, pretrained_weights = (ppb.DistilBertModel, ppb.DistilBertTokeni...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Lower case**
df[0]= df[0].str.lower() df[1]= df[1].str.lower() df[2]= df[2].str.lower() df[3]= df[3].str.lower() df[4]= df[4].str.lower() df[5]= df[5].str.lower()
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Remove Digits**
df[3] = df[3].str.replace(r'0', '') df[3] = df[3].str.replace(r'1', '') df[3] = df[3].str.replace(r'2', '') df[3] = df[3].str.replace(r'3', '') df[3] = df[3].str.replace(r'4', '') df[3] = df[3].str.replace(r'5', '') df[3] = df[3].str.replace(r'6', '') df[3] = df[3].str.replace(r'7', '') df[3] = df[3].str.replace(r'8', ...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Remove special characters**
df[3] = df[3].str.replace(r'/', '') df[3] = df[3].str.replace(r'@ ?', '') df[3] = df[3].str.replace(r'!', '') df[3] = df[3].str.replace(r'+', '') df[3] = df[3].str.replace(r'-', '') df[3] = df[3].str.replace(r'/', '') df[3] = df[3].str.replace(r':', '') df[3] = df[3].str.replace(r';', '') df[3] = df[3].str.replace(r'>'...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Convert to String type**
df[3] = pd.Series(df[3], dtype="string") # Pblm tokenize : " Input is not valid ,Should be a string, a list/tuple of strings or a list/tuple of integers" df[2] = pd.Series(df[2], dtype="string") df[2] = df[2].astype("|S") df[2].str.decode("utf-8") df[3] = df[3].astype("|S") df[3].str.decode("utf-8") df[3].str.len()
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Tokenization**
df.shape batch_31=df1[:3000] batch_32=df2[:3000] df3 = pd.concat([batch_31,batch_32], ignore_index=True) batch_41=df1[3000:6000] batch_42=df2[3000:6000] df4 = pd.concat([batch_41,batch_42], ignore_index=True) batch_51=df1[6000:9000] batch_52=df2[6000:9000] df5 = pd.concat([batch_51,batch_52], ignore_index=True) batch_6...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df3**
pair3= df3['Title1'] + [" [SEP] "] + df3['Title2'] tokenized3 = pair3.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len3 = 0 # padding all lists to the same size for i in tokenized3.values: if len(i) > max_len3: max_len3 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df4**
pair4= df4['Title1'] + [" [SEP] "] + df4['Title2'] tokenized4 = pair4.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len4 = 0 # padding all lists to the same size for i in tokenized4.values: if len(i) > max_len4: max_len4 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df5**
pair5= df5['Title1'] + [" [SEP] "] + df5['Title2'] tokenized5 = pair5.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) pair5.shape tokenized5.shape
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Padding**
max_len5 = 0 # padding all lists to the same size for i in tokenized5.values: if len(i) > max_len5: max_len5 = len(i) max_len5 =120 padded5 = np.array([i + [0]*(max_len5-len(i)) for i in tokenized5.values]) np.array(padded5).shape # Dimensions of the padded variable
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Masking**
attention_mask5 = np.where(padded5 != 0, 1, 0) attention_mask5.shape input_ids5 = torch.tensor(padded5) attention_mask5 = torch.tensor(attention_mask5) input_ids[0] ######## TITLE 2
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Running the `model()` function through BERT**
def _get_segments3(tokens, max_seq_length): """Segments: 0 for the first sequence, 1 for the second""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") segments = [] first_sep = False current_segment_id = 0 for token in tokens: segments.a...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Slicing the part of the output of BERT : [cls]**
features5 = last_hidden_states5[0][:,0,:].numpy() features5
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df6**
pair6= df6['Title1'] + [" [SEP] "] + df6['Title2'] tokenized6 = pair6.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len6 = 0 # padding all lists to the same size for i in tokenized6.values: if len(i) > max_len6: max_len6 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df7**
pair7= df7['Title1'] + [" [SEP] "] + df7['Title2'] tokenized7 = pair7.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len7 = 0 # padding all lists to the same size for i in tokenized7.values: if len(i) > max_len7: max_len7 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df8**
pair8= df8['Title1'] + [" [SEP] "] + df8['Title2'] tokenized8 = pair8.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len8 = 0 # padding all lists to the same size for i in tokenized8.values: if len(i) > max_len8: max_len8 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df9**
pair9= df9['Title1'] + [" [SEP] "] + df9['Title2'] tokenized9 = pair9.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len9 = 0 # padding all lists to the same size for i in tokenized9.values: if len(i) > max_len9: max_len9 = len(i) max_len...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**df10**
pair10= df10['Title1'] + [" [SEP] "] + df10['Title2'] tokenized10 = pair10.apply((lambda x: tokenizer.encode(x, add_special_tokens=True,truncation=True, max_length=512))) max_len10 = 0 # padding all lists to the same size for i in tokenized10.values: if len(i) > max_len10: max_len10 = len(i...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Classification**
features=np.concatenate([features3,features4,features5,features6,features7]) features=features3 features.shape Total = pd.concat([df3,df4,df5,df6,df7], ignore_index=True) Total labels =df3['Label'] labels =Total['Label'] labels train_features, test_features, train_labels, test_labels = train_test_split(features, labels...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Decision tree**
from sklearn.tree import DecisionTreeClassifier #n_splits=2 #cross_val_score=5 parameters = {'C': max_leaf_nodes=0)} grid_search = GridSearchCV(DecisionTreeClassifier(), parameters, cv=5) grid_search.fit(train_features, train_labels) print('best parameters: ', grid_search.best_params_) print('best scrores: ', grid_sear...
mean: 0.814 (std: 0.012)
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**SVM**
from sklearn.svm import SVC #n_splits=2 #cross_val_score=5 parameters = {'C': np.linspace(0.0001, 100, 20)} grid_search = GridSearchCV(SVC(), parameters, cv=5) grid_search.fit(train_features, train_labels) print('best parameters: ', grid_search.best_params_) print('best scrores: ', grid_search.best_score_) svclassifie...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
Cross_Val_SVC
from sklearn.model_selection import cross_val_score from sklearn import svm clf = svm.SVC(kernel='linear', C=36.84) scores = cross_val_score(clf, test_labels, y_pred, cv=5) scores = cross_val_score(clf, test_features, test_labels, cv=10) print("mean: {:.3f} (std: {:.3f})".format(scores.mean(), ...
mean: 0.850 (std: 0.011)
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**MLP Best params**
from sklearn.neural_network import MLPClassifier mlp = MLPClassifier(max_iter=100) from sklearn.datasets import make_classification parameter_space = { 'hidden_layer_sizes': [(50,50,50), (50,100,50), (100,)], 'activation': ['tanh', 'relu'], 'solver': ['sgd', 'adam'], 'alpha': [0.0001, 0.05], 'learni...
mean: 0.872 (std: 0.014)
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Random Forest**
from sklearn.ensemble import RandomForestRegressor regressor = RandomForestRegressor(n_estimators=20, random_state=0) regressor.fit(train_features, train_labels) y_pred1 = regressor.predict(test_features) y_pred from sklearn.metrics import classification_report, confusion_matrix, accuracy_score print(confusion_matrix...
[[616 73] [ 86 625]]
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Naive Bayes** Gaussian
from sklearn.naive_bayes import GaussianNB gnb = GaussianNB() gnb.fit(train_features, train_labels) y_pred = gnb.predict(test_features) from sklearn import metrics print("Accuracy:",metrics.accuracy_score(test_labels, y_pred))
Accuracy: 0.8358333333333333
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
*Cross Validation*
print("Cross Validation:",cross_val_score(gnb, digits.data, digits.target, scoring='accuracy', cv=10).mean())
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
Bernoulli:
from sklearn.naive_bayes import BernoulliNB bnb = BernoulliNB(binarize=0.0) bnb.fit(train_features, train_labels) print("Score: ",bnb.score(test_features, test_labels))
Score: 0.829
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
*Cross Validation*
print("Cross Validation:",cross_val_score(bnb, digits.data, digits.target, scoring='accuracy', cv=10).mean())
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
Multinomial
from sklearn.naive_bayes import MultinomialNB mnb = MultinomialNB() mnb.fit(train_features, train_labels) mnb.score(test_features, test_labels) mnb = MultinomialNB() cross_val_score(mnb, digits.data, digits.target, scoring='accuracy', cv=10).mean()
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
Best params SVC
from sklearn.svm import SVC model = SVC() model.fit(train_features, train_labels) prediction = model.predict(test_features) from sklearn.metrics import classification_report, confusion_matrix print(classification_report(test_labels,prediction)) print(confusion_matrix(test_labels, prediction)) param_grid = {'C':[1,10,10...
precision recall f1-score support 0 0.86 0.95 0.90 587 1 0.95 0.85 0.90 613 accuracy 0.90 1200 macro avg 0.91 0.90 0.90 1200 weighted avg 0.91 0.90 0.90 ...
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
**Random Forest Best params**
from sklearn.ensemble import RandomForestClassifier rfc=RandomForestClassifier(random_state=42) param_grid = { 'n_estimators': [200, 500], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [4,5,6,7,8], 'criterion' :['gini', 'entropy'] } CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid,...
_____no_output_____
MIT
Copie de test_tokens(1).ipynb
asma-miladi/DupBugRep-Scripts
Lambda School Data Science*Unit 2, Sprint 1, Module 4*--- Logistic Regression Assignment 🌯You'll use a [**dataset of 400+ burrito reviews**](https://srcole.github.io/100burritos/). How accurately can you predict whether a burrito is rated 'Great'?> We have developed a 10-dimensional system for rating the burritos in...
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Linear-Models/master/data/' !pip install category_encoders==2.* # If you're working locally: else: DATA_PATH = '../data/' # Load data downloaded from https://s...
_____no_output_____
MIT
module4-logistic-regression/Logistic_Regression_Assignment.ipynb
afroman32/DS-Unit-2-Linear-Models
**Train, Val, Test split**
df.shape # reset index because it skipped a couple of numbers df.reset_index(inplace = True, drop = True) df.head(174) # convert Great column to 1 for True and 0 for False key = {True: 1, False:0} df['Great'].replace(key, inplace = True) # convert date column to datetime df['Date'] = pd.to_datetime(df['Date']) df.head...
count 298 unique 110 top 2016-08-30 00:00:00 freq 29 first 2011-05-16 00:00:00 last 2016-12-15 00:00:00 Name: Date, dtype: object count 85 unique 42 top 2017-04-07 00:00:00 freq ...
MIT
module4-logistic-regression/Logistic_Regression_Assignment.ipynb
afroman32/DS-Unit-2-Linear-Models
**Baseline**
target = 'Great' features = ['Yelp', 'Google', 'Cost', 'Hunger', 'Tortilla', 'Temp', 'Meat', 'Fillings', 'Meat:filling', 'Uniformity', 'Salsa', 'Synergy', 'Wrap'] X_train = train[features] y_train = train[target].astype(int) X_val = val[features] y_val = val[target].astype(int) y_train.value_counts(norma...
_____no_output_____
MIT
module4-logistic-regression/Logistic_Regression_Assignment.ipynb
afroman32/DS-Unit-2-Linear-Models
**Logistic Regression Model**
import category_encoders as ce from sklearn.linear_model import LogisticRegressionCV from sklearn.preprocessing import StandardScaler target = 'Great' features = ['Yelp', 'Google', 'Cost', 'Hunger', 'Tortilla', 'Temp', 'Meat', 'Fillings', 'Meat:filling', 'Uniformity', 'Salsa', 'Synergy', 'Wrap'] X_train ...
_____no_output_____
MIT
module4-logistic-regression/Logistic_Regression_Assignment.ipynb
afroman32/DS-Unit-2-Linear-Models
Seminar: Monte-carlo tree searchIn this seminar, we'll implement a vanilla MCTS planning and use it to solve some Gym envs.But before we do that, we first need to modify gym env to allow saving and loading game states to facilitate backtracking.
from collections import namedtuple from pickle import dumps, loads from gym.core import Wrapper # a container for get_result function below. Works just like tuple, but prettier ActionResult = namedtuple( "action_result", ("snapshot", "observation", "reward", "is_done", "info")) class WithSnapshots(Wrapper): ...
_____no_output_____
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
try out snapshots:
# make env env = WithSnapshots(gym.make("CartPole-v0")) env.reset() n_actions = env.action_space.n print("initial_state:") plt.imshow(env.render('rgb_array')) env.close() # create first snapshot snap0 = env.get_snapshot() # play without making snapshots (faster) while True: is_done = env.step(env.action_space.sam...
_____no_output_____
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
MCTS: Monte-Carlo tree searchIn this section, we'll implement the vanilla MCTS algorithm with UCB1-based node selection.We will start by implementing the `Node` class - a simple class that acts like MCTS node and supports some of the MCTS algorithm steps.This MCTS implementation makes some assumptions about the enviro...
assert isinstance(env,WithSnapshots) class Node: """ a tree node for MCTS """ #metadata: parent = None #parent Node value_sum = 0. #sum of state values from all visits (numerator) times_visited = 0 #counter of visits (denominator) def __init__(self,parent,action)...
_____no_output_____
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
Main MCTS loopWith all we implemented, MCTS boils down to a trivial piece of code.
def plan_mcts(root,n_iters=10): """ builds tree with monte-carlo tree search for n_iters iterations :param root: tree node to plan from :param n_iters: how many select-expand-simulate-propagete loops to make """ for _ in range(n_iters): # PUT CODE HERE node = root.selec...
_____no_output_____
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
Plan and executeIn this section, we use the MCTS implementation to find optimal policy.
env = WithSnapshots(gym.make("CartPole-v0")) root_observation = env.reset() root_snapshot = env.get_snapshot() root = Root(root_snapshot, root_observation) #plan from root: plan_mcts(root,n_iters=1000) from IPython.display import clear_output from itertools import count from gym.wrappers import Monitor total_reward = ...
_____no_output_____
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
Submit to Coursera
from submit import submit_mcts submit_mcts(total_reward, "x@gmail.com", "xx")
Submitted to Coursera platform. See results on assignment page!
MIT
week6/practice_mcts.ipynb
Iramuk-ganh/practical-rl
$$\newcommand\bs[1]{\boldsymbol{1}}$$ IntroductionThis chapter is light but contains some important definitions. The identity matrix and the inverse of a matrix are concepts that will be very useful in subsequent chapters. Using these concepts, we will see how vectors and matrices can be transformed. To fully understa...
np.eye(3) # 3 rows, and 3 columns
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
When you "apply" the identity matrix to a vector using the dot product, the result is the same vector:$$\bs{I}_n\bs{x} = \bs{x}$$ Example 1$$\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1\end{bmatrix}\times\begin{bmatrix} x_{1} \\\\ x_{2} \\\\ x_{3}\end{bmatrix}=\begin{bmatrix} 1 \times x_...
x = np.array([[2], [6], [3]]) x x_id = np.eye(x.shape[0]).dot(x) x_id
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
More generally, when $\bs{A}$ is an $m\times n$ matrix, it is a property of matrix multiplication that:$$I_m\bs{A} = \bs{A}I_n = \bs{A}$$ Visualizing the intuitionVectors and matrices occupy $n$-dimensional space. This precept allows us to think about linear algebra geometrically and, if we're lucky enough to be worki...
A = np.array([[3, 0, 2], [2, 0, -2], [0, 1, 1]]) A
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
Now we calculate its inverse:
A_inv = np.linalg.inv(A) A_inv
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
We can check that $\bs{A^{-1}}$ is the inverse of $\bs{A}$ with Python:
A_bis = A_inv.dot(A) A_bis
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
Sovling a system of linear equationsThe inverse matrix can be used to solve the equation $\bs{Ax}=\bs{b}$ by adding it to each term:$$\bs{A}^{-1}\bs{Ax}=\bs{A}^{-1}\bs{b}$$Since we know by definition that $\bs{A}^{-1}\bs{A}=\bs{I}$, we have:$$\bs{I}_n\bs{x}=\bs{A}^{-1}\bs{b}$$We saw that a vector is not changed when m...
A = np.array([[2, -1], [1, 1]]) A
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
And let's define $\bs{b}$:
b = np.array([[0], [3]])
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
And now let's find the inverse of $\bs{A}$:
A_inv = np.linalg.inv(A) A_inv
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
Since we saw that$$\bs{x}=\bs{A}^{-1}\bs{b}$$We have:
x = A_inv.dot(b) x
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
This is our solution! $$\bs{x}=\begin{bmatrix} 1 \\\\ 2\end{bmatrix}$$Going back to the geometric interpretion of linear algebra, you can think of our solution vector $\bs{x}$ as containing a set of coordinates ($1, 2$). This point in a $2$-dimensional Cartesian plane is actually the intersection of the two lines...
#to draw the equation with Matplotlib, first create a vector with some x values x = np.arange(-10, 10) #then create some y values for each of those x values using the equation y = 2*x y1 = -x + 3 #then instantiate the plot figure plt.figure() #draw the first line plt.plot(x, y) #draw the second line plt.plot(x, y1) #s...
_____no_output_____
Unlicense
Learn Math/3. Linear Algebra/3.3 Identity and Inverse Matrices/3.3 Identity and Inverse Matrices.ipynb
mcallistercs/learning-data-science
ESML - accelerator: Quick DEMO
import sys, os sys.path.append(os.path.abspath("../azure-enterprise-scale-ml/esml/common/")) # NOQA: E402 from esml import ESMLDataset, ESMLProject p = ESMLProject() # Will search in ROOT for your copied SETTINGS folder '../../../settings', you should copy template settings from '../settings' #p = ESMLProject(True) # ...
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
from azureml.core import Workspacefrom azureml.core.authentication import InteractiveLoginAuthenticationauth = InteractiveLoginAuthentication(tenant_id = p.tenant)ws = Workspace.get(name = p.workspace_name,subscription_id = p.subscription_id,resource_group = p.resource_group,auth=auth)ws.write_config(path=".", file_nam...
from azureml.core import Workspace ws, config_name = p.authenticate_workspace_and_write_config() ws = p.get_workspace_from_config() ws.name print("Are we in R&D state (no dataset versioning) = {}".format(p.rnd)) p.unregister_all_datasets(ws) # DEMO purpose datastore = p.init(ws)
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3) IN->`BRONZE->SILVER`->Gold- Create dataset from PANDAS - Save to SILVER
import pandas as pd ds = p.DatasetByName("ds01_diabetes") df = ds.Bronze.to_pandas_dataframe() df.head()
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3) BRONZE-SILVER (EDIT rows & SAVE)- Test change rows, same structure = new version (and new file added)- Note: not earlier files in folder are removed. They are needed for other "versions". - Expected: For 3 files: New version, 997 rows: 2 older files=627 + 1 new file=370- Expected (if we delete OLD files): New versi...
df_filtered = df[df.AGE > 0.015] print(df.shape[0], df_filtered.shape[0])
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3a) Save `SILVER` ds01_diabetes
aml_silver = p.save_silver(p.DatasetByName("ds01_diabetes"),df_filtered) aml_silver.name
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
COMPARE `BRONZE vs SILVER`- Compare and validate the feature engineering
ds01 = p.DatasetByName("ds01_diabetes") bronze_rows = ds01.Bronze.to_pandas_dataframe().shape[0] silver_rows = ds01.Silver.to_pandas_dataframe().shape[0] print("Bronze: {}".format(bronze_rows)) # Expected 442 rows print("Silver: {}".format(silver_rows)) # Expected 185 rows (filtered) assert bronze_rows == 442,"BRONZE...
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3b) Save `BRONZE β†’ SILVER` ds02_other
df_edited = p.DatasetByName("ds02_other").Silver.to_pandas_dataframe() ds02_silver = p.save_silver(p.DatasetByName("ds02_other"),df_edited) ds02_silver.name
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3c) Merge all `SILVERS -> then save GOLD`
df_01 = ds01.Silver.to_pandas_dataframe() df_02 = ds02_silver.to_pandas_dataframe() df_gold1_join = df_01.join(df_02) # left join -> NULL on df_02 print("Diabetes shape: ", df_01.shape) print(df_gold1_join.shape)
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
Save `GOLD` v1
print(p.rnd) p.rnd=False # Allow versioning on DATASETS, to have lineage ds_gold_v1 = p.save_gold(df_gold1_join)
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
3c) Ops! "faulty" GOLD - too many features
print(p.Gold.to_pandas_dataframe().shape) # 19 features...I want 11 print("Are we in RnD phase? Or do we have 'versioning on datasets=ON'") print("RnD phase = {}".format(p.rnd))
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
Save `GOLD` v2
# Lets just go with features from ds01 ds_gold_v1 = p.save_gold(df_01)
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
Get `GOLD` by version
gold_1 = p.get_gold_version(1) gold_1.to_pandas_dataframe().shape # (185, 19) gold_2 = p.get_gold_version(2) gold_2.to_pandas_dataframe().shape # (185, 11) p.Gold.to_pandas_dataframe().shape # Latest version (185, 11) df_01_filtered = df_01[df_01.AGE > 0.03807] ds_gold_v1 = p.save_gold(df_01_filtered) gold_2 = p.get_go...
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
TRAIN - `AutoMLFactory + ComputeFactory`
from baselayer_azure_ml import AutoMLFactory, ComputeFactory p.dev_test_prod = "test" print("what environment are we targeting? = {}".format(p.dev_test_prod)) automl_performance_config = p.get_automl_performance_config() automl_performance_config p.dev_test_prod = "dev" automl_performance_config = p.get_automl_perfor...
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
Get `COMPUTE` for current `ENVIRONMENT`
aml_compute = p.get_training_aml_compute(ws)
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
`TRAIN` model -> See other notebook `esml_howto_2_train.ipynb`
from azureml.train.automl import AutoMLConfig from baselayer_azure_ml import azure_metric_regression label = "Y" train_6, validate_set_2, test_set_2 = p.split_gold_3(0.6,label) # Auto-registerin AZURE (M03_GOLD_TRAIN | M03_GOLD_VALIDATE | M03_GOLD_TEST) # Alt: train,testv= p.Gold.random_split(percentage=0.8, seed=23) ...
_____no_output_____
MIT
notebook_demos/esml_howto_0_short.ipynb
jostrm/azure-enterprise-scale-ml-usage
Pymaceuticals Inc.--- Analysis* Capomulin and Ramicane showed the smallest tumor volume at the end of the study.* There appears to be a correlation between mouse weight and the average tumor volume; as weight increases, tumor volume increases.* Capomulin had the lowest IQR, indicating a more narrow spread in the resul...
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import scipy.stats as st # Study data files mouse_metadata_path = "data/Mouse_metadata.csv" study_results_path = "data/Study_results.csv" # Read the mouse data and the study results mouse_metadata = pd.read_csv(mouse_metadata_path) study_resu...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
Summary Statistics
# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen mean_df = clinical_trial.groupby('Drug Regimen').mean().reset_index() mean_df = mean_df[['Drug Regimen', 'Tumor Volume (mm3)']] mean_df = mean_df.rename(columns={'Tumor Volume (mm3)':'Mean T...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
Bar and Pie Charts
# Generate a bar plot showing number of data points for each treatment regimen using pandas drug_summary.sort_values('Count', ascending=False).plot.bar(x="Drug Regimen", y="Count") # Generate a bar plot showing number of data points for each treatment regimen using pyplot plt.bar(drug_summary['Drug Regimen'], drug_summ...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
Quartiles, Outliers and Boxplots
# Calculate the final tumor volume of each mouse. tumor_df = clinical_trial.groupby('Mouse ID').last() tumor_df.head() # Calculate the final tumor volume of each mouse in Capomulin treatment regime. capomulin = tumor_df.loc[(tumor_df['Drug Regimen'] == "Capomulin"),:] capomulin.head() # Calculate the IQR and quantita...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
Line and Scatter Plots
# Generate a line plot of time point versus tumor volume for a mouse treated with Capomulin clinical_trial.head() single_mouse = clinical_trial[['Mouse ID', 'Timepoint', 'Tumor Volume (mm3)', 'Drug Regimen']] single_mouse = single_mouse.loc[(single_mouse['Drug Regimen'] == "Capomulin"),:].reset_index() single_mouse = s...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
Correlation and Regression
# Calculate the correlation coefficient and linear regression model # for mouse weight and average tumor volume for the Capomulin regimen vc_slope, vc_int, vc_r, vc_p, vc_std_err = st.linregress(weight, tumor) vc_fit = vc_slope * weight + vc_int plt.plot(weight,vc_fit) weight = capomulin_test_group['Weight (g)'] tumor...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_basco.ipynb
bascomary/matplotlib_challenge
In this notebook we'll provide an example for using different openrouteservice API's to help you look for an apartment.
mkdir ors-apartment conda create -n ors-apartment python=3.6 shapely cd ors-apartment pip install openrouteservice ortools folium import folium from openrouteservice import client
_____no_output_____
Apache-2.0
python/Apartment_Search.ipynb
Xenovortex/ors-example
We have just moved to San Francisco with our kids and are looking for the perfect location to get a new home. Our geo intuition tells us we have to look at the data to come to this important decision. So we decide to geek it up a bit. Apartment isochrones There are three different suggested locations for our new home....
api_key = '' #Provide your personal API key clnt = client.Client(key=api_key) # Set up folium map map1 = folium.Map(tiles='Stamen Toner', location=([37.738684, -122.450523]), zoom_start=12) # Set up the apartment dictionary with real coordinates apt_dict = {'first': {'location': [-122.430954, 37.792965]}, ...
_____no_output_____
Apache-2.0
python/Apartment_Search.ipynb
Xenovortex/ors-example
POIs around apartments For the ever-styled foodie parents we are, we need to have the 3 basic things covered: kindergarten, supermarket and hair dresser. Let's see what options we got around our apartments:
# Common request parameters params_poi = {'request': 'pois', 'sortby': 'distance'} # POI categories according to # https://github.com/GIScience/openrouteservice-docs#places-response categories_poi = {'kindergarten': [153], 'supermarket': [518], 'hairdresser': [395]} ...
first apartment kindergarten: 1 supermarket: 8 hairdresser: 10 second apartment kindergarten: 3 supermarket: 1 hairdresser: 4 third apartment kindergarten: 1 supermarket: 3 hairdresser: 2
Apache-2.0
python/Apartment_Search.ipynb
Xenovortex/ors-example
So, all apartments meet all requirements. Seems like we have to drill down further. Routing from apartments to POIs To decide on a place, we would like to know from which apartment we can reach all required POI categories the quickest. So, first we look at the distances from each apartment to the respective POIs.
# Set up common request parameters params_route = {'profile': 'foot-walking', 'format_out': 'geojson', 'geometry': 'true', 'geometry_format': 'geojson', 'instructions': 'false', } # Set up dict for font-awesome style_dict = {'kindergarten': 'ch...
_____no_output_____
Apache-2.0
python/Apartment_Search.ipynb
Xenovortex/ors-example
Quickest route to all POIs Now, we only need to determine which apartment is closest to all POI categories.
# Sum up the closest POIs to each apartment for name, apt in apt_dict.items(): apt['shortest_sum'] = sum([min(cat['durations']) for cat in apt['categories'].values()]) print("{} apartments: {} mins".format(name, apt['shortest_sum']/60 ...
first apartments: 37.09 mins second apartments: 40.325 mins third apartments: 35.315000000000005 mins
Apache-2.0
python/Apartment_Search.ipynb
Xenovortex/ors-example
Making El Nino AnimationsEl Nino is the warm phase of __[El NiΓ±o–Southern Oscillation (ENSO)](https://en.wikipedia.org/wiki/El_Ni%C3%B1o%E2%80%93Southern_Oscillation)__. It is a part of a routine climate pattern that occurs when sea surface temperatures in the tropical Pacific Ocean rise to above-normal levels for an ...
import os from dh_py_access import package_api import dh_py_access.lib.datahub as datahub import xarray as xr from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np import imageio import shutil import datetime import matplotlib as mpl mpl.rcParams['font.family'] = 'Avenir Lt Std' mp...
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Please put your datahub API key into a file called APIKEY and place it to the notebook folder or assign your API key directly to the variable API_key!
API_key = open('APIKEY').read().strip() server='api.planetos.com/' version = 'v1'
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
This is a part where you should change the time period if you want to get animation of different time frame. Strongest __[El Nino years](http://ggweather.com/enso/oni.htm)__ have been 1982-83, 1997-98 and 2015-16. However, El Nino have occured more frequently. NOAA OISST dataset in Planet OS Datahub starts from 2008, ...
time_start = '2016-01-01T00:00:00' time_end = '2016-03-10T00:00:00' dataset_key = 'noaa_oisst_daily_1_4' variable = 'anom' area = 'pacific' latitude_north = 40; latitude_south = -40 longitude_west = -180; longitude_east = -77 anim_name = variable + '_animation_' + str(datetime.datetime.strptime(time_start,'%Y-%m-%dT%H...
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Download the data with package API- Create package objects- Send commands for the package creation- Download the package files
dh=datahub.datahub(server,version,API_key) package = package_api.package_api(dh,dataset_key,variable,longitude_west,longitude_east,latitude_south,latitude_north,time_start,time_end,area_name=area) package.make_package() package.download_package()
Package exists
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Here we are using xarray to read in the data. We will also rewrite longitude coordinates as they are from 0-360 at first, but Basemap requires longitude -180 to 180.
dd1 = xr.open_dataset(package.local_file_name) dd1['lon'] = ((dd1.lon+180) % 360) - 180
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
We like to use Basemap to plot data on it. Here we define the area. You can find more information and documentation about Basemap __[here](https://matplotlib.org/basemap/)__.
m = Basemap(projection='merc', lat_0 = 0, lon_0 = (longitude_east + longitude_west)/2, resolution = 'l', area_thresh = 0.05, llcrnrlon=longitude_west, llcrnrlat=latitude_south, urcrnrlon=longitude_east, urcrnrlat=latitude_north) lons,lats = np.meshgrid(dd1.lon,dd1.lat) lonmap,latmap = m(lon...
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Below we make local folder where we save images. These are the images we will use for animation. No worries, in the end, we will delete the folder from your system.
folder = './ani/' if not os.path.exists(folder): os.mkdir(folder)
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Now it is time to make images from every time step. Let's also show first time step here:
vmin = -5; vmax = 5 for k in range(0,len(dd1[variable])): filename = folder + 'ani_' + str(k).rjust(3,'0') + '.png' fig=plt.figure(figsize=(12,10)) ax = fig.add_subplot(111) pcm = m.pcolormesh(lonmap,latmap,dd1[variable][k,0].data,vmin = vmin, vmax = vmax,cmap='bwr') m.fillcontinents(color='#58...
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
This is part where we are making animation.
files = sorted(os.listdir(folder)) fileList = [] for file in files: if not file.startswith('.'): complete_path = folder + file fileList.append(complete_path) writer = imageio.get_writer(anim_name, fps=4) for im in fileList: writer.append_data(imageio.imread(im)) writer.close() print ('Animatio...
Animation is saved as anom_animation_2016.mp4 under current working directory
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
And finally, we will delete folder where images where saved. Now you just have animation in your working directory.
shutil.rmtree(folder)
_____no_output_____
MIT
api-examples/El_Nino_animations.ipynb
steffenmodest/notebooks
Task 2: Prediction using Unsupervised ML - K- Means Clustering Importing the libraries
import numpy as np import matplotlib.pyplot as plt import pandas as pd
_____no_output_____
Apache-2.0
Task_2_Clustering.ipynb
BakkeshAS/GRIP_Task_2_Predict_Optimum_Clusters
Importing the dataset
dataset = pd.read_csv('/content/Iris.csv') dataset.head() dataset['Species'].describe()
_____no_output_____
Apache-2.0
Task_2_Clustering.ipynb
BakkeshAS/GRIP_Task_2_Predict_Optimum_Clusters
Determining K - number of clusters
x = dataset.iloc[:, [0, 1, 2, 3]].values from sklearn.cluster import KMeans wcss = [] for i in range(1, 15): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_)
_____no_output_____
Apache-2.0
Task_2_Clustering.ipynb
BakkeshAS/GRIP_Task_2_Predict_Optimum_Clusters
Plotting the results - observe 'The elbow'
plt.figure(figsize=(16,8)) plt.style.use('ggplot') plt.plot(range(1, 15), wcss) plt.title('The elbow method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') # Within cluster sum of squares plt.show()
_____no_output_____
Apache-2.0
Task_2_Clustering.ipynb
BakkeshAS/GRIP_Task_2_Predict_Optimum_Clusters
Creating the kmeans classifier with K = 3
kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) y_kmeans = kmeans.fit_predict(x)
_____no_output_____
Apache-2.0
Task_2_Clustering.ipynb
BakkeshAS/GRIP_Task_2_Predict_Optimum_Clusters