code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from scipy import * import FNC # # Example 1.1.2 # Recall the grade-school approximation to the number $\pi$. p = 22/7 print(p) # Note that not all the digits displayed for `p` are the same as for $\pi$. As an approximation, its absolute and relative accuracy are print("absolute accuracy: ",abs(p-pi)) print("relative accuracy: ",abs(p-pi)/pi) print("accurate digits: ",-log10(abs(p-pi)/pi)) # # Example 1.1.3 # There is no double precision number between $1$ and $1+\varepsilon_\text{mach}$. Thus the following difference is zero despite its appearance. eps = finfo(float).eps e = eps/2 (1.0 + e) - 1.0 # However, $1-\varepsilon_\text{mach}/2$ is a double precision number, so it and its negative are represented exactly: 1.0 + (e - 1.0) # This is now the "correct" result. But we have found a rather shocking breakdown of the associative law of addition! # # Example 1.3.2 # Here we show how to use `horner` to evaluate a polynomial. We first define a vector of the coefficients of $p(x)=(x−1)^3=x^3−3x^2+3x−1$, in descending degree order. Note that the textbook's functions are all in a namespace called `FNC`, to help distinguish them from other Python commands and modules. # c = array([1,-3,3,-1]) print( FNC.horner(c,1.6) ) # The above is the value of $p(1.6)$, up to a rounding error. # # Example 1.3.3 # Our first step is to construct a polynomial with six known roots. r = [-2.0,-1,1,1,3,6] p = poly(r) print(p) # Now we use a standard numerical method for finding those roots, pretending that we don't know them already. r_computed = sort(poly1d(p).roots) print(r_computed) # Here are the relative errors in each of the computed roots. print(abs(r - r_computed) / r) # It seems that the forward error is acceptably close to machine epsilon for double precision in all cases except the double root at $x=1$. This is not a surprise, though, given the poor conditioning at such roots. # # Let's consider the backward error. The data in the rootfinding problem are the polynomial coefficients. We can apply poly to find the coefficients of the polynomial (that is, the data) whose roots were actually computed by the numerical algorithm. p_computed = poly(r_computed) print(p_computed) # We find that in a relative sense, these coefficients are very close to those of the original, exact polynomial: print(abs(p-p_computed)/p) # In summary, even though there are some computed roots relatively far from their correct values, they are nevertheless the roots of a polynomial that is very close to the original. # # Example 1.3.4 a = 1.0 b = -(1e6+1e-6) c = 1.0 x1 = (-b + sqrt(b*b-4*a*c)) / (2*a) print(x1) # So far, so good. But: x2 = (-b - sqrt(b*b-4*a*c)) / (2*a) print(x2) # The first value is correct to all stored digits, but the second has fewer than six accurate digits: print( -log10(abs(1e-6-x2)/1e-6 ) ) # # Example 1.3.5 a = 1.0 b = -(1e6+1e-6) c = 1.0 # First, we find the "good" root using the quadratic forumla. x1 = (-b + sqrt(b*b-4*a*c)) / (2*a) print(x1) # Then we use the alternative formula for computing the other root. x2 = c/(a*x1) print(x2 - 1e-6)
python/Chapter01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: html # language: python # name: html # --- # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer from sklearn.metrics import accuracy_score, roc_auc_score from sklearn.model_selection import cross_val_score, train_test_split from sklearn.ensemble import RandomForestClassifier # + # load dataset breast_cancer_X, breast_cancer_y = load_breast_cancer(return_X_y=True) X = pd.DataFrame(breast_cancer_X) y = pd.Series(breast_cancer_y).map({0:1, 1:0}) # + # split dataset into a train and test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0) # + import optuna def objective(trial): rf_n_estimators = trial.suggest_int("rf_n_estimators", 100, 1000) rf_max_depth = trial.suggest_int("rf_max_depth", 1, 4) model = RandomForestClassifier( max_depth=rf_max_depth, n_estimators=rf_n_estimators ) score = cross_val_score(model, X_train, y_train, cv=3) accuracy = score.mean() return accuracy study = optuna.create_study(direction="maximize") study.optimize(objective, n_trials=10) # - study.best_params
_for_slides/04-Optuna-main-functions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- pwd import pandas as pd df=pd.read_csv('/home/sf/fresh_start/3_class_combination_10-5.csv') df # + test_subject=[int(i) for i in list(df[df['acc']==df['acc'].max()]['subjects_in_test'])[0][1:-1].split(',')] train_subject=[int(i) for i in list(df[df['acc']==df['acc'].max()]['subjects_in_train'])[0][1:-1].split(',')] test_subject # - import numpy as np from sklearn.ensemble import ExtraTreesClassifier from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from imblearn.over_sampling import SMOTE from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import Normalizer from itertools import combinations from sklearn import model_selection import copy from statistics import mean,mode from itertools import combinations from sklearn.ensemble import GradientBoostingClassifier df=pd.read_csv('/home/sf/fresh_start/60s_window_wrist_chest.csv',index_col=0) df=df[df['label']<3] # + features=df.columns.tolist() features removed = ['label'] for rem in removed: features.remove(rem) features_with_sub=[] features_with_sub[:]=features removed = ['subject'] for rem in removed: features.remove(rem) feature=features print(len(feature)) len(features_with_sub) sm = SMOTE(random_state=2) X, y= sm.fit_sample(df[features_with_sub], df['label']) df_new=pd.concat([pd.DataFrame(X,columns=features_with_sub),pd.DataFrame(y,columns=['label'])],axis=1) df_new for i in range (len(list(df_new['subject']))): df_new['subject'][i] = min([2,3,4,5,6,7,8,9,10,11,13,14,15,16,17], key=lambda x:abs(x-df_new['subject'][i])) df_new['subject']=df_new['subject'].astype(int) p_d=pd.read_csv('/home/sf/fresh_start/personal_detail.csv',index_col=0) df_new_1=df_new.merge(p_d,on='subject') df_new_1 # - sel_fea=['EDA_tonic_mean', 'EDA_tonic_max', 'EDA_tonic_min', 'EDA_phasic_mean', 'EDA_smna_mean', 'EDA_phasic_min', 'EMG_std', 'c_ACC_y_min', 'sport_today_YES', 'ECG_std', 'c_ACC_x_std', 'c_ACC_y_std'] # + # subjects_in_train = [] # subjects_in_test = [] # best_acc = [] # mean_acc = [] # min_acc = [] # acc = [] # for cp in range (1,len(train_subject)): # print ('*'*20) # print ("10C"+str(cp)) # print ('*'*20) # com = cp # combination number, If any doubt plz call me # combi = combinations(train_subject, com) # tot = str(len(list(copy.deepcopy(combi)))) # list_combi = list(combi) # for lc in list_combi: # print (list(lc)) # train= df_new_1.loc[df_new_1.subject.isin(list(lc))] # test= df_new_1.loc[df_new_1.subject.isin(test_subject)] # print ("TRAIN",lc) # print ("TEST",test_subject ) # scaler = Normalizer() # scaled_data_train = scaler.fit_transform(train[sel_fea]) # scaled_data_test = scaler.transform(test[sel_fea]) # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # acc.append(rpt) # subjects_in_train.append(str(list(lc))) # subjects_in_test.append(str(test_subject)) # combi_dict = {'subjects_in_train':subjects_in_train,'subjects_in_test':subjects_in_test, 'acc':acc} # df_plot_combi = pd.DataFrame(combi_dict) # - for cp in range (1,len(train_subject)): print ('*'*20) print ("10C"+str(cp)) print ('*'*20) com = cp # combination number, If any doubt plz call me combi = combinations(train_subject, com) tot = str(len(list(copy.deepcopy(combi)))) list_combi = list(combi) subjects_in_train = [] subjects_in_test = [] best_acc = [] mean_acc = [] min_acc = [] acc = [] for lc in list_combi: print (list(lc)) train= df_new_1.loc[df_new_1.subject.isin(list(lc))] test= df_new_1.loc[df_new_1.subject.isin(test_subject)] scaler = Normalizer() scaled_data_train = scaler.fit_transform(train[sel_fea]) scaled_data_test = scaler.transform(test[sel_fea]) clf = GradientBoostingClassifier() clf.fit(scaled_data_train,train['label']) y_pred=clf.predict(scaled_data_test) rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] acc.append(rpt) subjects_in_train.append(str(list(lc))) subjects_in_test.append(str(test_subject)) combi_dict = {'subjects_in_train':subjects_in_train,'subjects_in_test':subjects_in_test, 'acc':acc} df_plot_combi = pd.DataFrame(combi_dict) file_name = '3_class_combination_'+str(cp)+'-'+str(5)+'.csv' print (file_name) df_plot_combi.to_csv(file_name) df_plot_combi df_plot_combi.to_csv("as_you_asked_ram.csv") # + # # %%time # for cp in range (1,len(user_list)): # print ('*'*20) # print ("15C"+str(cp)) # print ('*'*20) # com = cp # combination number, If any doubt plz call me # combi = combinations(user_list, com) # tot = str(len(list(copy.deepcopy(combi)))) # # getting the best random state # best_random_state_train = user_list[0:com] # best_random_state_test = user_list[com:] # # print (best_random_state_train) # # print (best_random_state_test) # train= df_new_1.loc[df_new_1.subject.isin(best_random_state_train)] # test= df_new_1.loc[df_new_1.subject.isin(best_random_state_test)] # scaler = Normalizer() # scaled_data_train = scaler.fit_transform(train[sel_fea]) # scaled_data_test = scaler.transform(test[sel_fea]) # rnd_loc_acc = [] # for i in range (101): # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=i) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # rnd_loc_acc.append(rpt) # rnd_index = rnd_loc_acc.index(max(rnd_loc_acc)) # index = 1 # subjects_in_train = [] # subjects_in_test = [] # best_acc = [] # mean_acc = [] # min_acc = [] # acc = [] # for c in list(combi): # local_acc = [] # # print (str(index)+" of "+ tot) # train_sub = list(c) # test_sub = list(set(user_list)-set(train_sub)) # print (train_sub,test_sub) # train= df_new_1.loc[df_new_1.subject.isin(train_sub)] # test= df_new_1.loc[df_new_1.subject.isin(test_sub)] # scaler = Normalizer() # scaled_data_train = scaler.fit_transform(train[sel_fea]) # scaled_data_test = scaler.transform(test[sel_fea]) # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=rnd_index) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # acc.append(rpt) # subjects_in_train.append(str(train_sub)) # subjects_in_test.append(str(test_sub)) # # for i in range (51): # # print (i) # # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=i) # # clf.fit(scaled_data_train,train['label']) # # y_pred=clf.predict(scaled_data_test) # # # print (classification_report(test['label'],y_pred)) # # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # # local_acc.append(rpt) # # best_acc.append(max(local_acc)) # # mean_acc.append(mean(local_acc)) # # min_acc.append(min(local_acc)) # # subjects_in_train.append(str(train_sub)) # # subjects_in_test.append(str(test_sub)) # # print ("*"*10) # # print (acc) # # print ("*"*10) # index += 1 # combi_dict = {'subjects_in_train':subjects_in_train,'subjects_in_test':subjects_in_test, 'acc':acc} # df_plot_combi = pd.DataFrame(combi_dict) # temp = df_plot_combi[df_plot_combi['acc']>=max(df_plot_combi['acc'])] # subjects_in_train = eval(temp['subjects_in_train'].values[0]) # subjects_in_test = eval(temp['subjects_in_test'].values[0]) # train= df_new_1.loc[df_new_1.subject.isin(subjects_in_train)] # test= df_new_1.loc[df_new_1.subject.isin(subjects_in_test)] # scaler = Normalizer() # scaled_data_train = scaler.fit_transform(train[sel_fea]) # scaled_data_test = scaler.transform(test[sel_fea]) # print("****** Testing on Model ********") # #extra tree # print ("Extra tree") # loc_acc = [] # for i in range (101): # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=i) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # loc_acc.append(rpt) # index = loc_acc.index(max(loc_acc)) # clf = ExtraTreesClassifier(n_estimators=100,n_jobs=10,random_state=index) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # print (classification_report(test['label'],y_pred)) # df_plot_combi.at[df_plot_combi[df_plot_combi['acc'] == max(df_plot_combi['acc'])].index[0],'acc'] = rpt # #random forest # print ("Random Forest") # loc_acc = [] # for i in range (101): # clf=RandomForestClassifier(n_estimators=50,random_state=i) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # loc_acc.append(rpt) # index = loc_acc.index(max(loc_acc)) # clf=RandomForestClassifier(n_estimators=50,random_state=index) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # print (classification_report(test['label'],y_pred)) # #Decision-Tree # print ("Decision Tree") # loc_acc = [] # for i in range (101): # clf= DecisionTreeClassifier(random_state=i) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # loc_acc.append(rpt) # index = loc_acc.index(max(loc_acc)) # clf= DecisionTreeClassifier(random_state=index) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # print (classification_report(test['label'],y_pred)) # #GradientBoosting # print ("Gradient Boosting") # loc_acc = [] # for i in range (101): # clf= GradientBoostingClassifier(random_state=i) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # #print (classification_report(test['label'],y_pred)) # rpt = classification_report(test['label'],y_pred,output_dict=True)['accuracy'] # loc_acc.append(rpt) # index = loc_acc.index(max(loc_acc)) # clf= GradientBoostingClassifier(random_state=index) # clf.fit(scaled_data_train,train['label']) # y_pred=clf.predict(scaled_data_test) # print (classification_report(test['label'],y_pred)) # print("****** Writing to File ********") # # Plz cross check with the file name before saving to df to csv file # file_name = '3_class_combination_'+str(com)+'-'+str(15-com)+'.csv' # print (file_name) # df_plot_combi.to_csv(file_name) # temp = df_plot_combi[df_plot_combi['acc']>=max(df_plot_combi['acc'])] # print("Max:",max(df_plot_combi['acc'])) # print("Min:",min(df_plot_combi['acc'])) # print("Mean:",mean(df_plot_combi['acc'])) # - list_combi
User Independence Analysis/others/10-5-gradientboosting/.ipynb_checkpoints/Untitled-Copy1-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Notebook contains all code to generate embedding models for mental health related twitter data. The genisim package # is used along with Word2Vec and FastText to set up the embeddings. Dataset is cleaned according to each models # specification. The notebook leverages functions in the preprocessing and utility script which can be found in the scripts folder. For more details on each model please refer to details in the corresponding papers Appendix. # # + colab={} colab_type="code" id="4W8QpMU1GjYb" import sys sys.path.insert(0, 'scripts/') # - import utility import preprocessing as pp # + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" id="ft2J4XUYKf_s" outputId="1c05aa2a-7ae0-4b5f-9635-656acf598857" import pandas as pd import numpy as np import string import re from emoji import UNICODE_EMOJI import multiprocessing from multiprocessing import cpu_count # - import gensim as g from gensim.models.word2vec import Word2Vec from gensim.scripts.glove2word2vec import glove2word2vec from gensim.models.keyedvectors import KeyedVectors from gensim.models import FastText import gensim.downloader as api import nltk from nltk import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.decomposition import PCA # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="ZjtVy7liKf_w" outputId="98f50169-67fc-428a-b98b-e06f656082df" nltk.download('stopwords') stopwords = nltk.corpus.stopwords.words('english') nltk.download('wordnet') nltk.download('punkt') lemmatizer = WordNetLemmatizer() cores = multiprocessing.cpu_count() NOOCC_INDEX = 0 NOOCC_TOKEN = 'NOOCC' MODEL_NUM = 4 abbreviations = pd.read_csv('data/other/abbreviations.csv')['Abbreviation'].tolist() abbreviations = [str(a).strip() for a in abbreviations] # - min_count = [2, 3, 4, 5] window = [2, 3 , 4, 5] size = [25, 50, 100, 200] sample=6e-5 alpha=0.05 min_alpha=0.0007 negative=20 sgTrain = 1 cbowTrain = 0 m1Clean=['Tokens', 'Lemma', 'Stopwords', 'Phrases', 'Emoticons'] m2Clean=['Tokens', 'Lemma', 'Stopwords', 'Phrases'] m1LClean=['Tokens', 'Lemma', 'Stopwords', 'Phrases', 'Lowercase'] m2LClean=['Tokens', 'Lemma', 'Stopwords', 'Phrases'] emArgs = [min_count[0], window[0], size[3], sample, alpha, min_alpha, negative] # + [markdown] colab_type="text" id="e-2ilImDKf_0" # ## Data Load # + colab={} colab_type="code" id="FL-Hd81CKf_3" fileSchiz = 'data/dataIn/schiz/nonAnnFinalSchiz.csv' textSchiz = pp.getFile(fileSchiz, 'Tweet') # + colab={} colab_type="code" id="M4j2RyTQFl0F" fileStigma = 'data/dataIn/stigma/nonAnnFinalStig.csv' textStigma = pp.getFile(fileStigma, 'Tweet') # + colab={} colab_type="code" id="yMD5fnFGGjYy" textAll = pd.concat((textSchiz, textStigma)) # + [markdown] colab_type="text" id="w0uiCC42KgAB" # ## Word2Vec and FastText Models # + colab={} colab_type="code" id="6WQJh8B5KgAB" ''' embedding class contains code to train and save down a embedding model using Gensim Library. Code is compatible with either Word2Vec or FastText libraries. ''' class EmbeddingModel(): def __init__(self, library, tokens, name): self.lib = library self.tokens = tokens self.name = name self.model = None ''' train embedding models using arguments in emArgs ''' def getEmbeddings(self, trainMethod, emArgs): print(self.lib) model = self.lib(min_count=emArgs[0], window=emArgs[1], size=emArgs[2], sample=emArgs[3], alpha=emArgs[4], min_alpha=emArgs[5], negative=emArgs[6], workers=20, sg=trainMethod) model.build_vocab(self.tokens, progress_per=10000) model.train(self.tokens, total_examples=model.corpus_count, epochs=30, report_delay=1) model.init_sims(replace=True) self.save(model) self.model = model ''' save model down ''' def save(self, model): model.save(self.name) ''' return similar words ''' def getSimilar(self, model, word): return self.model.wv.most_similar(positive=[word]) ''' get the word index using the vocabulary and add an OOV token (NOOCC_TOKEN) for word out of vocabulary ''' def getWordIndex(self, newWord=NOOCC_TOKEN, newIndex=NOOCC_INDEX ): wordIndex = {k: v.index for k, v in self.model.wv.vocab.items()} self.model.wv.vectors = np.insert(self.model.wv.vectors, [newIndex], self.model.wv.vectors.mean(0), axis=0) wordIndex = {word:(index+1) if index>= newIndex else index for word, index in wordIndex.items()} wordIndex[newWord] = newIndex return wordIndex ''' get train data using wordIndex ''' def getIndexData(self, xText, labels, wordIndex): xTrain = [[wordIndex[tok] if tok in wordIndex else wordIndex[NOOCC_TOKEN] for tok in s] for s in xText] return (np.array(xTrain), np.array(labels)) ''' count number of missing words from model ''' def countMissing(self, text, wordIndex): return sum([1 for s in text for tok in s if tok not in wordIndex]) # + [markdown] colab={} colab_type="code" id="AQbvAjHmKgAF" # ## Model Preparation # + colab={} colab_type="code" id="LWQap41dKgAK" ''' call preprocessing class and set up cleaning object ''' def initializePreProcessing(text, tokenType, cleanMethods=['Tokens', 'Lemma', 'Stopwords', 'Phrases', 'Emoticons']): social = pp.SocialPreProcessing(text, tokenType) socialClean = social.clean(cleanMethods) return socialClean ''' call embedding class and set up embedding object ''' def initializeEmbedding(library, tokens, trainMethod, name, emArg): emModel = EmbeddingModel(library, tokens, name) emModel.getEmbeddings(trainMethod, emArg) return emModel ''' train all embedding models and get their word vocabulary ''' def getEmbeddings(libraries, embeddingText, tokenTypes, cleanSchedule, trainSchedule, names, modelNum, emArgs): embeddingTexts = map(initializePreProcessing, [embeddingText]*modelNum, tokenTypes, cleanSchedule) emModels = map(initializeEmbedding, libraries, embeddingTexts, trainSchedule, names, emArgs) indicies = map(lambda x: x.getWordIndex(), emModels) return indicies, emModels ''' set up word models to get word embeddings ''' def getWordModels(libraries, embeddingText, cleanSchedule, trainSchedule, wordNames, emArgs): modelNum = len(cleanSchedule) tokenTypes = [False]*modelNum emArgs = modelNum*[emArgs] wordIndicies, wordModels = getEmbeddings(libraries, embeddingText, tokenTypes, cleanSchedule, trainSchedule, wordNames, modelNum, emArgs) return wordIndicies, modelNum ''' set up char models to get char embeddings ''' def getCharModels(libraries, embeddingText, cleanSchedule, trainSchedule, charNames, emArgs): modelNum = len(cleanSchedule) tokenTypes = [True]*modelNum emArgs = modelNum*[emArgs] charIndicies, charModels = getEmbeddings(libraries, embeddingText, tokenTypes, cleanSchedule, trainSchedule, charNames, modelNum, emArgs) return charIndicies, charModels ''' call code to get models focused on emoticons. Return both character and word models ''' def initializeEmoticonModels(libraries, embeddingText, cleanSchedule, trainSchedule, args, wNames, cNames): wordIndicies, wordModels = getWordModels(libraries, embeddingText, cleanSchedule, trainSchedule, wNames, args) charIndicies, charModels = getCharModels(libraries, embeddingText, cleanSchedule, trainSchedule, cNames, args) return (wordModels, charModels) ''' call code to get models focused on capitalized words. Return both character and word models ''' def initializeLowerModels(libraries, embeddingText, cleanSchedule, trainSchedule, emArgs, wNames, cNames): wordIndicies, wordModels = getWordModels(libraries, embeddingText, cleanSchedule, trainSchedule, wNames, emArgs) charIndicies, charModels = getCharModels(libraries, embeddingText, cleanSchedule, trainSchedule, cNames, emArgs) return (wordModels, charModels) ''' return tweets with emoticons ''' def getEmoticonText(tokens, emojis): emojiLines = list(map(lambda x: any(i in emojis for i in x), tokens)) tokens = np.array(tokens) emojiLines = np.array(emojiLines) tokens = tokens[emojiLines] return tokens # + [markdown] colab_type="text" id="xaG3tFPeK4KF" # ## Mental health Stigma Dataset - Not in project # + colab={} colab_type="code" id="wozZ6YP6GjZQ" trainSchedule = [cbowTrain, sgTrain,] * 2 cleanSchedule = [m2Clean, m2Clean] *2 libraries = [Word2Vec]* 2 + [FastText] * 2 args = [min_count[0], window[0], size[3], sample, alpha, min_alpha, negative] # + colab={} colab_type="code" id="c__k--0pKgAO" wordNames = ['w2vWCBStig', 'w2vWCBEmStig', 'ftWSGStig', 'ftWSGEmStig'] charNames = ['w2vCCBStig', 'w2vCCBEMStig', 'ftCSGStig', 'ftCSGEmStig'] paths = ['embeddings/Word2Vec/stigma/']*2 + ['embeddings/FastText/stigma/']*2 wordNames = getFilePath(paths, wordNames) charNames = getFilePath(paths, charNames) # + colab={"base_uri": "https://localhost:8080/", "height": 561} colab_type="code" id="MGL00kusGjZb" outputId="5a6a75fe-2387-41be-e008-72956f9f043a" modelsStigma = initializeEmoticonModels(libraries, textStigma, cleanSchedule, trainSchedule, args, wordNames, charNames) # + [markdown] colab_type="text" id="VEgyLRCzGjZh" # ## Schizophrenia Stigma Dataset # - # Concentrate on embedding models with emoticons and without emoticons. Model code below can be found in the appendix # of the paper. The pipelines below take the data and perform all the NLP preprocessing according to the model being # constructed. For example the model 'w2vWCBSchiz' doesn't have the letters Em in it and therfore it will use m1Clean to remove the emoticons. Train schedule also determines if Skip Gram or CBOW is used. # + [markdown] colab_type="text" id="UHsiEVJ8GjZl" # ### Emoticons This first set of models looks at all data and remove emoticons accordingly # + colab={} colab_type="code" id="eX6l4AWWGjZm" trainSchedule = [cbowTrain, cbowTrain, sgTrain, sgTrain] * 2 cleanSchedule = [m1Clean, m2Clean, m1Clean, m2Clean]* 2 libraries = [Word2Vec]*4 + [FastText] * 4 # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="DSZiOrqPGjZp" outputId="1bdadaa4-5fbe-432d-f15c-fa6a070e54a0" wordNames = ['w2vWCBSchiz', 'w2vWCBEmSchiz', 'w2vWSGSchiz', 'w2vWSGEmSchiz', 'ftWCBSchiz', 'ftWCBEmSchiz', 'ftWSGSchiz', 'ftWSGEmSchiz'] charNames = ['w2vCCBSchiz', 'w2vCCBEMSchiz', 'w2vCSGSchiz', 'w2vCSGEmSchiz', 'ftCCBSchiz', 'ftCCBEMSchiz', 'ftCSGSchiz', 'ftCSGEmSchiz'] path1 = ['embeddings/Word2Vec/schiz/'] path2 = ['embeddings/FastText/schiz/'] wordNames = utility.getFilePath(path1, path2, wordNames) charNames = utility.getFilePath(path1, path2, charNames) libraries = [Word2Vec]*4 + [FastText]*4 # - modelsSchiz = initializeEmoticonModels(libraries, textSchiz, cleanSchedule, trainSchedule, emArgs, wordNames, charNames) # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="lr3VujcBGjZ1" outputId="9b4ee41f-37de-47ca-83ef-1ae4d3674541" #emWordNames = ['w2vemWCBSchiz', 'w2vemWCBEmSchiz', 'w2vemWSGSchiz', 'w2vemWSGEmSchiz', 'ftemWCBSchiz', 'ftemWCBEmSchiz', 'ftemWSGSchiz', 'ftemWSGEmSchiz'] #emCharNames = ['w2vemCCBSchizSchiz', 'w2vemCCBEMSchiz', 'w2vemCSGSchiz', 'w2vemCSGEmSchiz', 'ftemCCBSchizSchiz', 'ftemCCBEMSchiz', 'ftemCSGSchiz', 'ftemCSGEmSchiz'] #paths = ['embeddings/Word2Vec/schiz/emoticons/']*4 + ['embeddings/FastText/schiz/emoticons/']*4 #emWordNames = getFilePath(paths, emWordNames) #emWharNames = getFilePath(paths, emCharNames) #emojiTexts = getModelsTwo(textSchiz, UNICODE_EMOJI) #modelsStigma = initializeEmoticonModels(libraries, textSchiz, cleanSchedule, trainSchedule, emArgs, emWordNames, emCharNames) # - # ### Emoticon work around for NLTK problem. Load the data saved down by Spacey pre-Tokenized # Due NLTK tokenizer not tokenizing all emoticons, I use SpaceyMoji. Unfortunately this is a python 3 package so it is in a separate notebook, 08 SpaceyMoji, and I save down the tokenized data. Then I load in the SpaceyMoji tokenized data and then create all the relevant embedding models here. Create embedding models for both word and character tokens fileEmoji = 'data/dataOut/schiz/emoji/nonAnnFinalSchizEmoji.csv' textEmoji = pp.getFile(fileEmoji, 'Tweet') textEmoji = textEmoji.apply(lambda x: x[1:len(x)-1]) textEmoji = textEmoji.apply(lambda x: x.split(', ')) fileEmojiChar = 'data/dataOut/schiz/emoji/nonAnnFinalSchizEmojiChar.csv' textEmojiChar = pp.getFile(fileEmojiChar, 'Tweet') textEmojiChar = textEmojiChar.apply(lambda x: x[1:len(x)-1]) textEmojichar = textEmojiChar.apply(lambda x: x.split(', ')) emWordNames = ['w2vemWCBSchiz', 'w2vemWCBEmSchiz', 'w2vemWSGSchiz', 'w2vemWSGEmSchiz', 'ftemWCBSchiz', 'ftemWCBEmSchiz', 'ftemWSGSchiz', 'ftemWSGEmSchiz'] emCharNames = ['w2vemCCBSchizSchiz', 'w2vemCCBEMSchiz', 'w2vemCSGSchiz', 'w2vemCSGEmSchiz', 'ftemCCBSchizSchiz', 'ftemCCBEMSchiz', 'ftemCSGSchiz', 'ftemCSGEmSchiz'] path1 = ['embeddings/Word2Vec/schiz/02 emoticons2/'] path2 = ['embeddings/FastText/schiz/02 emoticons2/'] m1Clean=['Lemma', 'Stopwords', 'Phrases', 'Emoticons'] m2Clean=['Lemma', 'Stopwords', 'Phrases'] cleanSchedule = [m1Clean, m2Clean, m1Clean, m2Clean]* 2 trainSchedule = [cbowTrain, cbowTrain, sgTrain, sgTrain] * 2 libraries = [Word2Vec]*4 + [FastText]*4 emWordNames = utility.getFilePath(path1, path2, emWordNames) emCharNames = utility.getFilePath(path1, path2, emCharNames) #WORD TOKENS wordIndicies, wordModels = getWordModels(libraries, textEmoji, cleanSchedule, trainSchedule, emWordNames, emArgs) #CHARACTER TOKENS charIndicies, charModels = getCharModels(libraries, textEmojiChar, cleanSchedule, trainSchedule, emCharNames, emArgs) # + [markdown] colab_type="text" id="IGAcJ8YHGjZ5" # ### Capitalized Words # - # This follows the same logic as above except we add in the lowercase cleaning function if we are looking at models that should all be lowercase. Same pipeline is followed, NLP prepocessing and then we train the embeddings. These are saved down in the lowercase folder. # + colab={} colab_type="code" id="xiNg1vd8GjaB" lCharNames = ['w2vCCBSchiz', 'w2vCCBlSchiz', 'w2vCSGSchiz', 'w2vCSGlSchiz''ftCCBSchiz', 'ftCCBlSchiz', 'ftCSGSchiz', 'ftCSGlSchiz'] lWordNames = ['w2vWCBSchiz','w2vWCBlSchiz', 'w2vWSGSchiz', 'w2vWSGlSchiz', 'ftWCBSchiz','ftWCBlSchiz', 'ftWSGSchiz', 'ftWSGlSchiz'] path1 = ['embeddings/Word2Vec/schiz/01 lowercase/all/'] path2 = ['embeddings/FastText/schiz/01 lowercase/all/'] lWordNames = utility.getFilePath(path1, path2, lWordNames) lCharNames = utility.getFilePath(path1, path2, lCharNames) libraries = [Word2Vec]*4 + [FastText]*4 trainSchedule = [cbowTrain, cbowTrain, sgTrain, sgTrain] * 2 cleanSchedule = [m1LClean, m2LClean, m1LClean, m2LClean] * 2 # - models = initializeLowerModels(libraries, textSchiz, cleanSchedule, trainSchedule, emArgs, lWordNames, lCharNames) # here we train embedding models with only tweets that contain lowercase words. Given this led to around a small number of tweets ca.3000, it was decided to not include this in the paper because the size of the dataset became the overwhelming factor in the classification performance # + colab={} colab_type="code" id="m522MCqEGjaI" lCharNames = ['w2vlCCBSchiz', 'w2vlCCBlSchiz', 'w2vlCSGSchiz', 'w2vlCSGlSchiz', 'ftlCCBSchiz', 'ftlCCBlSchiz', 'ftlCSGSchiz', 'ftlCSGlSchiz'] lWordNames = ['w2vlWCBSchiz', 'w2vlWCBlSchiz', 'w2vlWSGSchiz', 'w2vlWSGlSchiz', 'ftlWCBSchiz', 'ftlWCBlSchiz', 'ftlWSGSchiz', 'ftlWSGlSchiz'] lowerTexts = getModelsTwo(textSchiz) models = initializeLowerModels(libraries, textSchiz, cleanSchedule, trainSchedule, emArgs, lWordNames, lCharNames) # + [markdown] colab_type="text" id="ED-tad-lGjaL" # ## Combined schizophrenia and stigma - Not used in the final paper # - # Combined the two datasets for the embedding models to see if this increased the performance # + colab={} colab_type="code" id="lZsBVlmjGjaM" emWordNames = ['w2vWCBAll', 'w2vWCBEmAll', 'w2vWSGAll', 'w2vWSGEmAll', 'ftWCBAll', 'ftWCBEmAll', 'ftWSGAll', 'ftWSGEmAll'] emCharNames = ['w2vCCBAll', 'w2vCCBEMAll', 'w2vCSGAll', 'w2vCSGEmAll', 'ftCCBAll', 'ftCCBEMAll', 'ftCSGAll', 'ftCSGEmAll'] trainSchedule = [cbowTrain, cbowTrain, sgTrain, sgTrain] * 2 cleanSchedule = [m2Clean, m2Clean, m2Clean, m2Clean] * 2 modelsStigma = initializeEmoticonModels(libraries, textAll, cleanSchedule, trainSchedule, emArgs, emWordNames, emCharNames) # + colab={} colab_type="code" id="_cQQtyzubAwy" #Get training data trainText = map(initializePreProcessing, [text]) getIndexData = map(lambda f, x, y, z: f.getIndexData(x, y, z), emModels, trainText, [labels], wordIndicies) # + colab={} colab_type="code" id="3XW-eD2mKgAp" #Check number of missing words total = sum([1 for s in trainText[0] for tok in s]) missing = map(lambda f, x, y: f.countMissing(x, y), emModels, trainText, wordIndicies) missing = map(lambda x, y: x/float(y), missing, [total]*len(missing)) # - # ### Size of Embedding # This was used to test how size affects the embedding models performance. This is in the final paper ''' loops through the data and incrementally and splits it up in multiples of 100 ''' def getSizeEmbeddings(textSet, modelPath, libraries): for i in range(len(textSet)): text = textSet[i] text = pd.Series(text) models = [w+str(i) for w in modelPath] x, y = getWordModels(libraries, text, cleanSchedule, trainSchedule, models, emArgs) textSchizLst = textSchiz.tolist() schizSets = [textSchizLst[0:i+100] for i in range(0, len(textSchizLst), 100)] m2Clean=['Tokens', 'Lemma', 'Stopwords', 'Phrases'] trainSchedule = [sgTrain] cleanSchedule = [m2Clean] libraries = [Word2Vec] w2vWordPath = ['embeddings/size/w2v/w2vWSGEmSchiz'] ftWordNames = ['embeddings/size/ft/ftWSGEmSchiz'] librariesFt = [FastText] getSizeEmbeddings(schizSets, ftWordNames, librariesFt) # + [markdown] colab={} colab_type="code" id="rEKoKl7-KgAx" # ### ELMO - This is not in the project # + colab={} colab_type="code" id="J5qwYGCv9g_t" import pandas as pd import numpy as np from tqdm import tqdm import re import time import pickle import tensorflow_hub as hub import tensorflow as tf from sklearn.model_selection import train_test_split # + colab={} colab_type="code" id="vH_f9x5r9g_y" outputId="8893ea5a-a5b2-415f-f551-495f5cc91950" trainList = embeddingStigma.tolist() elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True) # + colab={} colab_type="code" id="9Dga1i1Q9g_2" def getELMO(elmo, text): embeddings = elmo(text, signature='default', as_dict=True)['elmo'] sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run(tf.tables_initializer()) embedding = sess.run(tf.reduce_mean(embeddings,1)) sess.close() return embedding # + colab={} colab_type="code" id="a57LAZpD9g_3" xTrain = [[sent] for sent in trainList] elmoEmbed = [getELMO(elmo, sent) for sent in xTrain] # + colab={} colab_type="code" id="VngMtKgcYIGf" elmoEmbed # + colab={} colab_type="code" id="sAn_Km9r9g_5" pickle_out = open("elmo_train_03032019.pickle","wb") pickle.dump(elmoEmbed, pickle_out) pickle_out.close()
notebooks/03 embeddings.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib notebook import matplotlib.pyplot as plt from sympy import * init_printing() # + x,y=var("x y") x,y f=x**3 - 3*x**2-24*x+32 df=f.diff() ddf=df.diff() df,ddf # + pc=solve(df) pc # - plot(f)
CLASES/Clase Grafica 2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:py3_sci] # language: python # name: conda-env-py3_sci-py # --- # # Estimating poly(A) tail length with Nanopolish polyA # # Code for producing Figures 2 and S2 on poly(A) tail length in Arabidopsis and ERCC reads # + import sys import os from glob import glob import random from collections import Counter import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import matplotlib_venn as vn from matplotlib.colors import ListedColormap import seaborn as sns import pysam ## Default plotting params # %matplotlib inline sns.set(font='Arial') plt.rcParams['svg.fonttype'] = 'none' style = sns.axes_style('white') style.update(sns.axes_style('ticks')) style['xtick.major.size'] = 2 style['ytick.major.size'] = 2 sns.set(font_scale=1.5, style=style) pal = sns.color_palette(['#0072b2', '#d55e00', '#009e73', '#f0e442', '#cc79a7']) cmap = ListedColormap(pal.as_hex()) sns.set_palette(pal) sns.palplot(pal) plt.show() # + polya_lengths = {} for fn in [x for x in glob('../*Col0*/polya_tails/*_col0_*_polya_lengths.tsv.gz') if 'ERCC' not in x]: sample = os.path.split(fn)[1].split('_polya_')[0] p = pd.read_table( fn, sep='\t', usecols=['readname', 'contig', 'position', 'polya_length', 'qc_tag'], na_values=['-1'], dtype={'readname': str, 'contig': str, 'position': int, 'polya_length': float, 'qc_tag': 'category'}, index_col='readname' ) #p = p[p['qc_tag'] == 'PASS'] polya_lengths[sample] = p polya_lengths = pd.concat(polya_lengths, axis=0) polya_lengths.head() # - polya_lengths.qc_tag.value_counts() sum(polya_lengths.qc_tag == 'PASS') / len(polya_lengths) polya_lengths = polya_lengths[polya_lengths['qc_tag'] == 'PASS'] fig, ax = plt.subplots(figsize=(5.5, 5.5)) mt = polya_lengths[polya_lengths.contig == 'Mt'] pt = polya_lengths[polya_lengths.contig == 'Pt'] nc = polya_lengths[~polya_lengths.contig.isin(['Mt', 'Pt'])] sns.distplot(pt.dropna().polya_length, hist=True, kde=False, bins=np.linspace(0, 200, 50), hist_kws={'density': True}, color=pal[2], label='Chloroplast') sns.distplot(mt.dropna().polya_length, hist=True, kde=False, bins=np.linspace(0, 200, 50), hist_kws={'density': True}, color=pal[1], label='Mitochondrial') sns.distplot(nc.dropna().polya_length, hist=True, kde=False, bins=np.linspace(0, 200, 50), hist_kws={'density': True}, color=pal[0], label='Nuclear') ax.set_xlabel('Poly(A) tail length') ax.set_ylabel('Reads (Frequency Density)') #ax.set_xticks([0, 1, 2, 3]) #ax.set_xticklabels([1, 10, 100, 1000]) #ax.set_xlim(-1, 2.75) ax.legend(fontsize=14) plt.tight_layout() plt.savefig('polya_tail_length_dist.svg', transparent=True) plt.show() nc.polya_length.describe(percentiles=(0.025, 0.25, 0.50, 0.75, 0.975)) pt.polya_length.describe(percentiles=(0.025, 0.25, 0.50, 0.75, 0.975)) mt.polya_length.describe(percentiles=(0.025, 0.25, 0.50, 0.75, 0.975)) # + ercc_polya_lengths = {} for fn in glob('../*Col0*_ERCC/polya_tails/*_col0_*_polya_lengths.tsv.gz'): sample = os.path.split(fn)[1].split('_polya_')[0] p = pd.read_table( fn, sep='\t', usecols=['readname', 'contig', 'position', 'polya_length', 'qc_tag'], na_values=['-1'], dtype={'readname': str, 'contig': str, 'position': int, 'polya_length': float, 'qc_tag': 'category'}, index_col='readname' ) #p = p[p['qc_tag'] == 'PASS'] ercc_polya_lengths[sample] = p ercc_polya_lengths = pd.concat(ercc_polya_lengths, axis=0) ercc_polya_lengths.head() # - ercc_polya_lengths.qc_tag.value_counts() sum(ercc_polya_lengths.qc_tag == 'PASS') / len(ercc_polya_lengths) ercc_polya_lengths = ercc_polya_lengths[ercc_polya_lengths['qc_tag'] == 'PASS'] # + language="bash" # wget https://assets.thermofisher.com/TFS-Assets/LSG/manuals/cms_095047.txt # - ercc_seqs = pd.read_csv('cms_095047.txt', sep='\t', index_col=0) ercc_seqs['polya'] = ercc_seqs.Sequence.str.extract('(A+)$') ercc_seqs['polya_length'] = ercc_seqs['polya'].str.len() ercc_seqs.head() ercc_polya_lengths.polya_length.describe(percentiles=(0.025, 0.25, 0.50, 0.75, 0.975)) # + reads_per_contig = ercc_polya_lengths.contig.value_counts() order = reads_per_contig[reads_per_contig >= 100].index fig, ax = plt.subplots(figsize=(8, 5)) sns.boxplot( x='contig', y='polya_length', data=ercc_polya_lengths, order=order, fliersize=0, color=pal[0], ) sns.pointplot( x='ERCC_ID', y='polya_length', data=ercc_seqs.reset_index(), order=order, join=False, ci=None, estimator=lambda x: x[0] if len(x) == 1 else np.nan, color=pal[1] ) ax.set_ylim(0, 80) xticklabels = [f'{x.get_text()}\nn={reads_per_contig[x.get_text()]}' for x in ax.get_xticklabels()] ax.set_xticklabels(xticklabels, rotation=30, ha='right', va='top', fontsize=14) ax.set_xlabel('') ax.set_ylabel('Poly(A) length estimate') plt.tight_layout() plt.savefig('ERCC_polya_length_boxplot.svg') plt.savefig('ERCC_polya_length_boxplot.png') plt.show() # - fig, ax = plt.subplots(figsize=(5.5, 5.5)) sns.distplot(ercc_polya_lengths.dropna().polya_length, hist=True, kde=False, bins=np.linspace(0, 100, 50), hist_kws={'density': True}, color=pal[0]) ax.set_xlabel('Poly(A) tail length') ax.set_ylabel('Reads (Frequency Density)') #ax.set_xticks([0, 1, 2, 3]) #ax.set_xticklabels([1, 10, 100, 1000]) #ax.set_xlim(-1, 2.75) plt.tight_layout() plt.savefig('ERCC_polya_length.svg') plt.savefig('ERCC_polya_length.png') plt.show() # + vir1_pa_dists = pd.read_csv( 'data/vir1_vs_col0_polya.tsv', sep='\t', names=['chrom', 'start', 'end', 'gene_id', 'score', 'strand', 'nreads_col0', 'nreads_vir1', 'median_col0', 'ci_lower_col0', 'ci_upper_col0', 'median_vir1', 'ci_lower_vir1', 'ci_upper_vir1', 'ks', 'ks_p_val', 'ks_fdr', 'mwu', 'mwu_p_val', 'mwu_fdr'] ) vir1_pa_dists['cpm_col0'] = vir1_pa_dists['nreads_col0'] / vir1_pa_dists['nreads_col0'].sum(0) * 1_000_000 vir1_pa_dists['cpm_vir1'] = vir1_pa_dists['nreads_vir1'] / vir1_pa_dists['nreads_vir1'].sum(0) * 1_000_000 vir1_pa_dists['med_change'] = vir1_pa_dists['median_vir1'] - vir1_pa_dists['median_col0'] vir1_pa_dists.head() # + fig, ax = plt.subplots(figsize=(5.2, 5)) plt.tight_layout() nuclear_only = vir1_pa_dists[vir1_pa_dists.chrom.isin(list('12345'))] sns.regplot( x=np.log2(nuclear_only.cpm_col0), y=nuclear_only.median_col0, scatter_kws={'alpha': 0.05, 'rasterized': True}, line_kws={'color': '#252525'}, lowess=False, ax=ax ) ax.set_xlabel('Expression (logCPM)') ax.set_ylabel('Median poly(A) tail length') rho, p = stats.spearmanr(nuclear_only.cpm_col0, nuclear_only.median_col0) ax.annotate(xy=(0.67, 0.9), s=f'ρ={rho:.2f}', xycoords='axes fraction') plt.tight_layout() plt.savefig('polya_length_vs_expression.svg') plt.show() # - print(rho, p) # + boot_res = [] s = nuclear_only.loc[:, ['cpm_col0', 'median_col0']] n = len(s) for _ in range(10_000): samp = s.sample(n=n, replace=True) boot_res.append(stats.spearmanr(samp['cpm_col0'], samp['median_col0'])[0]) # - plt.hist(boot_res) plt.show() np.percentile(boot_res, (2.5, 97.5))
notebooks/04_polya_lengths.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Short Corridor with Switched Actions # --- # Consider the small corridor grid world shown inset in the graph below. The reward is -1 per step, as usual. In each of the three nonterminal states there are only two actions, right and left. These actions have their usual consequences in the first and third states (left causes no movement in the first state), but in the second state they are reversed, so that right moves to the left and left moves to the right. The problem is difficult because all the states appear identical under the function approximation. In particular, we define `x(s, right) = [1, 0]` and `x(s, left) = [0, 1]`, for all s. # # $$J(\theta) = V_{\pi_\theta}(S)$$ # # <img src="corridor.png" width="600"> # # MC Policy Gradient # --- # <img src="mc_policy_gradient.png" width="600"> # <img src="h.png" width="300"> # <img src="policy.png" width="400"> import numpy as np import matplotlib.pyplot as plt # + code_folding=[] class ShortCorridor: def __init__(self, alpha=0.2, gamma=0.8): self.actions = ["left", "right"] self.x = np.array([[0, 1], [1, 0]]) # left|s, right|s self.theta = np.array([-1.47, 1.47]) self.state = 0 # initial state 0 self.gamma = gamma self.alpha = alpha def softmax(self, vector): return np.exp(vector)/sum(np.exp(vector)) def chooseAction(self): h = np.dot(self.theta, self.x) prob = self.softmax(h) # left, right probability for all state imin = np.argmin(prob) epsilon = 0.05 if prob[imin] < epsilon: prob[:] = 1 - epsilon prob[imin] = epsilon action = np.random.choice(self.actions, p=prob) return action def takeAction(self, action): if self.state == 0: nxtState = 0 if action == "left" else 1 elif self.state == 1: nxtState = 2 if action == "left" else 0 # reversed elif self.state == 2: nxtState = 1 if action == "left" else 3 else: nxtState = 2 if action == "left" else 3 return nxtState def giveReward(self): if self.state == 3: return 0 return -1 def reset(self): self.state = 0 def run(self, rounds=100): actions = [] rewards = [] for i in range(1, rounds+1): reward_sum = 0 while True: action = self.chooseAction() nxtState = self.takeAction(action) reward = self.giveReward() reward_sum += reward actions.append(action) rewards.append(reward) self.state = nxtState # game end if self.state == 3: T = len(rewards) for t in range(T): # calculate G G = 0 for k in range(t+1, T): G += np.power(self.gamma, k-t-1)*rewards[k] j = 1 if actions[t] == "right" else 0 # dev on particular state h = np.dot(self.theta, self.x) prob = self.softmax(h) grad = self.x[:, j] - np.dot(self.x, prob) self.theta += self.alpha*np.power(self.gamma, t)*G*grad # reset self.state = 0 actions = [] rewards = [] if i % 50 == 0: print("round {}: current prob {} reward {}".format(i, prob, reward_sum)) reward_sum = 0 break # - sc = ShortCorridor(alpha=2e-4, gamma=1) sc.run(1000) h = np.dot(sc.theta, sc.x) sc.softmax(h) # left, right probability for all state
ShortCorridor/ShortCorridor.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python # language: python # name: conda-env-python-py # --- # # Part 1 # ### Import the needed libraries # + jupyter={"outputs_hidden": true} conda install lxml; # - import pandas as pd, numpy as np conda install -c conda-forge geopy --yes; # ### Read the webpage and find the table url='https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M' tables = pd.read_html(url) toronto = tables[0] # # ### Replacing words "Not assigned" and delete such rows in the Borough column (we should ignore it). # ### In the third row of code below I replace Not assigned Neighbourhood with the name from the Borough column. #replace not assigned with Nan toronto=toronto.replace('Not assigned',np.nan) #drop nan in Borugh column inplace toronto.dropna(axis=0,how='any',subset=['Borough'],inplace=True) #data in Neighbourhood column should be replaced with Borough values toronto['Neighbourhood'].replace(np.nan,toronto['Borough'],inplace=True) #now you can see the head of my toronto table toronto.head().sort_values('Borough') # ### Here I prepare some values to start work with columns. # #### I need for values from Postcode column without duplicates. # obtain data from Postcode column without duplicates; it will be 'plist' plist=toronto.Postcode.drop_duplicates().to_frame() plist.head() # I named iterater for plist as plist_i and set it to zero plist_i=0 # in while-loop I want to find and join all Neighbourhoods for each Postcode # so, while plist_i is not equal to the length of plist... while plist_i<len(plist): # I will use adding (it is what I will add to Neighbourhoods) adding='' # plist_x is the value of Postcode column in plist plist_x=plist.iloc[plist_i,0] # with loc I can find Neighbourhoods which corresponds to Postcode values x=toronto.loc[(toronto['Postcode']==plist_x),'Neighbourhood'] # they should be joined into one line adding=', '.join(x) # and all cells in Toronto table should be set to such line toronto.loc[(toronto['Postcode']==plist_x),'Neighbourhood']=adding # then it should be repeated with all other Postcode values plist_i=plist_i+1 # to escape duplicates toronto=toronto.drop_duplicates() # now you can see shape and head of Toronto Table print('Shape of Toronto Table is ', toronto.shape) toronto.reset_index(drop=True,inplace=True) toronto.head(10) # # # Part 2 # #### As geocoder was not available, I could only use the csv file gscoord = pd.read_csv('gscoord.csv') gscoord.head() # #### Initially, I created two empty column, and then I started to fill # #### them with the values (Latitude and Longitude) from gscoord dataframe. i=0 toronto['Latitude']=' ' toronto['Longitude']=' ' while i<len(toronto): x=toronto.iloc[i,0] toronto.iloc[i,3]=gscoord.loc[gscoord['Postal Code']==x,'Latitude'].values[0] toronto.iloc[i,4]=gscoord.loc[gscoord['Postal Code']==x,'Longitude'].values[0] i=i+1 toronto.head() # #### In the next step, I imported folium library, # #### chose to work with data about Toronto, Ontario # #### and added data about this region to the map. # + # map rendering library import folium from geopy.geocoders import Nominatim # I chose Toronto, Ontario address = 'Toronto, Ontario' geolocator = Nominatim(user_agent="ny_explorer") location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Toronto are {}, {}.'.format(latitude, longitude)) # create map of Toronto using latitude and longitude values map_toronto = folium.Map(location=[latitude, longitude], zoom_start=10) # add markers to map for lat, lng, borough, neighbourhood in zip(toronto['Latitude'], toronto['Longitude'], toronto['Borough'], toronto['Neighbourhood']): label = '{}, {}'.format(neighbourhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='green', fill=True, fill_color='#3186cc', fill_opacity=0.6, parse_html=False).add_to(map_toronto) map_toronto # - # #### Here I used my credentials from Foursquare service # + CLIENT_ID = 'deleted' # your Foursquare ID CLIENT_SECRET = 'deleted' # your Foursquare Secret VERSION = '20180605' # Foursquare API version print('Your credentails:') print('CLIENT_ID: ' + CLIENT_ID) print('CLIENT_SECRET:' + CLIENT_SECRET) # - # #### At the next step I dropped duplicates from toronto dataframe # #### and saved new dataframe as toronto_exploring torontod = toronto.loc[toronto['Borough'].str.contains('Toronto'),'Borough'].drop_duplicates() toronto_exploring=toronto.loc[toronto.Borough.isin(torontod),:] toronto_exploring.head() # #### then I obrained the coordinates of Toronto, Ontario # + address = 'Toronto, Ontario' geolocator = Nominatim(user_agent="ny_explorer") location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Toronto are {}, {}.'.format(latitude, longitude)) # create map of Toronto using latitude and longitude values map_toronto_exploring = folium.Map(location=[latitude, longitude], zoom_start=11) # - # #### ... and added coordinates from toronto_exporing to the map in the view of popup labels. # + # add markers to map for lat, lng, borough, Neighbourhood in zip(toronto_exploring['Latitude'], toronto_exploring['Longitude'], toronto_exploring['Borough'], toronto_exploring['Neighbourhood']): label = '{}, {}'.format(Neighbourhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='green', fill=True, fill_color='#3186cc', fill_opacity=0.6, parse_html=False).add_to(map_toronto_exploring) map_toronto_exploring # - # #### The next task for me was to obtain data from Foursquare about Toronto, Ontario and transform them to the dataframe. # #### I have used the way we learnt in Labs while learning this course. def getNearbyVenues(names, latitudes, longitudes, radius=500): #limit for length of list LIMIT=100 #create an empty list venues_list=[] #for every note from our dataframe function will... for name, lat, lng in zip(names, latitudes, longitudes): # ...create the API request URL url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT) # ...make the GET request with the previous created url and get json-formatted text results = requests.get(url).json()["response"]['groups'][0]['items'] # to return only relevant information for each nearby venue we should choose district name, # coordinates, venue_name, venue coordinates and categories venues_list.append([( name, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results]) # now we can store that in dataframe nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list]) #and rename columns nearby_venues.columns = ['Neighbourhood', 'Neighbourhood Latitude', 'Neighbourhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category'] return(nearby_venues) # #### This cell only provide data for the function that allows me to attain that dataframe. # + import requests # library to handle requests from pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe toronto_venues = getNearbyVenues(names=toronto_exploring['Neighbourhood'], latitudes=toronto_exploring['Latitude'], longitudes=toronto_exploring['Longitude'] ) toronto_venues.head() # - # #### Here you can see the shape of my dataframe. print('The shape of Toronto Dataframe is', toronto_venues.shape) # #### The next task I did, was sorting and screening the most frequent venue category in Toronto. toronto_venues.groupby('Neighbourhood',as_index=False).count().sort_values('Venue Category', ascending=0).head(10)[['Neighbourhood','Venue Category']] # #### I chose the first 20 from them I saw how many venues in each of them. x=toronto_venues.groupby('Venue Category',as_index=False).count().sort_values('Venue', ascending=0).head(20)[['Venue Category','Venue']] x # #### In the several next cells you can see some additional facts about them print('There are {} uniques categories.'.format(len(toronto_venues['Venue Category'].unique()))) print('There are {} uniques Venues'.format(x['Venue'].unique().sum()), 'in top 20 Venue Categories.') # #### If I decided to seek for a place for living there, I would like to live near Gym, Park, Bakery, Fish Market, Grocery or Store. # #### Actually, I have tried to perform seeking with Excel, but it takes me for some more time, than just using python and clustering... my_list=['Gym','Park','Bakery','Fish Market','Grocery','Store',\ 'Department Store','Miscellaneous Shop','Shopping Mall'] x=toronto_venues.loc[toronto_venues['Venue Category'].isin(my_list),'Venue'] print('There are {} unique Venues'.format(x.count()),'in my favourite list') # #### so, there are 116 unique Venues from 238 unique categories. I would like to create some auto method to choose the best place for living. # #### I can easily learn if there is a district that corresponds to my wishes and also has metro station, train station or airport. # #### But there are none of such... (see below) y=['Metro Station'] my_goal=toronto_venues.loc[\ (toronto_venues['Venue Category'].isin(my_list))&(toronto_venues['Venue Category'].isin(y))\ ,'Neighbourhood'] my_goal.count() y=['Train Station'] my_goal=toronto_venues.loc[\ (toronto_venues['Venue Category'].isin(my_list))&(toronto_venues['Venue Category'].isin(y))\ ,'Neighbourhood'] my_goal.count() y=['Airport Terminal', 'Airport'] my_goal=toronto_venues.loc[\ (toronto_venues['Venue Category'].isin(my_list))&(toronto_venues['Venue Category'].isin(y))\ ,'Neighbourhood'] my_goal.count() y=['Theater','Event Space','Plaza','Movie Theater','Music Venue','College Rec Center','Lake','Video Game Store','Jazz Club','Recording Studio'] my_goal=toronto_venues.loc[\ (toronto_venues['Venue Category'].isin(my_list))&(toronto_venues['Venue Category'].isin(y))\ ,'Neighbourhood'] my_goal.count() my_goal=toronto_venues.loc[\ (toronto_venues['Venue Category'].isin(my_list))\ ,['Neighbourhood','Venue']].groupby('Neighbourhood',as_index=False).count().sort_values('Venue',ascending=0) my_goal.head() # #### As you can see, due to this table, I can opt for Commerce Court, Victoria Hotel... # ##### more likely than other neighborhoods. # #### But what if there are some other types of venues which are not in my interests? # #### For instance, I do not like to live near restaurants, clubs, business centers and so on. # #### So, I can consider Neighborhoods that corresponds to my initial wishes as my preferable regions for residency. print ('There are ', my_goal.count()[1], 'nerghborhood that correspond to my wishes.') # #### Since I have not in mind how I can distinguish neighborhoods of my wishes and neighborhoods # #### which are not appropriate for me, I should start to use clustering to attain my goal. # #### Now I can perform one hot encoding as it was described in this course # #### I need to do that to use categorical values in my investigation. # #### As the result, you can see what kind of Venues there are in each neighborhood. # + # one hot encoding toronto_onehot = pd.get_dummies(toronto_venues[['Venue Category']], prefix="", prefix_sep="") # add neighborhood column back to dataframe toronto_onehot['Neighbourhood'] = toronto_venues['Neighbourhood'] # move neighborhood column to the first column fixed_columns = [toronto_onehot.columns[-1]] + list(toronto_onehot.columns[:-1]) toronto_onehot = toronto_onehot[fixed_columns] toronto_onehot.tail() # - # #### Here I just want to know what is frequency of each kind of venues. toronto_grouped = toronto_onehot.groupby('Neighbourhood').mean().round(4).reset_index() toronto_grouped.head() toronto_grouped.shape # #### Now I want to obtain information about 5 the most common venues in each neighborhoods. # + # firstly, I grouped my dataframe by neighborhoods toronto_grouped1 = toronto_onehot.groupby('Neighbourhood').mean().round(4) # then, I created the initial list for new dataframe (list will be changed) toronto_v_top=pd.DataFrame(['1','2','3','4','5','6','7','8','9','10']) # then, I created the initial list for header for new dataframe toronto_v_columns=[] k=0 while k<len(toronto_grouped1): # firstly, I transposed my dataframe, and sorted it from high to low n_toronto_grouped1=pd.DataFrame(toronto_grouped1.iloc[k,:].transpose().sort_values(ascending=False)) #got index from transposed dataframe (I got the first 5 of them to obtain 5 the most common Venue) toronto_v_top[k]=pd.DataFrame(n_toronto_grouped1.head(10)).index #and added columns name (which are the name of neighborhoods) to the list of future columns toronto_v_columns.append(pd.DataFrame(n_toronto_grouped1.head(10)).columns.values.tolist()) k=k+1 # + #after perfoming tasks from the previous cell, I can create the columns, toronto_v_columns=pd.DataFrame(toronto_v_columns) # and change the name of columns in created dataframe toronto_v_top.columns=toronto_v_columns[0] #and perform transpositioin again toronto_v_top=toronto_v_top.T #Again, I need the names of new dataframe columns, toronto_v_top.columns=['1st Most Common Venue','2nd Most Common Venue','3rd Most Common Venue','4th Most Common Venue','5th Most Common Venue',\ '6th Most Common Venue','7th Most Common Venue','8th Most Common Venue','9th Most Common Venue','10th Most Common Venue'] #reset index, toronto_v_top.reset_index(level=0, inplace=True) #rename the first column toronto_v_top.rename(columns={0:'Neighbourhood'},inplace=True) #and check my result toronto_v_top.head() # - # #### I can use the method from our Lab to create the Cluster Labels for Venues in my dataframe # + # import k-means from clustering stage from sklearn.cluster import KMeans # set number of clusters kclusters = 7 toronto_grouped_clustering = toronto_grouped.drop('Neighbourhood', 1) # run k-means clustering kmeans = KMeans(n_clusters=kclusters, random_state=0).fit(toronto_grouped_clustering) # check cluster labels generated for each row in the dataframe kmeans.labels_[0:10] # + # add clustering labels toronto_v_top.insert(0, 'Cluster Labels', kmeans.labels_) toronto_merged = toronto # merge toronto_grouped with toronto_data to add latitude/longitude for each neighborhood toronto_merged = toronto_merged.join(toronto_v_top.set_index('Neighbourhood'), on='Neighbourhood') toronto_merged=toronto_merged.dropna(axis=0,inplace=False,how='any',subset=['Cluster Labels']).sort_values('Cluster Labels',ascending=False) toronto_merged.head() # + import matplotlib.cm as cm import matplotlib.colors as colors # create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i + x + (i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, poi, cluster in zip(toronto_merged['Latitude'], toronto_merged['Longitude'], toronto_merged['Neighbourhood'], toronto_merged['Cluster Labels']): label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( [lat, lon], radius=5, popup=label, color=rainbow[int(cluster)-1], fill=True, # fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(map_clusters) map_clusters # - toronto_merged.loc[toronto_merged['Cluster Labels']==5.0,\ ['Cluster Labels','Neighbourhood','1st Most Common Venue','2nd Most Common Venue',\ '3rd Most Common Venue','4th Most Common Venue','5th Most Common Venue', '6th Most Common Venue','7th Most Common Venue','8th Most Common Venue','9th Most Common Venue','10th Most Common Venue']] toronto_merged.shape toronto_merged.loc[toronto_merged['Cluster Labels']==0.0,\ ['Cluster Labels','Neighbourhood','1st Most Common Venue','2nd Most Common Venue',\ '3rd Most Common Venue','4th Most Common Venue','5th Most Common Venue', '6th Most Common Venue','7th Most Common Venue','8th Most Common Venue','9th Most Common Venue','10th Most Common Venue']]\ .head() toronto_merged.loc[(toronto_merged['Cluster Labels']!=0.0),\ ['Cluster Labels','Neighbourhood','1st Most Common Venue','2nd Most Common Venue',\ '3rd Most Common Venue','4th Most Common Venue','5th Most Common Venue', '6th Most Common Venue','7th Most Common Venue','8th Most Common Venue','9th Most Common Venue','10th Most Common Venue']] # #### I should remember about my goal (i.e. preferable regions): my_goal # #### Finally, you can see that in the case I used only information about what I wish to have in my district, I should choose Commerce Court or Victoria Hotel. # #### But with using clustering I can see that they are not the best choice for me: these districts are more entertaining than, for instance Lawrence Park or Moore Park. # #### But the best options for me are 1) Lawrence Park, 2) Moore Park and Summerhill East and 3) Rosedale # #### because all of them do not contradict to my_goal list and have enough diversity in venue species which can be useful for me. #
ADSC_assignment.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import os def generate_db_url(user, password, host, db_name, protocol = "mysql+pymysql"): return f"{protocol}://{user}:{password}@{host}/{db_name}" def generate_csv_url(sheet_url): if type(sheet_url) == str: if(sheet_url.find("edit#gid") > -1): return sheet_url.replace("edit#gid", "export?format=csv&gid") else: raise ValueError("sheet_url must contain 'edit#gid' phrase") else: raise TypeError("sheet_url must be a string") def generate_df(file_name, query="", db_url="", cached=True): file_present = os.path.isfile(file_name) if cached and file_present: df = pd.read_csv(file_name) else: df = pd.read_sql(query, db_url) df.to_csv(file_name, index=False) return df
acquisition/test_bench.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Stacking the Best Models # <pre><b>This Kernel shows how the scores can be improved using Stacking Method. # Credit Goes to the following kernels # ref: # 1. https://www.kaggle.com/filemide/distance-criskiev-hyparam-cont-1-662 # 2. https://www.kaggle.com/criskiev/distance-is-all-you-need-lb-1-481 # 3. https://www.kaggle.com/marcelotamashiro/lgb-public-kernels-plus-more-features # 4. https://www.kaggle.com/scaomath/no-memory-reduction-workflow-for-each-type-lb-1-28 # 5. https://www.kaggle.com/fnands/1-mpnn/output?scriptVersionId=18233432 # 6. https://www.kaggle.com/harshit92/fork-from-kernel-1-481 # 7. https://www.kaggle.com/xwxw2929/keras-neural-net-and-distance-features # 8. https://www.kaggle.com/marcogorelli/criskiev-s-distances-more-estimators-groupkfold?scriptVersionId=18843561 # 9. https://www.kaggle.com/toshik/schnet-starter-kit # 10.https://www.kaggle.com/abazdyrev/nn-w-o-skew # # </b></pre> # ## Stat Stack nb = '99-02' # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats.mstats import gmean import seaborn as sns # %matplotlib inline from subprocess import check_output print(check_output(["ls", "../input"]).decode("utf8")) # + active="" # sub_path = "../input/chemistry-models" # all_files = os.listdir(sub_path) # all_files # - sub_path = './../output' all_files = [ 'nb60_submission_lgb_-1.5330660525700779.csv', 'nb79_submission_extra_trees_regressor_-1.56760.csv', # 'nb80_submission_extra_trees_regressor_-1.48000.csv', # 'nb81_submission_bagging_regressor_-1.44452.csv', 'nb84_submission_extra_trees_regressor_-1.60943.csv', # 'nb85_submission_extra_trees_regressor_-1.52972.csv', 'nb88_submission_lgb_-1.547953965914086.csv', # 'nb91_submission_extra_trees_regressor_-1.47467.csv', 'nb91_stack_submission_lgb_-1.7348780297791941.csv', 'nb95_stack_submission_ridge_-1.74195.csv', 'nb95_stack_submission_lasso_-1.74192.csv', 'nb96_stack_submission_extra_trees_regressor_-1.79030.csv', 'nb99_stack_submission_random_forest_regressor_-1.78717.csv', 'nb99-01_stack_submission_lgb_-1.75427.csv', ] # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" import warnings warnings.filterwarnings("ignore") outs = [pd.read_csv(os.path.join(sub_path, f), index_col=0) for f in all_files] concat_sub = pd.concat(outs, axis=1) cols = list(map(lambda x: "mol" + str(x), range(len(concat_sub.columns)))) concat_sub.columns = cols concat_sub.reset_index(inplace=True) concat_sub.head() ncol = concat_sub.shape[1] # - # check correlation concat_sub.iloc[:,1:].corr() # + corr = concat_sub.iloc[:,1:].corr() mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap='prism', vmin=0.96, center=0, square=True, linewidths=1, annot=True, fmt='.4f') # - # get the data fields ready for stacking concat_sub['m_max'] = concat_sub.iloc[:, 1:].max(axis=1) concat_sub['m_min'] = concat_sub.iloc[:, 1:].min(axis=1) concat_sub['m_median'] = concat_sub.iloc[:, 1:].median(axis=1) concat_sub.describe() cutoff_lo = 0.8 cutoff_hi = 0.2 # # Mean Stacking rank = np.tril(concat_sub.iloc[:,1:ncol].corr().values,-1) m_gmean = 0 n = 8 while rank.max()>0: mx = np.unravel_index(rank.argmax(), rank.shape) m_gmean += n*(np.log(concat_sub.iloc[:, mx[0]+1]) + np.log(concat_sub.iloc[:, mx[1]+1]))/2 rank[mx] = 0 n += 1 concat_sub['m_mean'] = np.exp(m_gmean/(n-1)**2) # + active="" # concat_sub['scalar_coupling_constant'] = concat_sub['m_mean'] # concat_sub[['id', 'scalar_coupling_constant']].to_csv('stack_mean.csv', # index=False, float_format='%.6f') # - # # Median Stacking # + path_submission = f'../output/nb{nb}_stack_median_submission.csv' print(f'save pash: {path_submission}') concat_sub['scalar_coupling_constant'] = concat_sub['m_median'] concat_sub[['id', 'scalar_coupling_constant']].to_csv(path_submission, index=False, float_format='%.6f') # - df = pd.read_csv(path_submission) df.head() plt.scatter(outs[0].scalar_coupling_constant.values, df.scalar_coupling_constant.values) # # Pushout + Median Stacking # >* Pushout strategy is bit aggresive # + active="" # concat_sub['scalar_coupling_constant'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), 1, # np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), # 0, concat_sub['m_median'])) # concat_sub[['id', 'scalar_coupling_constant']].to_csv('stack_pushout_median.csv', # index=False, float_format='%.6f') # - # # MinMax + Mean Stacking # >* MinMax seems more gentle and it outperforms the previous one # + active="" # concat_sub['scalar_coupling_constant'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), # concat_sub['m_max'], # np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), # concat_sub['m_min'], # concat_sub['m_mean'])) # concat_sub[['id', 'scalar_coupling_constant']].to_csv('stack_minmax_mean.csv', # index=False, float_format='%.6f') # - # # MinMax + Median Stacking # + active="" # concat_sub['scalar_coupling_constant'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), # concat_sub['m_max'], # np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), # concat_sub['m_min'], # concat_sub['m_median'])) # concat_sub[['id', 'scalar_coupling_constant']].to_csv('stack_minmax_median.csv', # index=False, float_format='%.6f') # - # ## Averaging Ranks # + active="" # concat_sub['scalar_coupling_constant'] = concat_sub['mol0'].rank(method ='min') + concat_sub['mol1'].rank(method ='min') + concat_sub['mol2'].rank(method ='min') # concat_sub['scalar_coupling_constant'] = (concat_sub['scalar_coupling_constant']-concat_sub['scalar_coupling_constant'].min())/(concat_sub['scalar_coupling_constant'].max() - concat_sub['scalar_coupling_constant'].min()) # concat_sub.describe() # concat_sub[['id', 'scalar_coupling_constant']].to_csv('stack_rank.csv', index=False, float_format='%.8f') # - # Best Results : Stack Median # # Blending Approach # + active="" # one = pd.read_csv('../input/chemistry-models/submission-1.619.csv') # two = pd.read_csv('../input/chemistry-models/submission-1.643.csv') # three = pd.read_csv('../input/chemistry-models/submission-1.662.csv') # # submission = pd.DataFrame() # submission['id'] = one.id # submission['scalar_coupling_constant'] = (0.65*three.scalar_coupling_constant) + (0.25*two.scalar_coupling_constant) + (0.10*one.scalar_coupling_constant) # # submission.to_csv('Aggblender.csv', index=False)
src/99-02_stack_from_kernel.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Exercise 2 # ### a) Compute the derivative of the sigmoid function: # $$\sigma(z) = \frac{1}{1 + e^{-z}}$$ # Use **Chain Rule**: # $$ # \sigma'(z)=\frac{d}{dz}\sigma(z)=\frac{d}{dz}\frac{1}{1 + e^{-z}}\\ # \sigma'(z)=\frac{d}{dz}(1 + e^{-z})^{-1}\\ # \sigma'(z)=-1 * (1 + e^{-z})^{-2} * e^{-z} * -1\\ # \sigma'(z)=\frac{e^{-z}}{(1 + e^{-z})^{2}}\\ # $$ # ### b) Show that the derivative fullfills the equation: # $$\sigma'(z) = \sigma(z).(1-\sigma(z))$$ # Reformat the derivative to use $\sigma(z)$: # $$ # \sigma'(z)=\frac{e^{-z}}{(1 + e^{-z})^{2}}\\ # \sigma'(z)=\frac{e^{-z}}{(1 + e^{-z})*(1 + e^{-z})}\\ # \sigma'(z)=\frac{1}{(1 + e^{-z})}*\frac{e^{-z}}{(1 + e^{-z})}\\ # \sigma'(z)=\frac{1}{(1 + e^{-z})}*\frac{1+e^{-z}-1}{(1 + e^{-z})}\\ # \sigma'(z)=\frac{1}{(1 + e^{-z})}*(\frac{(1+e^{-z})}{(1 + e^{-z})} - \frac{1}{(1 + e^{-z})})\\ # \sigma'(z)=\frac{1}{(1 + e^{-z})}*(1 - \frac{1}{(1 + e^{-z})})\\ # \sigma'(z) = \sigma(z).(1-\sigma(z))\\ # $$ # ### c) Compute the first and second derivative of ζ(z). Create a plot of ζ. # $$\zeta(z) = -log(\sigma(-z))$$ # $$ # \sigma(-z) = \frac{1}{1 + e^{z}}\\ # \zeta(z) = -log(\frac{1}{1 + e^{z}})\\ # \zeta(z) = -(log(1)-log(1 + e^{z}))\\ # \zeta(z) = -(0-log(1 + e^{z}))\\ # \zeta(z) = log(1 + e^{z})\\ # $$ # #### First derivative: # $$ # \zeta'(z) = \frac{1}{1 + e^z}* e^z * 1 \\ # \zeta'(z) = \frac{e^z}{1 + e^z} \\ # $$ # #### Second derivative: # $$ # f = \frac{g}{h}\\ # f' = \frac{g'.h-g.h'}{h^2} \\ # $$ # Applied for $\zeta''(z)$: # $$ # \zeta''(z) = \frac{(e^z * (1 + e^z))-(e^z * e^z)} {(1 + e^z)^2} \\ # \zeta''(z) = \frac{(e^z + e^{2z})-(e^{2z})} {(1 + e^z)^2} \\ # \zeta''(z) = \frac{e^z} {(1 + e^z)^2} \\ # $$ # + import numpy as np def zeta(x): """ Zeta function zeta = -ln(sigma(-x)) = ln(1 + e^x) Arguments: x -- array of inputs of size (1,m) Returns: y -- array of outputs of size (1,m) """ y = np.log(1 + np.exp(x)) return y # + import matplotlib.pyplot as plt x = np.linspace(-100, 100, 200) y = zeta(x) plt.plot(x, y) plt.show() # - # For $z \to -\infty$: # $$ # \lim\limits_{z \to -\infty} \zeta(z) = \lim\limits_{z \to -\infty}log(1 + e^{z})=0\\ # $$ # For $z \to \infty$: # $$ # \lim\limits_{z \to \infty} \zeta(z) = \lim\limits_{z \to \infty}log(1 + e^{z})=\infty\\ # $$ # Consider limit of $\zeta(z)/z$: # $$ # \lim\limits_{z \to \infty} \frac {\zeta(z)}{z} = \lim\limits_{z \to \infty} \frac {log(1 + e^{z})}{z}=1\\ # $$ # Asymptotes: # - y = 0 # - y = x # + def sigmoid(z): return 1/(1+np.exp(-z)) def softplus(z): return -np.log(sigmoid(-z)) def rectifier(z): return np.maximum(0,z) # + import numpy as np import matplotlib.pyplot as plt x = np.linspace(-5, 5, 50) plt.plot(x, softplus(x)) plt.plot(x, rectifier(x)) plt.legend(['Softplus', 'Rectifier']) plt.grid() plt.show() # - # ### d) Sigmoid function and its derivative: # Implement the sigmoid function in a Jupyter Notebook. Make it work such that you can # pass numpy arrays of arbitrary shape and the function is applied element-wise. Plot the # sigmoid function and its derivative by using matplotlib. # + import numpy as np def sigmoid(x): """ Sigmoid function sigma = 1/(1 + e^-x) Arguments: x -- array of inputs of size (1,m) Returns: y -- array of outputs of size (1,m) """ y = 1 / (1 + np.exp(-x)) return y def d_sigmoid(x): """ Derivative of sigmoid function dsigma = sigma(x)*(1-sigma(x)) Arguments: x -- array of inputs of size (1,m) Returns: y -- array of outputs of size (1,m) """ y = sigmoid(x)*(1 - sigmoid(x)) return y # + import matplotlib.pyplot as plt x = np.linspace(-10, 10, 100) y = sigmoid(x) plt.figure(figsize=(15,5)) plt.subplot(1,2,1) plt.plot(x, y) plt.title('Sigmoid') y1 = d_sigmoid(x) plt.subplot(1,2,2) plt.plot(x, y1) plt.title('Derivative of Sigmoid') plt.show() # - # ### e) No exercise # ### f) Non-convex function: # Show that the function # c1(x) = (σ(x) − 1)**2 # is non-convex. # Explain in which situations (initial settings) optimising c1(x) with gradient descent may # become difficult. For the explanation create a plot. Note that this exercise should give an # intuition on why mean-square error loss is less suited for classification problems. # # # $$ # c_1(x) =(\sigma(x)-1)^2 # $$ def c1(x): """ Function c1 from exercise 2f Arguments: x -- array of inputs of size (1,m) Returns: y -- array of outputs of size (1,m) """ y = (sigmoid(x)-1)**2 return y # + x = np.linspace(-10, 10, 100) y = c1(x) x1 = np.array([-5, 5]) y1 = c1(x1) plt.plot(x, y) plt.plot(x1, y1, 'g', linestyle=':', marker='o') plt.text(x1[0], y1[0], 'P1', color='r') plt.text(x1[1], y1[1], 'P2', color='r') plt.show() # - # #### Show that the function $c_1(x) =(\sigma(x)-1)^2$ is non-convex: # Demonstrating, that the function c1(x) is non-convex graphically is trivial. In the plot above, two points (P1 and P2) around the sattle-point (Around approximately x=-1) are connected by a green-dotted line. If the function c1(x) would be convex, then no point of the blue c1(x) curve would be above the green-dotted line. This is not the case, hence c1(x) is non-convex. # # #### Explain in which situations (initial settings) optimising c1(x) with gradient descent may become difficult. # The gradient descent algorithm xk+1=xk−λ∇f(xk) works best, if there is a significant gradient ∇f(xk) around the local point to be optimized. Regarding the function c1(x), this is the case for the range between -4 and 2. It can be observed in the figure above, that the gradient of c1(x) tends to go towards 0, if the x value gets very small (Smaller than -4) or very large (larger than 2). Hence, the stepsize of the gradient descent algorithm approaches 0 and gets (nearly) stuck. This kind of problem is called "The vanishing gradient" problem. # ### g) Compute the first and second derivative of the function: # $$ # c_2(x)=-(y.log(\sigma(w.x))+(1-y).log(1-\sigma(w.x))) # $$ # ### First derivative: # Use **Chain-** and **Sum-Rules**: # #### Separate in a and b: # $$ # a = y.log(\sigma(w.x))=y.log(\frac{1}{1+e^{-w.x}})\\ # b = (1-y).log(1-\sigma(w.x))=(1-y).log(1-\frac{1}{1+e^{-w.x}})\\ # $$ # #### Derivative a: # $$ # a' = y. \frac{1}{\frac{1}{1+e^{-w.x}}}.-1.(1+e^{-w.x})^{-2}.e^{-w.x}.-w\\ # a' = \frac{y.w.e^{-w.x}}{1+e^{-w.x}}\\ # $$ # #### Derivative b: # $$ # b' = (1-y). \frac{1}{1- \frac{1}{1+e^{-w.x}}} .-1.-1.(1+e^{-w.x})^{-2} .e^{-w.x}.-w\\ # b' = (1-y). \frac{1}{\frac{1+e^{-w.x}-1}{1+e^{-w.x}}}.(1+e^{-w.x})^{-2}.-w.e^{-w.x}\\ # b' = (1-y). \frac{1+e^{-w.x}}{e^{-w.x}}.\frac{-w.e^{-w.x}}{(1+e^{-w.x})^2}\\ # b' = (1-y). \frac{-w}{1+e^{-w.x}}\\ # $$ # #### Derivative $c_2$: # $$ # c'_2 = -(a'+b')\\ # c'_2 = -( \frac{y.w.e^{-w.x}}{1+e^{-w.x}} + (1-y). \frac{-w}{1+e^{-w.x}} )\\ # c'_2 = -( \frac{y.w.e^{-w.x}}{1+e^{-w.x}} + \frac{-w}{1+e^{-w.x}} - \frac{-w.y}{1+e^{-w.x}} )\\ # c'_2 = -( \frac{y.w.e^{-w.x}-w+w.y}{1+e^{-w.x}})\\ # c'_2 = -( \frac{y.w.e^{-w.x}-w+w.y}{1+e^{-w.x}})\,\times\,\frac{e^{w.x}}{e^{w.x}}\\ # c'_2 = -( \frac{y.w-w.e^{w.x}+w.y.e^{w.x}}{e^{w.x}+1})\\ # c'_2 = \frac{-w.(y-e^{w.x}+y.e^{w.x})}{e^{w.x}+1}\\ # c'_2 = \frac{-w.(y+(y-1).e^{w.x})}{e^{w.x}+1}\\ # $$ # ### Second derivative: # Use **Quotient-Rule**: # $$ # c''_2 = - (\frac{(w.(y-1).w.e^{w.x}.(e^{w.x}+1)) - (w.(y+(y-1).e^{w.x}).w.e^{w.x})} {(e^{w.x}+1)^2})\\ # c''_2 = - (\frac{w.e^{w.x}.(w.(y-1).e^{w.x}+w.(y-1)-w.y-w.(y-1).e^{w.x})} {(e^{w.x}+1)^2})\\ # c''_2 = - (\frac{w.e^{w.x}.(w.(y-1)-w.y)} {(e^{w.x}+1)^2})\\ # c''_2 = - (\frac{w.e^{w.x}.(-w)} {(e^{w.x}+1)^2})\\ # c''_2 = \frac{w^2.e^{w.x}} {(e^{w.x}+1)^2}\\ # $$ # #### Show that c2 is convex for x != 0 # + def c2(w,x,y): return -(y*np.log(sigmoid(w*x))+(1-y)*np.log(1-sigmoid(w*x))) plt.figure(figsize=(15,5)) # c2 with y=0 and w=1 (Just a scaling factor) plt.subplot(1,2,1) plt.plot(x, c2(1,x,0)) plt.title('c2 with y=0 and w=1') plt.grid() # straight line to proove the function c2 with y=0 to be convex x1 = -4 x2 = 4 p1 = [x1, c2(1,x1,0)] p2 = [x2, c2(1,x2,0)] plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'o-') plt.legend(['c2(w,x,y)', 'Two connected points']) # c2 with y=1 and w=1 (Just a scaling factor) plt.subplot(1,2,2) plt.plot(x, c2(1,x,1)) plt.title('c2 with y=1 and w=1') plt.grid() # straight line to proove the function c2 with y=1 to be convex x1 = -4 x2 = 4 p1 = [x1, c2(1,x1,1)] p2 = [x2, c2(1,x2,1)] plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'o-') plt.legend(['c2(w,x,y)', 'Two connected points']) plt.show() # - # Given an orange line of any two connected points in the blue function c2(w,x,y), all points of c2(w,x,y) lie underneath the line. Hence, the function c2(w,x,y) is convex. # #### Another point of view: #Compute second derivative def dd_c2(w, x): """ Second derivative of c2 Arguments: w -- array of inputs of size (1,m) x -- array of inputs of size (1,m) Returns: y -- array of outputs of size (1,m) """ y = (w**2)*np.exp(w*x)/ (np.exp(w*x) + 1)**2 return y # + x = np.linspace(-10, 10, 100) w = -10 y = dd_c2(w, x) plt.plot(x, y) plt.show() # - # Second derivative is non-negative, this function should be convex.
exercises/exercise2/G11_exercise2_latex.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### M00 PhysComp – Intro to Physical Computing # #### Exercise: Processing NY Taxi Trip Data # **Date:** 01/04/2019 # <br/> # **Author:** Cisco • A C R O B O T I C 🦿 # <br/> # **Contact Info:** @[acrobotic](https://twitter.com/acrobotic) (Twitter) • <EMAIL> # <br/> # **Module Link:** [https://github.com/acrobotic/EduKits](https://github.com/acrobotic/EduKits) # <br/> # **Support:** [https://discord.gg/hbGxaa](https://discord.gg/hbGxaa) # <br/> # **Filename:** process_data_taxi.ipynb # <br/> # **Language:** Python 3 (Jupyter Notebook) # # ### Overview # # The goal of this exercise is to process and visualize online data from taxi cab trips in New York. # # ### List of Materials # # * Raspberry Pi # # ### Hardware Setup # # None. # # ### Software Setup # # Ensure you've followed the steps in `get_data_taxi.ipynb`. # * Include all the libraries we'll need for processing the data import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline # * Declare variables for storing the location (relative paths) of the files in the operating system data_filename = 'data/nyc_data.csv' fare_filename = 'data/nyc_fare.csv' # * Use pandas to read the csv data into variables data = pd.read_csv(data_filename, parse_dates=['pickup_datetime', 'dropoff_datetime']) fare = pd.read_csv(fare_filename, parse_dates=['pickup_datetime']) # * Use the dot notation to print out to an output cell the contents of the columns in the `data` object data.columns # * Assign specific data to variables for plotting, that is, the latitude and longitude of pickup locations p_lng = data.pickup_longitude p_lat = data.pickup_latitude # * Define a function for converting latitude and longitude values to `(x,y)` pixel coordinates for visualizing the data def lat_lng_to_pixels(lat, lng): lat_rad = lat * np.pi / 180.0 lat_rad = np.log(np.tan((lat_rad + np.pi / 2.0) / 2.0)) x = 100 * (lng + 180.0) / 360.0 y = 100 * (lat_rad - np.pi) / (2.0 * np.pi) return (x, y) px, py = lat_lng_to_pixels(p_lat, p_lng) # * Generate a scatter plot of the latitude and longitude data in `(x,y)` coordinate space plt.scatter(px, py) # * Resize the figure and configure it for better visualization plt.figure(figsize=(8, 6)) plt.scatter(px, py, s=.1, alpha=.03) plt.axis('equal') plt.xlim(29.40, 29.55) plt.ylim(-37.63, -37.54) plt.axis('off')
M00_PhysComp/04. Data Processing/exercises/process_data_taxi.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + topics = [(0, [('shahidul_alam',0.043), ('bangladeshi', 0.025), ('photographer',0.019), ('day', 0.019), ('release', 0.019), ('freeshahidul', 0.017), ('give', 0.017), ('shahidulalam', 0.015), ('arrest', 0.015), ('shahidul', 0.012)]), (1, [('bangladesh',0.285), ('wewantjustice', 0.175), ('roadsafety', 0.098), ('dhaka', 0.095), ('roadsafetybd', 0.039), ('rt', 0.023), ('savebangladesh', 0.017), ('child', 0.016), ('studentprotest', 0.011), ('action', 0.007)]), (2, [('cnn',0.139), ('bbc', 0.128), ('aljazeera', 0.098), ('bangladesh', 0.085), ('wewantjustice', 0.066), ('world', 0.027), ('citizen', 0.025), ('skynews_ccbm', 0.019), ('telegraph_thesun', 0.018), ('saferoadsforall', 0.017)]), (3, [('happen',0.091), ('spread', 0.07), ('people', 0.06), ('wewantjustice', 0.039), ('trend', 0.035), ('stop', 0.032), ('bangladesh', 0.032), ('hashtag', 0.028), ('pray', 0.025), ('awareness', 0.024)]), (4, [('government',0.084), ('medium', 0.083), ('news', 0.061), ('bangladesh', 0.038), ('international', 0.032), ('situation', 0.031), ('cover', 0.027), ('coverage', 0.022), ('internet', 0.018), ('world', 0.015)]), (5, [('student',0.131), ('rape', 0.1), ('kill', 0.099), ('road', 0.082), ('protest', 0.067), ('safety', 0.051), ('safe', 0.039), ('beat', 0.033), ('girl', 0.03), ('murder', 0.024)]), (6, [('youth',0.029), ('hope', 0.025), ('voice', 0.022), ('world', 0.022), ('make', 0.022), ('stand', 0.02), ('fight', 0.02), ('deserve', 0.018), ('time', 0.018), ('live', 0.018)]), (7, [('student',0.106), ('police', 0.063), ('protest', 0.063), ('attack', 0.063), ('government', 0.023), ('injure', 0.022), ('today', 0.018), ('peaceful', 0.016), ('university', 0.016), ('journalist', 0.015)]), (8, [('bangladesh',0.21), ('pic', 0.198), ('twitt', 0.192), ('wewantjustice', 0.146), ('bcl', 0.031), ('chhatra_league', 0.017), ('petition', 0.017), ('sign', 0.017), ('united_nation', 0.014), ('terrorist_organization', 0.014)]), (9, [('wewantjustice',0.15), ('bangladesh', 0.094), ('wedemandjustice', 0.055), ('por', 0.017), ('tag', 0.013), ('para', 0.012), ('esto', 0.01), ('army', 0.009), ('wewantjusitce', 0.007), ('isso', 0.007)]), (10, [('govt',0.089), ('demand', 0.078), ('violence', 0.056), ('people', 0.048), ('pic', 0.044), ('twitt', 0.043), ('student', 0.042), ('bnpjamaat', 0.041), ('road', 0.04), ('stophoax', 0.035)]), (11, [('student',0.095), ('country', 0.081), ('twitt', 0.074), ('pic', 0.072), ('safe', 0.06), ('back', 0.043), ('demand', 0.043), ('sheikhhasina', 0.04), ('road', 0.036), ('stophoax', 0.033)]), (12, [('bangladesh',0.308), ('wewantjustice', 0.268), ('wewantsaferoad', 0.083), ('justice', 0.069), ('wedemandjustice', 0.025), ('save', 0.022), ('sister', 0.01), ('brother', 0.01), ('bbcworld', 0.006), ('die', 0.005)]), (13, [('bangladesh',0.161), ('wewantjustice', 0.154), ('student', 0.118), ('movement', 0.069), ('support', 0.062), ('school', 0.036), ('saferoadsforall', 0.034), ('govt', 0.032), ('bnpjamaat', 0.019), ('agree', 0.018)]) ] # - from nltk.corpus import stopwords stop_words = stopwords.words('english') stop_words.extend(['from', 'subject', 're', 'edu', 'use', 'not', 'would', 'say', 'could', '_', 'be', 'know', 'good', 'go', 'get', 'do', 'done', 'try', 'many', 'some', 'nice', 'thank', 'think', 'see', 'rather', 'easy', 'easily', 'lot', 'lack', 'make', 'want', 'seem', 'run', 'need', 'even', 'right', 'line', 'even', 'also', 'may', 'take', 'come']) # + # 1. Wordcloud of Top N words in each topic from matplotlib import pyplot as plt from wordcloud import WordCloud, STOPWORDS import matplotlib.colors as mcolors cols = [color for name, color in mcolors.TABLEAU_COLORS.items()] # more colors: 'mcolors.XKCD_COLORS' cloud = WordCloud(stopwords=stop_words, background_color='white', width=2500, height=1800, max_words=10, colormap='tab10', color_func=lambda *args, **kwargs: cols[i], prefer_horizontal=1.0) fig, axes = plt.subplots(3, 3, figsize=(10,10), sharex=True, sharey=True) for i, ax in enumerate(axes.flatten()): fig.add_subplot(ax) topic_words = dict(topics[i][1]) cloud.generate_from_frequencies(topic_words, max_font_size=300) plt.gca().imshow(cloud) plt.gca().set_title('Topic ' + str(i), fontdict=dict(size=16)) plt.gca().axis('off') plt.subplots_adjust(wspace=0, hspace=0) plt.axis('off') plt.margins(x=0, y=0) plt.tight_layout() plt.show() # -
student1/word cloud.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Db2 Sample For H20 # # In this code sample, we will show how to use the Db2 Python driver to import data from our Db2 database. Then, we will use that data to create a machine learning model with H20. # # Many wine connoisseurs love to taste different wines from all over the world. Mostly importantly, they want to know how the quality differs between each wine based on the ingredients. Some of them also want to be able to predict the quality before even tasting it. In this notebook, we will be using a dataset that has collected certain attributes of many wine bottles that determines the quality of the wine. Using this dataset, we will help our wine connoisseurs predict the quality of wine. # # This notebook will demonstrate how to use Db2 as a data source for creating machine learning models. # # Prerequisites: # 1. Python 3.6 and above # 2. Db2 on Cloud instance (using free-tier option) # 3. Data already loaded in your Db2 instance # 4. Have Db2 connection credentials on hand # # We will be importing two libraries- `ibm_db` and `ibm_dbi`. `ibm_db` is a library with low-level functions that will directly connect to our db2 database. To make things easier for you, we will be using `ibm-dbi`, which communicates with `ibm-db` and gives us an easy interface to interact with our data and import our data as a pandas dataframe. # # For this example, we will be using the [winequality-red dataset](../data/winequality-red.csv), which we have loaded into our Db2 instance. # # NOTE: Running this notebook within a docker container. If `!easy_install ibm_db` doesn't work on your normally on jupter notebook, you may need to also run this notebook within a docker container as well. # ## 1. Import Data # Let's first install and import all the libraries needed for this notebook. Most important we will be installing and importing the db2 python driver `ibm_db`. # !pip install h2o # !easy_install ibm_db # + import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline # The two python ibm db2 drivers we need import ibm_db import ibm_db_dbi # + # replace only <> credentials dsn = "DRIVER={{IBM DB2 ODBC DRIVER}};" + \ "DATABASE=<DATABASE NAME>;" + \ "HOSTNAME=<HOSTNMAE>;" + \ "PORT=50000;" + \ "PROTOCOL=TCPIP;" + \ "UID=<USERNAME>;" + \ "PWD=<<PASSWORD>>;" hdbc = ibm_db.connect(dsn, "", "") hdbi = ibm_db_dbi.Connection(hdbc) sql = 'SELECT * FROM <SCHEMA NAME>.<TABLE NAME>' wine = pandas.read_sql(sql,hdbi) #wine = pd.read_csv('../data/winequality-red.csv', sep=';') # - # Let's see what our data looks like wine.head() # ## 2. Data Exploration # In this step, we are going to try and explore our data inorder to gain insight. We hope to be able to make some assumptions of our data before we start modeling. wine.describe() # + # Minimum price of the data minimum_price = np.amin(wine['quality']) # Maximum price of the data maximum_price = np.amax(wine['quality']) # Mean price of the data mean_price = np.mean(wine['quality']) # Median price of the data median_price = np.median(wine['quality']) # Standard deviation of prices of the data std_price = np.std(wine['quality']) # Show the calculated statistics print("Statistics for housing dataset:\n") print("Minimum quality: {}".format(minimum_price)) print("Maximum quality: {}".format(maximum_price)) print("Mean quality: {}".format(mean_price)) print("Median quality {}".format(median_price)) print("Standard deviation of quality: {}".format(std_price)) # - wine.corr() corr_matrix = wine.corr() corr_matrix["quality"].sort_values(ascending=False) # ## 3. Data Visualization wine.hist(bins=50, figsize=(30,25)) plt.show() boxplot = wine.boxplot(column=['quality']) # ## 4. Creating Machine Learning Model # # Now that we have cleaned and explored our data. We are ready to build our model that will predict the attribute `Class`. # + import h2o # Create an H2o session h2o.init() # - # Convert a Pandas Data Frame to H2o Frame wine_data = h2o.H2OFrame(wine) # Make sure the data is no corrupted during conversion wine_data.head(5) # + # Split the data into tran and test data wine_split = wine_data.split_frame(ratios = [0.8], seed = 1234) wine_train = wine_split[0] # using 80% for training wine_test = wine_split[1] #rest 20% for testing # Verify shape of data sets print(wine_train.shape, wine_test.shape) # + # We to define the predictors for this model predictors = list(wine_data.columns) # Since we need to predict quality, let's take that out predictors.remove('quality') predictors # + # Import the function for GLM from h2o.estimators.glm import H2OGeneralizedLinearEstimator # Set up GLM for regression glm = H2OGeneralizedLinearEstimator(family = 'gaussian', model_id = 'glm_default') # Use .train() to build the model glm.train(x = predictors, y = 'quality', training_frame = wine_train) print(glm) # - glm.model_performance(wine_test) predictions = glm.predict(wine_test) predictions.head(5) # ## 5. H2o Auto ML # In this section, I will walk through how to use H2o AutoML Module. # + from h2o.automl import H2OAutoML # Here AutoML will run for 20 base models for 100 seconds. aml = H2OAutoML(max_models = 20, max_runtime_secs=100, seed = 1) # - # Training our model aml.train(x=predictors, y='quality', training_frame=wine_train, validation_frame=wine_test) # + # Now let us look at the automl leaderboard. print(aml.leaderboard) #The leaderboard displays the top 10 models built by AutoML with their parameters. #The best model is placed on the top is a Stacked Ensemble.
notebooks/Db2 Sample For H2o.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + run_control={"frozen": false, "read_only": false} from jove.LangDef import * # - help(nthnumeric) nthnumeric(15) help(lstar) lstar({'a','b'},4)
notebooks/driver/Drive_LangDef.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6 # language: python # name: python36 # --- # Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License. # # AutoML 14: Explain classification model and visualize the explanation # # In this example we use the sklearn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use the AutoML Classifier for a simple classification problem. # # Make sure you have executed the [00.configuration](00.configuration.ipynb) before running this notebook. # # In this notebook you would see # 1. Creating an Experiment in an existing Workspace # 2. Instantiating AutoMLConfig # 3. Training the Model using local compute and explain the model # 4. Visualization model's feature importance in widget # 5. Explore best model's explanation # # ## Install AzureML Explainer SDK # !pip install azureml_sdk[explain] # ## Create Experiment # # As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments. # + import logging import os import random import pandas as pd import azureml.core from azureml.core.experiment import Experiment from azureml.core.workspace import Workspace from azureml.train.automl import AutoMLConfig from azureml.train.automl.run import AutoMLRun # + ws = Workspace.from_config() # choose a name for experiment experiment_name = 'automl-local-classification' # project folder project_folder = './sample_projects/automl-local-classification-model-explanation' experiment=Experiment(ws, experiment_name) output = {} output['SDK version'] = azureml.core.VERSION output['Subscription ID'] = ws.subscription_id output['Workspace Name'] = ws.name output['Resource Group'] = ws.resource_group output['Location'] = ws.location output['Project Directory'] = project_folder output['Experiment Name'] = experiment.name pd.set_option('display.max_colwidth', -1) pd.DataFrame(data = output, index = ['']).T # - # ## Diagnostics # # Opt-in diagnostics for better experience, quality, and security of future releases from azureml.telemetry import set_diagnostics_collection set_diagnostics_collection(send_diagnostics=True) # ## Load Iris Data Set # + from sklearn import datasets iris = datasets.load_iris() y = iris.target X = iris.data features = iris.feature_names from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=100, stratify=y) X_train = pd.DataFrame(X_train, columns=features) X_test = pd.DataFrame(X_test, columns=features) # - # ## Instantiate Auto ML Config # # Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment. # # |Property|Description| # |-|-| # |**task**|classification or regression| # |**primary_metric**|This is the metric that you want to optimize.<br> Classification supports the following primary metrics <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>balanced_accuracy</i><br><i>average_precision_score_weighted</i><br><i>precision_score_weighted</i>| # |**max_time_sec**|Time limit in minutes for each iterations| # |**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline| # |**X**|(sparse) array-like, shape = [n_samples, n_features]| # |**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]<br>Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers. | # |**X_valid**|(sparse) array-like, shape = [n_samples, n_features]| # |**y_valid**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]| # |**model_explainability**|Indicate to explain each trained pipeline or not | # |**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. | automl_config = AutoMLConfig(task = 'classification', debug_log = 'automl_errors.log', primary_metric = 'AUC_weighted', max_time_sec = 12000, iterations = 10, verbosity = logging.INFO, X = X_train, y = y_train, X_valid = X_test, y_valid = y_test, model_explainability=True, path=project_folder) # ## Training the Model # # You can call the submit method on the experiment object and pass the run configuration. For Local runs the execution is synchronous. Depending on the data and number of iterations this can run for while. # You will see the currently running iterations printing to the console. local_run = experiment.submit(automl_config, show_output=True) # ## Exploring the results # ### Widget for monitoring runs # # The widget will sit on "loading" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete. # # NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details. from azureml.widgets import RunDetails RunDetails(local_run).show() child_run = next(local_run.get_children()) RunDetails(child_run).show() # ### Retrieve the Best Model # # Below we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*. best_run, fitted_model = local_run.get_output() print(best_run) print(fitted_model) # ### Best Model 's explanation # # Retrieve the explanation from the best_run. And explanation information includes: # # 1. shap_values: The explanation information generated by shap lib # 2. expected_values: The expected value of the model applied to set of X_train data. # 3. overall_summary: The model level feature importance values sorted in descending order # 4. overall_imp: The feature names sorted in the same order as in overall_summary # 5. per_class_summary: The class level feature importance values sorted in descending order. Only available for the classification case # 6. per_class_imp: The feature names sorted in the same order as in per_class_summary. Only available for the classification case # + from azureml.train.automl.automlexplainer import retrieve_model_explanation shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \ retrieve_model_explanation(best_run) # - print(overall_summary) print(overall_imp) print(per_class_summary) print(per_class_imp) # Beside retrieve the existed model explanation information, explain the model with different train/test data # + from azureml.train.automl.automlexplainer import explain_model shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \ explain_model(fitted_model, X_train, X_test) # - print(overall_summary) print(overall_imp)
automl/14.auto-ml-model-explanation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Demo of ROCKET transform # # ## Overview # # ROCKET [1] transforms time series using random convolutional kernels (random length, weights, bias, dilation, and padding). ROCKET computes two features from the resulting feature maps: the max, and the proportion of positive values (or ppv). The transformed features are used to train a linear classifier. # # [1] <NAME>, <NAME>, <NAME> (2019) ROCKET: Exceptionally fast and accurate time series classification using random convolutional kernels. [arXiv:1910.13051](https://arxiv.org/abs/1910.13051) # # *** # # ## Contents # # 1. Imports # 2. Univariate Time Series # 3. Multivariate Time Series # 4. Pipeline Example # # *** # # ## 1 Imports # # Import example data, ROCKET, and a classifier (`RidgeClassifierCV` from scikit-learn), as well as NumPy and `make_pipeline` from scikit-learn. # # **Note**: ROCKET compiles (via Numba) on import, which may take a few seconds. # + # # !pip install --upgrade numba # - import numpy as np from sklearn.linear_model import RidgeClassifierCV from sklearn.pipeline import make_pipeline from sktime.datasets import load_arrow_head # univariate dataset from sktime.datasets.base import load_japanese_vowels # multivariate dataset from sktime.transformers.series_as_features.rocket import Rocket # ## 2 Univariate Time Series # # We can transform the data using ROCKET and separately fit a classifier, or we can use ROCKET together with a classifier in a pipeline (section 4, below). # # ### 2.1 Load the Training Data # For more details on the data set, see the [univariate time series classification notebook](https://github.com/alan-turing-institute/sktime/blob/master/examples/02_classification_univariate.ipynb). X_train, y_train = load_arrow_head(split="train", return_X_y=True) # ### 2.2 Initialise ROCKET and Transform the Training Data rocket = Rocket() # by default, ROCKET uses 10,000 kernels rocket.fit(X_train) X_train_transform = rocket.transform(X_train) # ### 2.3 Fit a Classifier # We recommend using `RidgeClassifierCV` from scikit-learn for smaller datasets (fewer than approx. 20K training examples), and using logistic regression trained using stochastic gradient descent for larger datasets. classifier = RidgeClassifierCV(alphas = np.logspace(-3, 3, 10), normalize = True) classifier.fit(X_train_transform, y_train) # ### 2.4 Load and Transform the Test Data X_test, y_test = load_arrow_head(split="test", return_X_y=True) X_test_transform = rocket.transform(X_test) # ### 2.5 Classify the Test Data classifier.score(X_test_transform, y_test) # *** # # ## 3 Multivariate Time Series # # We can use ROCKET in exactly the same way for multivariate time series. # # ### 3.1 Load the Training Data X_train, y_train = load_japanese_vowels(split="train", return_X_y=True) # ### 3.2 Initialise ROCKET and Transform the Training Data rocket = Rocket() rocket.fit(X_train) X_train_transform = rocket.transform(X_train) # ### 3.3 Fit a Classifier classifier = RidgeClassifierCV(alphas = np.logspace(-3, 3, 10), normalize = True) classifier.fit(X_train_transform, y_train) # ### 3.4 Load and Transform the Test Data X_test, y_test = load_japanese_vowels(split="test", return_X_y=True) X_test_transform = rocket.transform(X_test) # ### 3.5 Classify the Test Data classifier.score(X_test_transform, y_test) # *** # # ## 4 Pipeline Example # # We can use ROCKET together with `RidgeClassifierCV` (or another classifier) in a pipeline. We can then use the pipeline like a self-contained classifier, with a single call to `fit`, and without having to separately transform the data, etc. # # ### 4.1 Initialise the Pipeline rocket_pipeline = make_pipeline( Rocket(), RidgeClassifierCV(alphas=np.logspace(-3, 3, 10), normalize=True) ) # ### 4.2 Load and Fit the Training Data # + X_train, y_train = load_arrow_head(split="train", return_X_y=True) # it is necessary to pass y_train to the pipeline # y_train is not used for the transform, but it is used by the classifier rocket_pipeline.fit(X_train, y_train) # - # ### 4.3 Load and Classify the Test Data # + X_test, y_test = load_arrow_head(split="test", return_X_y=True) rocket_pipeline.score(X_test, y_test)
examples/rocket.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/algharak/BERTenhance/blob/master/experiments.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="hmA5LRGhBe00" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 289} outputId="7fccb532-c41d-4793-f294-75d00e8a7b06" # %matplotlib inline # !pip install mxnet import mxnet as mx from mxnet import gluon import numpy as np import pandas as pd import matplotlib.pyplot as plt import json import os from itertools import islice from pathlib import Path # + id="3l6YAbUgSIMA" colab_type="code" colab={} mx.random.seed(0) np.random.seed(0) # + id="DMWbJJOlSjLM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 513} outputId="a1d0cb68-4520-4839-d2a7-50fd8e8879e8" # !pip install gluonts # + id="URXuJgqhSRF6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="a1f3e0ca-eeab-4e25-ce14-42241f59b01a" from gluonts.dataset.repository.datasets import get_dataset, dataset_recipes from gluonts.dataset.util import to_pandas print(f"Available datasets: {list(dataset_recipes.keys())}") # + id="LKodXDuxS7Xb" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="78f505d6-19fb-4e93-e895-61a6b02f6d07" dataset = get_dataset("m4_monthly", regenerate=True) # + id="8Y7VaGiQBTDd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="27c919c4-0c5d-4e6b-8831-8b8a9d11ebd5" train_entry = next(iter(dataset.train)) #train_entry = next(iter(dataset.train)) aa = train_entry print (aa['item_id']) print(train_entry.keys()) # + id="Na8OqILHTHOe" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="26d6a048-a9eb-44c4-a480-ec2deee3e043" train_entry = next(iter(dataset.train)) test_entry = next(iter(dataset.test)) print(train_entry['target'].shape) print(test_entry['target'].shape) train_entry = next(iter(dataset.train)) test_entry = next(iter(dataset.test)) print(train_entry['target'].shape) print(test_entry['target'].shape) # + id="mNxPr62h6LL_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 71} outputId="7151d8f2-c02c-4475-c0b0-e072f1df40be" print (type(dataset.metadata)) print (dataset.metadata) # + id="b9KkjiwJR4_Q" colab_type="code" colab={} me=iter(dataset.train) j = 1 for i in me: mef = to_pandas(i) print (j) print (mef.shape) j +=1 print ('i am donr') # + id="UrQOJcmRUjkM" colab_type="code" colab={} fig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 7)) train_series.plot(ax=ax[0]) ax[0].grid(which="both") ax[0].legend(["train series"], loc="upper left") test_series.plot(ax=ax[1]) ax[1].axvline(train_series.index[-1], color='r') # end of train dataset ax[1].grid(which="both") ax[1].legend(["test series", "end of train series"], loc="upper left") plt.show() # + id="lr_1I3bK02qB" colab_type="code" colab={} from google.colab import files uploaded = files.upload() # + id="-cjffxYR3DoC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 215} outputId="997e0e59-5181-4e80-810e-443a6d06d4fd" import io import pandas as pd df2 = pd.read_csv(io.BytesIO(uploaded['Historical Product Demand.csv'])) df2.head # + id="FqjMDNH33ydN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 164} outputId="15896f69-fedb-41a7-d1ab-962c13f0dfc1" df2.shape # + id="k4C0zW1k9KAZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="20abe089-91d4-4b57-8d46-0ad6e5bbb36f" colnames = df2.columns.to_list() print(type(colnames)) for i in colnames: print (i) # + id="ljH5YD1g-e2Q" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="84684730-8e50-481b-a69e-2914bcd4e437" #print (pd.unique(df2['Product_Category'])) prod_categ = list(pd.unique(df2['Product_Category'])) print(type(prod_categ)) # + id="mK1F3lIIDWea" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="21f307e6-253f-4b5d-f244-f00e66481f40" start_date = df2['Date'].min() end_date = df2['Date'].max() print (start_date,end_date) # + id="vWoiIdUFL3yq" colab_type="code" colab={} idx = pd.date_range(start=start_date, end=end_date) # + id="Q4SRO7efOK8a" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="1b8252d6-1183-4448-bdb3-0b58d70bb6a4" dtdelta = end_date-start_date nrows = dtdelta.days print (type(nrows)) ncols = len (colnames) print(nrows,ncols) # + id="ZuhF3ZSZMGDA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 181} outputId="c57c2c41-e12f-40c3-8a5b-58029ee1d64a" dfnew = pd.DataFrame(np.zeros((nrows+1,ncols),dtype=int),index=idx, columns=colnames) dfnew.head # + id="NfRwBOqORj4T" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 232} outputId="42e7d434-6f5c-4196-aa0a-6cdd78ca739e" import datetime cat_idx = colnames.index('Product_Category') dt_idx = colnames.index('Date') value_idx = colnames.index('Order_Demand') print(col_idx) df2.info() df2['Date'] = df2['Date'].astype(str) nr = df2.shape[0] print(nr) inds = pd.isnull(df2).any(1) print('inds',inds) for n in range(10): act_date = datetime.datetime.strptime(df2.iloc[n,dt_idx], '%Y-%m-%d').date() act_cat = df2.iloc[n,cat_idx] act_value = int(df2.iloc[n,value_idx]) print (n) dfnew.loc[act_date,act_cat] += act_value #print (dfnew.loc[act_date,act_cat]) #print(act_value)
experiments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="a9d79da1-6001-4f97-8381-b11b5516e640" tags=[] # # **Welcome to MMTracking** # + [markdown] id="527a563a-c8b2-44f0-ae20-0d226ab1e547" # In this tutorial, you will learn to: # # + Install MMTracking. # # + Perform inference with pretrained weights in MMTracking. # # + Train a new MOT model with a toy dataset. # Let's start! # + [markdown] id="ab2c382c-a169-46fe-938f-c6687d763e8e" # ## **Install MMTracking** # + colab={"base_uri": "https://localhost:8080/"} id="f8ced8f4-b07b-4216-8953-f7af6928b77c" outputId="6b5af5d7-5b52-4804-aae5-6edebf920816" # Check nvcc version # !nvcc -V # Check GCC version # !gcc --version # + colab={"base_uri": "https://localhost:8080/"} id="6b4f093f-e197-42bd-ba64-dc905e379382" outputId="cb4c26d9-d955-4a13-e789-814dbbd8847e" # install MMCV # !pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.10.0/index.html # install MMDetection # !pip install mmdet # clone the MMTracking repository # !git clone https://github.com/open-mmlab/mmtracking.git # %cd mmtracking # install MMTracking and its dependencies # !pip install -r requirements/build.txt # !pip install -e . # used to MOT evaluation # !pip install git+https://github.com/JonathonLuiten/TrackEval.git # + colab={"base_uri": "https://localhost:8080/"} id="03a4a583-78e7-40a1-a6ef-d80056989546" outputId="e183515f-9615-41e2-b405-70f4c0d8465d" from mmcv import collect_env collect_env() # + colab={"base_uri": "https://localhost:8080/"} id="ff6aea79-2ce9-4b1c-b3c4-3f92d1a4e34c" outputId="1494d3f0-ebba-4aa4-e1dc-575615fb3794" # Check Pytorch installation import torch, torchvision print(torch.__version__, torch.cuda.is_available()) # Check mmcv installation from mmcv.ops import get_compiling_cuda_version, get_compiler_version print(get_compiling_cuda_version()) print(get_compiler_version()) # Check MMDetection installation import mmdet print(mmdet.__version__) # Check MMTracking installation import mmtrack print(mmtrack.__version__) # + [markdown] id="4d43b49c-320a-4b0f-baca-fb4bde0630ff" tags=[] # ## **Perform inference** # + colab={"base_uri": "https://localhost:8080/"} id="dd7c8466-f057-455f-985a-71e5f22c36e4" outputId="a9866284-1762-4852-b5f7-194737289ed8" # unset the proxy for downloading the pretrained models (optional) # !unset https_proxy # !unset http_proxy # download checkpoints # !mkdir checkpoints # !wget -c https://download.openmmlab.com/mmtracking/vid/selsa/selsa_faster_rcnn_r50_dc5_1x_imagenetvid/selsa_faster_rcnn_r50_dc5_1x_imagenetvid_20201227_204835-2f5a4952.pth -P ./checkpoints # !wget -c https://download.openmmlab.com/mmtracking/sot/siamese_rpn/siamese_rpn_r50_1x_lasot/siamese_rpn_r50_1x_lasot_20211203_151612-da4b3c66.pth -P ./checkpoints # !wget -c https://download.openmmlab.com/mmtracking/vis/masktrack_rcnn/masktrack_rcnn_r50_fpn_12e_youtubevis2019/masktrack_rcnn_r50_fpn_12e_youtubevis2019_20211022_194830-6ca6b91e.pth -P ./checkpoints # + colab={"base_uri": "https://localhost:8080/", "height": 418, "referenced_widgets": ["c2cdc25a1b9644b0ac9a45a5e5609314", "7aacc564ceed400582af233b42822f7d", "89b71747f37a4213be4750c562a7ccd9", "7da6f24364594f56a573d31665913645", "<KEY>", "36dd9bf50205454493fc50a1cef64d23", "8ea164a027b044278794e87a396a548a", "bc127741c92f4b65ada91a4c4890ec87", "f140214cae9c45f39c0ca28d856fe596", "12bedcdf97a94489a2356e89d393d107", "3d277b18e9d2486492614f9093bf19a4", "0ce49a6424414d268a0224b7e57739b6", "<KEY>", "<KEY>", "c2d658f5adc3416e9be42fa615e2061d", "cbddeebf0f8f464ca15e5899a8cee2a7", "68c48555d8dd49f49e26956904746e60", "758197b8b211425f864204242e518fed", "<KEY>", "<KEY>", "<KEY>", "ab7f46e98c794292893599541f343047"]} id="420dae4b-4426-405e-97fb-7823943b8ee8" outputId="ce13d7f0-b5c5-4aea-af61-d3ee93291f02" # run mot demo import mmcv import tempfile from mmtrack.apis import inference_mot, init_model mot_config = './configs/mot/deepsort/deepsort_faster-rcnn_fpn_4e_mot17-private-half.py' input_video = './demo/demo.mp4' imgs = mmcv.VideoReader(input_video) # build the model from a config file mot_model = init_model(mot_config, device='cuda:0') prog_bar = mmcv.ProgressBar(len(imgs)) out_dir = tempfile.TemporaryDirectory() out_path = out_dir.name # test and show/save the images for i, img in enumerate(imgs): result = inference_mot(mot_model, img, frame_id=i) mot_model.show_result( img, result, show=False, wait_time=int(1000. / imgs.fps), out_file=f'{out_path}/{i:06d}.jpg') prog_bar.update() output = './demo/mot.mp4' print(f'\n making the output video at {output} with a FPS of {imgs.fps}') mmcv.frames2video(out_path, output, fps=imgs.fps, fourcc='mp4v') out_dir.cleanup() # + colab={"base_uri": "https://localhost:8080/", "height": 386, "referenced_widgets": ["d189fcaddeff41fcb9cd7b27969d53de", "f507f59b242a4a5ebb204c4bb84a8241", "939e2242b3eb4388aa4e30ebccd020cc", "15eafa933541440d822371cc6afce196", "4ea1a24a8ffc4269b46dc1dc7539a0f3", "a1106afabced4d418406b7bbb4f826cc", "9a95f05e979e4a9bbad4675883350b1d", "2bb53ac1784d421ca2050b5aa6701a0d", "82f81af913424d3c96ba2cb8d905258a", "3187d7f735ab45cfad16f5bb3471dc0b", "24da18975ff0468a9bc0c294c45b8a16"]} id="d4a97033-b779-4169-84c9-781c58840ae5" outputId="a44ea1ef-bd8a-48c5-e297-97df926fb729" # run vis demo from mmtrack.apis import inference_mot vis_config = './configs/vis/masktrack_rcnn/masktrack_rcnn_r50_fpn_12e_youtubevis2019.py' vis_checkpoint = './checkpoints/masktrack_rcnn_r50_fpn_12e_youtubevis2019_20211022_194830-6ca6b91e.pth' # build the model from a config file and a checkpoint file vis_model = init_model(vis_config, vis_checkpoint, device='cuda:0') imgs = mmcv.VideoReader(input_video) prog_bar = mmcv.ProgressBar(len(imgs)) out_dir = tempfile.TemporaryDirectory() out_path = out_dir.name for i, img in enumerate(imgs): result = inference_mot(vis_model, img, frame_id=i) vis_model.show_result( img, result, wait_time=int(1000. / imgs.fps), out_file=f'{out_path}/{i:06d}.jpg') prog_bar.update() output = './demo/vis.mp4' print(f'\n making the output video at {output} with a FPS of {imgs.fps}') mmcv.frames2video(out_path, output, fps=imgs.fps, fourcc='mp4v') out_dir.cleanup() # + colab={"base_uri": "https://localhost:8080/", "height": 406, "referenced_widgets": ["091f72866bc64f8bba239684fe9ddeb6", "c20f8918d08d4e07a544ac69541038fd", "be103dd0cc5543be9dea3dd8c7890187", "5be59a3bfc0148478a662f436e1677a8", "4c616e4740f24416bbea27ba49709d50", "6ad0273eb02440109ba7c2cde43739f9", "5f08eb6751fc4438a5de45051218530f", "57bc05e1d2b64e899fd524c13cd47f5a", "9244d2f08f8c4e2a80e4f2f4921f1b0b", "01fa8d3fb39b483195f7cfc293c6b3ba", "ac746c3a37c145c0bc0d40fa7cabfd2d"]} id="abd0863b-933c-42d1-8442-70565d1b4b55" outputId="62ea5c55-2b21-43de-97a6-922afac8bbbb" # run vid demo from mmtrack.apis import inference_vid vid_config = './configs/vid/selsa/selsa_faster_rcnn_r50_dc5_1x_imagenetvid.py' vid_checkpoint = './checkpoints/selsa_faster_rcnn_r50_dc5_1x_imagenetvid_20201227_204835-2f5a4952.pth' # build the model from a config file and a checkpoint file vid_model = init_model(vid_config, vid_checkpoint, device='cuda:0') imgs = mmcv.VideoReader(input_video) prog_bar = mmcv.ProgressBar(len(imgs)) out_dir = tempfile.TemporaryDirectory() out_path = out_dir.name for i, img in enumerate(imgs): result = inference_vid(vid_model, img, frame_id=i) vid_model.show_result( img, result, wait_time=int(1000. / imgs.fps), out_file=f'{out_path}/{i:06d}.jpg') prog_bar.update() output = './demo/vid.mp4' print(f'\n making the output video at {output} with a FPS of {imgs.fps}') mmcv.frames2video(out_path, output, fps=imgs.fps, fourcc='mp4v') out_dir.cleanup() # + colab={"base_uri": "https://localhost:8080/", "height": 227, "referenced_widgets": ["321a9bbadb4b4167ac37f84320bdf76f", "f69886a5f4984ee09804aaa411660955", "fc977a68f1494ad68c203f5544ce1521", "995bca8653914372874f8861a38f0185", "<KEY>", "<KEY>", "ddfcad5fc8854b5cbe0fe8840013ffe5", "e8b957c1eadc45ba9f7092df0d080f08", "<KEY>", "535faa89033349c08b3bd31ff5be0018", "5c2860d7559940a7be431ab1228bbe6f"]} id="0189f86a-b216-4f63-a58a-97e40e326869" outputId="a8fccd93-2171-4110-d971-4b6277dfc3c2" # run sot demo from mmtrack.apis import inference_sot sot_config = './configs/sot/siamese_rpn/siamese_rpn_r50_20e_lasot.py' sot_checkpoint = './checkpoints/siamese_rpn_r50_1x_lasot_20211203_151612-da4b3c66.pth' # build the model from a config file and a checkpoint file sot_model = init_model(sot_config, sot_checkpoint, device='cuda:0') init_bbox = [371, 411, 450, 646] imgs = mmcv.VideoReader(input_video) prog_bar = mmcv.ProgressBar(len(imgs)) out_dir = tempfile.TemporaryDirectory() out_path = out_dir.name for i, img in enumerate(imgs): result = inference_sot(sot_model, img, init_bbox, frame_id=i) sot_model.show_result( img, result, wait_time=int(1000. / imgs.fps), out_file=f'{out_path}/{i:06d}.jpg') prog_bar.update() output = './demo/sot.mp4' print(f'\n making the output video at {output} with a FPS of {imgs.fps}') mmcv.frames2video(out_path, output, fps=imgs.fps, fourcc='mp4v') out_dir.cleanup() # + [markdown] id="500ff07b-9664-4429-9e3f-e97dd4fa1c29" tags=[] # ## **Train a MOT model with a toy dataset** # + [markdown] id="e7bd4f44-447a-49a5-8c9c-cf160691bda5" tags=[] # ### **Prepare dataset** # + colab={"base_uri": "https://localhost:8080/"} id="a91a55bd-14be-46bf-aa18-5e30d9abe5b7" outputId="6c21c659-20e9-464d-c576-fcf2d726865d" # !mkdir data # !wget https://download.openmmlab.com/mmtracking/data/MOT17_tiny.zip -P ./data # !unzip -q ./data/MOT17_tiny.zip -d ./data # + colab={"base_uri": "https://localhost:8080/"} id="d0db0d5f-b192-48ee-b145-149f33ad3685" outputId="27bef171-e8f0-4c97-d70d-b5a7e370cd61" # convert the dataset to coco format # !python ./tools/convert_datasets/mot/mot2coco.py -i ./data/MOT17_tiny/ -o ./data/MOT17_tiny/annotations --split-train --convert-det # crop pedestrian patches from the original dataset for training reid model. It may take a few minutes. # !rm -rf ./data/MOT17_tiny/reid # !python ./tools/convert_datasets/mot/mot2reid.py -i ./data/MOT17_tiny/ -o ./data/MOT17_tiny/reid --val-split 0.9 --vis-threshold 0.8 # + [markdown] id="ae887970-7382-4bd0-a739-6b07e6dded6f" tags=[] # ### **Train a detector for MOT** # + colab={"base_uri": "https://localhost:8080/"} id="bce04095-8586-45c5-a556-40c51d08b2cb" outputId="05f85750-c853-4887-c8e4-306401b866c3" import mmcv from mmdet.apis import set_random_seed cfg = mmcv.Config.fromfile('./configs/det/faster-rcnn_r50_fpn_4e_mot17-half.py') cfg.data_root = 'data/MOT17_tiny/' cfg.data.test.ann_file = cfg.data.test.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.ann_file = cfg.data.train.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.val.ann_file = cfg.data.val.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.test.img_prefix = cfg.data.test.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.img_prefix = cfg.data.train.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.val.img_prefix = cfg.data.val.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.work_dir = './tutorial_exps/detector' cfg.seed = 0 set_random_seed(0, deterministic=False) cfg.gpu_ids = range(1) print(f'Config:\n{cfg.pretty_text}') # + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["7f20458c3bf7422fba34beba519c27bd", "9e5d67b0f3fb4baaa7254a102464057b", "f750ac53345746ee8c0364b5f850a56d", "3ed731e3194e4465aa7b79579f8eaaca", "7a4444bb015249ae9caa2b14c21fa0fd", "9718af278d2d45e99d1355cafc2c7518", "cb11dac7ded84ad59f12a03b04660b3c", "f2613e8b5e1e453db11090a1aa888799", "<KEY>", "750088e53a064a13872ed5fa5616face", "eb8e5c96ffea40e298a38db2b5a38ace"]} id="889b4255-50be-4da3-85c4-dcd19c8111ac" outputId="bcc096ba-5ce0-4eb3-ab81-776d54424104" import os.path as osp from mmtrack.datasets import build_dataset from mmdet.apis import train_detector as train_model from mmdet.models import build_detector as build_model mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) model = build_model(cfg.model.detector) model.init_weights() datasets = [build_dataset(cfg.data.train)] model.CLASSES = datasets[0].CLASSES train_model(model, datasets, cfg) # + [markdown] id="7f747c1f-7944-49f2-b9fc-a51dc3f85857" tags=[] # ### **Train a ReID model for MOT** # + colab={"base_uri": "https://localhost:8080/"} id="6705deeb-a9d7-42e2-9d52-b51b7b588d1f" outputId="b3b974a6-9bfa-4c04-c568-aab06c6828d4" import mmcv from mmdet.apis import set_random_seed cfg = mmcv.Config.fromfile('./configs/reid/resnet50_b32x8_MOT17.py') cfg.data_root = 'data/MOT17_tiny/' cfg.data.test.ann_file = cfg.data.test.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.ann_file = 'data/MOT17_tiny/reid/meta/train_9.txt' cfg.data.val.ann_file = cfg.data.val.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.test.data_prefix = cfg.data.test.data_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.data_prefix = cfg.data.train.data_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.val.data_prefix = cfg.data.val.data_prefix.replace('data/MOT17/','data/MOT17_tiny/') # learning policy cfg.lr_config = dict( policy='step', warmup='linear', warmup_iters=200, warmup_ratio=1.0 / 200, step=[1]) cfg.total_epochs = 2 cfg.work_dir = './tutorial_exps/reid' cfg.seed = 0 set_random_seed(0, deterministic=False) cfg.gpu_ids = range(1) print(f'Config:\n{cfg.pretty_text}') # + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["1fc5eb2eaa6a4ed88a005a081bc24a70", "1f5d5858bede4242b51d1cb635c3f610", "9344070d5d004c0fb5c0bdf22632e343", "<KEY>", "<KEY>", "<KEY>", "6b83dd17433745a3ae3d2ef9b4b932ad", "<KEY>", "9604ece7c2bb4e8ba8914d4430a72876", "7d5fd07e913046a6b5445a791197a287", "<KEY>"]} id="12f2b54e-7e5f-4d95-9e27-528115717e03" outputId="b3a6f9b1-5095-4b6f-82de-4c9f81e15e80" from mmtrack.datasets import build_dataset from mmdet.apis import train_detector as train_model from mmtrack.models import build_reid as build_model model = build_model(cfg.model.reid) model.init_weights() datasets = [build_dataset(cfg.data.train)] model.CLASSES = datasets[0].CLASSES train_model(model, datasets, cfg) # + [markdown] id="e5ac4b40-7023-498a-9ddf-bc06ff2100af" tags=[] # ### **Test the DeepSORT model** # + colab={"base_uri": "https://localhost:8080/"} id="c837c657-cc81-426d-8060-ad19f5494461" outputId="d33fa793-8dc1-4186-dac0-49d97355c69a" import mmcv from mmdet.apis import set_random_seed cfg = mmcv.Config.fromfile('./configs/mot/deepsort/deepsort_faster-rcnn_fpn_4e_mot17-private-half.py') cfg.data_root = 'data/MOT17_tiny/' cfg.data.test.ann_file = cfg.data.test.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.ann_file = cfg.data.test.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.val.ann_file = cfg.data.val.ann_file.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.test.img_prefix = cfg.data.test.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.train.img_prefix = cfg.data.train.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.data.val.img_prefix = cfg.data.val.img_prefix.replace('data/MOT17/','data/MOT17_tiny/') cfg.model.detector.init_cfg.checkpoint = './tutorial_exps/detector/epoch_4.pth' cfg.model.reid.init_cfg.checkpoint = './tutorial_exps/reid/epoch_2.pth' cfg.work_dir = './tutorial_exps' cfg.seed = 0 set_random_seed(0, deterministic=False) cfg.gpu_ids = range(1) cfg.data.test.test_mode = True print(f'Config:\n{cfg.pretty_text}') # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="29c9f531-3ea9-42d3-9fb3-bcdd13594406" outputId="7c5837e7-78bb-41c7-f0c7-e4dadada5a6c" from mmtrack.datasets import build_dataloader from mmtrack.apis import init_model from mmcv.parallel import MMDataParallel from mmtrack.apis import single_gpu_test from mmtrack.datasets import build_dataset dataset = build_dataset(cfg.data.test) data_loader = build_dataloader( dataset, samples_per_gpu=1, workers_per_gpu=cfg.data.workers_per_gpu, dist=False, shuffle=False) # build the model and load checkpoint model = init_model(cfg) model = MMDataParallel(model, device_ids=cfg.gpu_ids) outputs = single_gpu_test(model, data_loader) eval_kwargs = cfg.get('evaluation', {}).copy() # hard-code way to remove EvalHook args eval_hook_args = [ 'interval', 'tmpdir', 'start', 'gpu_collect', 'save_best', 'rule', 'by_epoch' ] for key in eval_hook_args: eval_kwargs.pop(key, None) eval_kwargs.update(dict(metric=['track'])) metric = dataset.evaluate(outputs, **eval_kwargs) print(metric)
demo/MMTracking_Tutorial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: SageMath # language: '' # name: sagemath # --- # # 向量與物件(Vectors and Objects) # ![Creative Commons License](https://i.creativecommons.org/l/by/4.0/88x31.png) # # This work by <NAME> is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/). # _Tested on SageMath version 8.7_ # ## 向量 # ### 二維向量 # 一個向量記錄了方向以及距離 # 它是一個把物體移動的過程 # # 在二維平面中 # $(a,b)$ 可以代表一個點 # 也可以代表一個向量 # 這個向量可以把物體從 $(0,0)$ 移動到 $(a,b)$ # 所以這向量的長度(或是距離)為 $a^2+b^2$ # 在 Sage 裡 # 可以用 `vector([a,b])` 來建造一個向量 $(a,b)$ v1 = vector([2,3]) # 函數 `f` 的 `f.plot()` 會把函數繪製出來 # 向量 `v` 的 `v.plot()` 同樣會把向量繪製出來 # # 不同類型的物件會畫出不同東西 v1.plot() # 我們只在意向量的方向及距離 # 並不在意它的起始點在哪邊 # # 所以下方的藍向量與紅向量是被視為一樣的 # 可以用 `start` 參數 # 來調整繪製時的起始點 v1 = vector([2,3]) pic1 = v1.plot(color='blue') pic2 = v1.plot(start=(2,0), color='red') pic1 + pic2 # 向量有**向量加法**: # 向量加向量就是把各項相加 # $(a,b)+(c,d)=(a+c,b+d)$ v1 = vector([2,3]) v2 = vector([-1,-1]) v3 = v1 + v2 v3 # 意思是 # 把一點從原點用 $(a,b)$ 向量移動 # 再用 $(c,d)$ 向量移動 # # 相當於直接用 $(a+c,b+d)$ 來移動 v1 = vector([2,3]) v2 = vector([-1,-1]) v3 = v1 + v2 pic1 = v1.plot(color='blue') pic2 = v2.plot(color='orange', start=v1) pic3 = v3.plot(color='red') pic1 + pic2 + pic3 # 向量有**純量乘法**: # 純量和向量相乘就是把純量乘進每一項 # $k\times (a,b)=(ka,kb)$ v1 = vector([2,3]) 3 * v1 # 意思就是將這個向量伸縮 $k$ 倍 v1 = vector([2,3]) v2 = 3 * v1 pic1 = v1.plot() pic2 = v1.plot(start=v1) pic3 = v1.plot(start=v1+v1) pic4 = v2.plot(start=(0.05,0),color='red') pic1 + pic2 + pic3 + pic4 # 向量和向量之間可以做**內積**(dot product) # 得到一個純量 # $(a,b)\cdot (c,d) = ac+bd$ v1 = vector([2,3]) v2 = vector([-1,-1]) v1 * v2 # ### 高維度向量 # 一個 $n$ 個數字的數對 # $(a_1, \ldots, a_n)$ # 叫作一個 **$n$ 維向量** v1 = vector([1,2,3,4,5]) # 如同二維向量一般 # 兩個高維度的向量可以**相加** # $(a_1, \ldots, a_n) + (b_1, \ldots, b_n) = (a_1+b_1, \ldots, a_n+b_n)$ v1 = vector([1,2,3,4,5]) v2 = vector([5,4,3,2,1]) v1 + v2 # 純量和向量可以做**純量乘法** # $k\times (a_1, \ldots, a_n)=(ka_1, \ldots, ka_n)$ v1 = vector([1,2,3,4,5]) 3 * v1 # 向量和向量可以做**內積** # 得到一個純量 # $(a_1, \ldots, a_n)\cdot (b_1, \ldots, b_n) = a_1b_1 + \cdots + a_nb_n$ v1 = vector([1,2,3,4,5]) v2 = vector([5,4,3,2,1]) v1 * v2 # ## Python 中的物件 # 在 Python 裡 # 我們可以創造出全新的東西 # 然後定義它的許多性質及相關函數 # 甚至定義它們的加法 # 如何比大小 # 如何顯示出來 # # 因為它是一個幾乎沒有侷限的東西 # 所以我們叫它作**物件** # ### 類別 # Python 裡的物件有各自的**資料結構**(type) # 或是它屬於某一個**類別**(class) type(1) type(1.5) type(x) type(range) type(matrix([[1]])) type(QQ) type(exp) # 物件可以是一個類別裡的**實例**(instance) # 可以用 `isinstance` 來判斷一個物件屬不屬於某一類別 isinstance(1,Integer) isinstance(1,int) isinstance(x,Expression) # ### 自行定義一個類別 # 接下來 # 我們試著在 Sage 中 # 定義一個新的類別叫作 `fraction` # 來實現數學中的分數 # `class fraction` # 定義了類別的名稱 # # `__init__` # 定義了如何創造一個新物件 # # 一個分數其實只須要兩個輸入的值: # 分子(numerator)和分母(denominator) # 每個物件都可以設定許多**屬性**(attribute) # 像這裡我們設定了 `numerator`、`denominator`、以及 `gcd` # # 當 `q` 是一個物件 # `gcd` 是它的屬性 # 可以用 `q.gcd` 叫出這個屬性的值 # + class fraction: def __init__(self,a,b): self.numerator = a self.denominator = b self.gcd = gcd(a,b) q = fraction(4,6) q.gcd # - # 每個物件也可以定義其相關的函數 # 叫作**運算**(method) # # 這裡我們定義一個新的運算 # 計算分數的倒數(reciprocal) # + class fraction: def __init__(self,a,b): self.numerator = a self.denominator = b self.gcd = gcd(a,b) def reciprocal(self): return fraction(self.denominator,self.numerator) q = fraction(2,3) print('q') print(q.numerator) print(q.denominator) print('---') p = q.reciprocal(); print('1/q') print(p.numerator) print(p.denominator) # - # 運算是函數 # 所以最後要用 `()` 收尾 # 或是放入一些須要的參數 # # 屬性只是一個值 # 所以不用用 `()` 收尾 q.numerator() q.reciprocal # 這邊附帶提一下 # `_` 並不是什麼特殊的字元 # 它可以拿來當變數的名字 for _ in range(10): print(_) # Python 中的類別人有許多特殊的運算(special method) # 像是 `__init__`、`__repr__`、`__add__`、以及 `__contain__` # # `__repr__` 告訴 Python # 如何把這個物件 `print` 出來 # (賦予 `print` 的意義) # + class fraction: def __init__(self,a,b): self.numerator = a self.denominator = b self.gcd = gcd(a,b) def reciprocal(self): return fraction(self.denominator,self.numerator) def __repr__(self): return "{} / {}".format(self.numerator,self.denominator) q = fraction(2,3) print(q) # - # `__add__` 告訴 Python # 如何將兩個物件相加 # (賦予 `+` 的意義) # # 類似的還有: # `__sub__` 定義了減法 `-` # `__mul__` 定義了乘法 `*` # `__div__` 定義了除法 `/` # + class fraction: def __init__(self,a,b): self.numerator = a self.denominator = b self.gcd = gcd(a,b) def reciprocal(self): return fraction(self.denominator,self.numerator) def __repr__(self): return "{} / {}".format(self.numerator,self.denominator) def __add__(self,other): a,b = self.numerator,self.denominator c,d = other.numerator,other.denominator return fraction( a*d + b*c, b*d ) q = fraction(2,3) p = fraction(2,5) print(p, '+', q, '=' , p+q) # - # `__eq__` 告訴 Python # 如何判斷兩個物件是否一樣 # (賦予 `==` 意義) # # 類似的還有 # `__ne__` 定義了不等於 `!=` # + class fraction: def __init__(self,a,b): self.numerator = a self.denominator = b self.gcd = gcd(a,b) def reciprocal(self): return fraction(self.denominator,self.numerator) def __repr__(self): return "{} / {}".format(self.numerator,self.denominator) def __add__(self,other): a,b = self.numerator,self.denominator c,d = other.numerator,other.denominator return fraction( a*d + b*c, b*d) def __eq__(self,other): a,b = self.numerator,self.denominator c,d = other.numerator,other.denominator return a*d == b*c q = fraction(2,3) print(q) p = fraction(4,6) print(p) print(p == q) # - # 最後 # 我們可以用 `dir` # 來查找所有的屬性及運算 dir(q) # 或是用 `vars` 來列出所有的屬性 vars(q) # 這樣我們的 `fraction` 已經很完整了 # # 然而我們可以留心一些小細節 # 讓它更臻完美 # 比如說加入一些偵錯的機制 # # 若是分母可以為 0 # 程式不見得會出錯 # 然後結果不見得是我們要的 q = fraction(2,0) print(q) p = fraction(3,0) print(p) print(p == q) # 所以可以用 `raise Error` 來偵錯 # # 不同的 `Error` 形式 # 可以在 [Python 說明書](https://docs.python.org/3/library/exceptions.html)中找到 # + class fraction: def __init__(self,a,b): if b == 0: raise ValueError, "The divisor cannot be zero." self.numerator = a self.denominator = b self.gcd = gcd(a,b) def reciprocal(self): return fraction(self.denominator,self.numerator) def __repr__(self): return "{} / {}".format(self.numerator,self.denominator) def __add__(self,other): a,b = self.numerator,self.denominator c,d = other.numerator,other.denominator return fraction( a*d + b*c, b*d) def __eq__(self,other): a,b = self.numerator,self.denominator c,d = other.numerator,other.denominator return a*d == b*c q = fraction(2,0) print(q) # - # ## 動手試試看 # ##### 練習 1 # 若 $v_1 = (3,5)$ 且 $v_2 = (-2,-4)$。 # 計算 $10 v_1 + 5 v_2$。 # + ### your answer here # - # ##### 練習 2 # 若 $v_1 = (3,5)$ 且 $v_2 = (-2,-4)$。 # 計算 $(10 v_1)\cdot(5 v_2)$。 # + ### your answer here # - # ##### 練習 3 # # 令 $a=1$, $b=2$, $c=3$, $d=4$ # 定義一個函數 `linear_transformation(v)` # 使得輸入向量 $v=(x,y)$ 時 # 輸出為向量 $(ax+by, cx+dy)$ # + ### your answer here # - # ##### 練習 4 # 若 $v_1 = (1,1)$ , $v_2 = (-1,1)$ # 且 $v_1' = (2,-1)$ , $v_2' = (1,2)$ # # 找出 $a,b,c,d$ 使得上一題中的`linear_transformation` # 符合以下性質: # 若 $(x,y) = v_1$,則回傳值為 $(x',y') = v_1'$ # 若 $(x,y) = v_2$,則回傳值為 $(x',y') = v_2'$ # + ### your answer here # - # ##### 練習 5 # # 如果我們有兩個向量,那麼我們就可以計算這兩個向量所張出的平行四邊形的面積 # 例如 $v_1 = (1,0)$ , $v_2 = (0,1)$ # 則此兩向量所張出的平行四邊形 $ABCD$ 為 $A(0,0),B(1,0),C(1,1),D(1,0)$ # 且此平行四邊形的面積為 $1$ # 有一個快速計算面積的方法 # 若 $v_1 = (x_1,y_1)$ 且 $v_2 = (x_2,y_2)$ # 那麼 $v_1$ 和 $v_2$ 所張出的平行四邊形的面積就是 $|x_1y_2 - y_1x_2|$ # # 定義一個函數 `area` 其功能為: # 輸入兩個二維空間中向量 `v1` , `v2` # 回傳 `v1` 和 `v2` 所張出的平行四邊形的面積 # + ### your answer here # - # ##### 練習 6 # Python 在定義類別的時候還有許多特殊運算: # `__le__` 定義小於等於 `<=`、 # `__lt__` 定義小於 `<`、 # `__ge__` 定義大於等於 `>=`、 # `__gt__` 定義大於 `>`。 # # 將這些特殊運算補到我們先前所定義的 `fraction` 之中。 # + ### your answer here # - # ##### 練習 7 # # 定義一個新的類別 `clock_time`: # 輸入時可以放入一個整數 `n`, # `print` 的時候會印出 1 到 12 中 # 和 `n` 差 12 的倍數的那個數字。 # 並定義其加法為 # `clock_time(a) + clock_time(b) = clock_time(a+b)`。 # # 七點鐘再過八個小時會是幾點鐘? # + ### your answer here # - # ##### 練習 8 # # 定義一個函數`change_length`其功能為: # 輸入一個向量`v` # 並回傳一個方向與`v` 相同且長度為`1` ### your answer here def change_length(v): # ##### 練習 9 # 定義一個類別`calories_game:` # 輸入時可以放入兩個列表 `L1` 及 `L2` # 其中 `L1` 代表一個隊伍中每人的跑步時間(小時) # `L2` 代表一個隊伍中每人的散步時間(小時) # 已知慢跑一小時可消耗__400大卡__,散步一小時可消耗**150大卡**。 # 並在類別中定義一個整數 `cal` 儲存所有人的總卡路里消耗量,且 `print` 時印出總卡路里消耗量。 # # 定義以 `cal` 來比較兩個類別之間的 `<`, `>`,`==` # + ### your answer here # - # ##### 練習 10 # # 給定三組隊伍的每人各自跑步,散步時間(小時) # # A隊: # 慢跑:`[0, 8, 1, 0, 7, 9, 10, 0, 1, 5, 4, 9, 10, 4, 6]` # 散步:`[6, 6, 5, 3, 7, 8, 10, 1, 8, 2, 6, 5, 9, 5, 7]` # # B隊: # 慢跑:`[1, 2, 0, 3, 4, 9, 10, 2, 7, 10, 0, 1, 4, 3, 8]` # 散步:`[8, 7, 2, 1, 0, 10, 4, 1, 2, 3, 3, 10, 4, 7, 7]` # # C隊: # 慢跑:`[7, 7, 5, 6, 0, 10, 8, 10, 4, 1, 8, 6, 6, 1, 2]` # 散步:`[5, 9, 10, 2, 9, 1, 7, 1, 0, 9, 3, 1, 5, 6, 9]` # # 請使用上面製作的類別比較三隊的總卡路里消耗量。 # + ### your answer here
Sage4HS/05-Vectors-and-Objects.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from tools import * from models import * import plotly.graph_objects as go import plotly.figure_factory as ff from Bio.SeqUtils import GC from Bio import SeqIO import os from random import sample from plotly.subplots import make_subplots import pickle from scipy import stats from collections import Counter plt.ioff() import warnings warnings.filterwarnings('ignore') # + TFs = ["JUND", "MAX", "SPI1", "SP1", "HNF4A", "EGR1"] results = {} real_bm_include_target = {} real_bm_no_target = {} fake_bm_include_target = {} fake_bm_no_target = {} for TF in TFs: real_bm_include_target[TF] = [] real_bm_no_target[TF] = [] fake_bm_include_target[TF] = [] fake_bm_no_target[TF] = [] for i in range(1,6): #pkl_file = open("../RESULTS_BM_R_True_I_True/"+ # TF+"_"+str(i)+"/mccoef.pkl", 'rb') pkl_file = open("../RESULTS_BM_SUBSAMPLE_R_True_I_True/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_true = pickle.load(pkl_file) pkl_file.close() real_bm_include_target[TF].append(list(mccoef_true_true.values())[0]) #pkl_file = open("../RESULTS_BM_R_True_I_False/"+ # TF+"_"+str(i)+"/mccoef.pkl", 'rb') pkl_file = open("../RESULTS_BM_SUBSAMPLE_R_True_I_False/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_false = pickle.load(pkl_file) pkl_file.close() real_bm_no_target[TF].append(list(mccoef_true_false.values())[0]) #pkl_file = open("../RESULTS_BM_R_False_I_True/"+ # TF+"_"+str(i)+"/mccoef.pkl", 'rb') pkl_file = open("../RESULTS_BM_SUBSAMPLE_R_False_I_True/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_false_true = pickle.load(pkl_file) pkl_file.close() fake_bm_include_target[TF].append(list(mccoef_false_true.values())[0]) #pkl_file = open("../RESULTS_BM_R_False_I_False/"+ # TF+"_"+str(i)+"/mccoef.pkl", 'rb') pkl_file = open("../RESULTS_BM_SUBSAMPLE_R_False_I_False/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_false_false = pickle.load(pkl_file) pkl_file.close() fake_bm_no_target[TF].append(list(mccoef_false_false.values())[0]) real_bm_include_target = pd.Series(real_bm_include_target) real_bm_no_target = pd.Series(real_bm_no_target) fake_bm_include_target = pd.Series(fake_bm_include_target) fake_bm_no_target = pd.Series(fake_bm_no_target) # + results = {} real_cofactor_include_target = {} real_cofactor_no_target = {} for TF in TFs: real_cofactor_include_target[TF] = [] real_cofactor_no_target[TF] = [] for i in range(1,6): pkl_file = open("../RESULTS_COFACTOR_SUBSAMPLE_I_True/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_true = pickle.load(pkl_file) pkl_file.close() real_cofactor_include_target[TF].append(list(mccoef_true_true.values())[0]) pkl_file = open("../RESULTS_COFACTOR_SUBSAMPLE_I_False/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_false = pickle.load(pkl_file) pkl_file.close() real_cofactor_no_target[TF].append(list(mccoef_true_false.values())[0]) real_cofactor_include_target = pd.Series(real_cofactor_include_target) real_cofactor_no_target = pd.Series(real_cofactor_no_target) # + results = {} real_string_include_target = {} real_string_no_target = {} for TF in TFs: real_string_include_target[TF] = [] real_string_no_target[TF] = [] for i in range(1,6): pkl_file = open("../RESULTS_STRING_SUBSAMPLE_I_True/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_true = pickle.load(pkl_file) pkl_file.close() real_string_include_target[TF].append(list(mccoef_true_true.values())[0]) pkl_file = open("../RESULTS_STRING_SUBSAMPLE_I_False/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_false = pickle.load(pkl_file) pkl_file.close() real_string_no_target[TF].append(list(mccoef_true_false.values())[0]) real_string_include_target = pd.Series(real_string_include_target) real_string_no_target = pd.Series(real_string_no_target) # + real_lowcorbm_include_target = {} real_lowcorbm_no_target = {} for TF in TFs: real_lowcorbm_include_target[TF] = [] real_lowcorbm_no_target[TF] = [] for i in range(1,6): pkl_file = open("../RESULTS_LOWCORBM_SUBSAMPLE_I_True/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_true = pickle.load(pkl_file) pkl_file.close() real_lowcorbm_include_target[TF].append(list(mccoef_true_true.values())[0]) pkl_file = open("../RESULTS_LOWCORBM_SUBSAMPLE_I_False/"+ TF+"_"+str(i)+"/mccoef.pkl", 'rb') mccoef_true_false = pickle.load(pkl_file) pkl_file.close() real_lowcorbm_no_target[TF].append(list(mccoef_true_false.values())[0]) real_lowcorbm_include_target = pd.Series(real_lowcorbm_include_target) real_lowcorbm_no_target = pd.Series(real_lowcorbm_no_target) # + #figure 6 boxplot fig = go.Figure() TF = "JUND" fig.add_trace(go.Box( y=real_bm_include_target[TF], x=[TF]*5, name='Same binding mode', marker_color='rgb(25,101,176)', showlegend=False )) fig.add_trace(go.Box( y=real_cofactor_include_target[TF], x=[TF]*5, name='Cofactors', marker_color='rgb(123,175,222)', showlegend=False )) fig.add_trace(go.Box( y=real_lowcorbm_include_target[TF], x=[TF]*5, name='Same binding mode (low correlation)', marker_color='rgb(78,178,101)', showlegend=False )) fig.add_trace(go.Box( y=real_string_include_target[TF], x=[TF]*5, name='STRING partners', marker_color='rgb(247,240,86)', showlegend=False )) fig.add_trace(go.Box( y=fake_bm_include_target[TF], x=[TF]*5, name='Random', marker_color='rgb(220,5,12)', showlegend=False )) fig.add_trace(go.Box( y=[0,0,0,0,0], x=[TF]*5, name='', marker_color='white', showlegend=False )) ########################################### fig.add_trace(go.Box( y=real_bm_no_target[TF], x=[TF]*5, name='Same binding mode', marker_color='rgb(25,101,176)', showlegend=False )) fig.add_trace(go.Box( y=real_cofactor_no_target[TF], x=[TF]*5, name='Co-factors', marker_color='rgb(123,175,222)', showlegend=False )) fig.add_trace(go.Box( y=real_lowcorbm_no_target[TF], x=[TF]*5, name='Same binding mode (low correlation)', marker_color='rgb(78,178,101)', showlegend=False )) fig.add_trace(go.Box( y=real_string_no_target[TF], x=[TF]*5, name='STRING partners', marker_color='rgb(247,240,86)', showlegend=False )) fig.add_trace(go.Box( y=fake_bm_no_target[TF], x=[TF]*5, name='Random', marker_color='rgb(220,5,12)', showlegend=False )) fig.update_layout(title='', plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', boxmode='group', font=dict( family="Arial", size=14, color="black" )) fig.update_layout(legend=dict( yanchor="top", y=0.99, xanchor="right", x=1.4, font=dict( size=10, color="black" ) )) #fig.update_layout(autosize=False,width=500,height=333) fig.update_yaxes(range=[0, 1], title= 'MCC') fig.update_xaxes(showline=True, linewidth=2, linecolor='black', tickfont=dict(size=18)) fig.update_yaxes(showline=True, linewidth=2, linecolor='black') fig.show()
notebooks/TL_exploring_pentad_TFs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.7.4 # language: python # name: python-374 # --- # # Annotations # ## Überblick # # Wir können visuelle Hinweise (Begrenzungslinien, schattierte Bereiche, Beschriftungen und Pfeile usw.) zu unseren Plots hinzufügen, um bestimmte Merkmale hervorzuheben. Bokeh bietet hierfür mehrere Annotationstypen. Um *Annotations* hinzuzufügen, erstellen wir normalerweise ein *Low-Level*-Objekt und fügen es mit `add_layout` unserem Diagramm hinzu. Schauen wir uns einige konkrete Beispiele an: # ### Spans # # Spans sind vertikale oder horizontale Linien, für die die Spannweiten zwischen den Bemaßung angegeben werden kann, z.B.: # + hide_input=true from bokeh.io import output_notebook, show from bokeh.plotting import figure output_notebook() # + import numpy as np from bokeh.models.annotations import Span x = np.linspace(0, 20, 200) y = np.sin(x) p = figure(y_range=(-2, 2)) p.line(x, y) upper = Span(location=1, dimension='width', line_color='olive', line_width=4) p.add_layout(upper) lower = Span(location=-1, dimension='width', line_color='firebrick', line_width=4) p.add_layout(lower) show(p) # - # ### Box Annotations # # Soll ein Bereich eines Diagramms hervorgehoben werden, so können diese mit `BoxAnnotation`, den Koordinateneigenschaften # # * `top` # * `left` # * `bottom` # * `right` # # sowie Linien- und Fülleigenschaften das Erscheinungsbild konfiguriert werden. # # Infinite Boxen können erstellt werden, indem die Koordinaten nicht angegeben werden. Wenn zum Beispiel `top` nicht angegeben ist, wird die Box immer bis zum oberen Rand des Plotbereichs angezeigt, unabhängig davon, ob ein Verschieben oder Zoomen stattfindet, z.B.: # + import numpy as np from bokeh.models.annotations import BoxAnnotation x = np.linspace(0, 20, 200) y = np.sin(x) p = figure(y_range=(-2, 2)) p.line(x, y) # region that always fills the top of the plot upper = BoxAnnotation(bottom=1, fill_alpha=0.1, fill_color='olive') p.add_layout(upper) # region that always fills the bottom of the plot lower = BoxAnnotation(top=-1, fill_alpha=0.1, fill_color='firebrick') p.add_layout(lower) # a finite region center = BoxAnnotation(top=0.6, bottom=-0.3, left=7, right=12, fill_alpha=0.1, fill_color='navy') p.add_layout(center) show(p) # - # ### Label # # Mit der Annotation `Label` können wir einzelne Beschriftungen einfach an Plots anbringen. Die anzuzeigende Position und der Text sind als `x`, `y` und `text` konfiguriert: # # ```python # Label(x=10, y=5, text="Some Label") # ``` # # Standardmäßig befinden sich die Einheiten im *data space*, aber `x_units` und `y_units` können auf `screen` `gesetzt werden, um die Beschriftung relativ zur Zeichenfläche zu positionieren, und Labels können mit `x_offset` und `y_offset` positioniert werden. # # `Label`-Objekte haben auch Standardtext-, Zeilen- (`border_line`) und Fülleigenschaften (`background_fill`). Die Linien- und Fülleigenschaften gelten für einen Begrenzungsrahmen um den Text: # # ```python # Label(x=10, y=5, text="Some Label", text_font_size="12pt", # border_line_color="red", background_fill_color="blue") # ``` # + from bokeh.models.annotations import Label from bokeh.plotting import figure p = figure(x_range=(0,10), y_range=(0,10)) p.circle([2, 5, 8], [4, 7, 6], color="olive", size=10) label = Label(x=5, y=7, x_offset=12, text="Second Point", text_baseline="middle") p.add_layout(label) show(p) # - # ### LabelSet # # Mit der Annotation `LabelSet` könnt ihr viele Beschriftungen gleichzeitig erstellen, z.B. wenn ihr einen ganzen Satz von Scatter Markers beschriften möchtet. Sie ähneln `Label`, können aber auch eine `ColumnDataSource` als `source` -Eigenschaft nutzen, wobei sich `x` und `y` auf Spalten in der Datenquelle beziehen. # + from bokeh.plotting import figure from bokeh.models import ColumnDataSource, LabelSet source = ColumnDataSource(data=dict( temp=[166, 171, 172, 168, 174, 162], pressure=[165, 189, 220, 141, 260, 174], names=['A', 'B', 'C', 'D', 'E', 'F'])) p = figure(x_range=(160, 175)) p.scatter(x='temp', y='pressure', size=8, source=source) p.xaxis.axis_label = 'Temperature (C)' p.yaxis.axis_label = 'Pressure (lbs)' labels = LabelSet(x='temp', y='pressure', text='names', level='glyph', x_offset=5, y_offset=5, source=source, render_mode='canvas') p.add_layout(labels) show(p) # - # ### Arrows # # Mit der Annotation `Arrow` könnt ihr auf verschiedene Elemente in eurer Zeichnung *zeigen+. Dies kann besonders bei Beschriftungen hilfreich sein. # # So könnt ihr beispielsweise einen Pfeil erstellen, der von `(0,0)` bis `(1,1)` zeigt: # # ```python # p.add_layout(Arrow(x_start=0, y_start=0, x_end=1, y_end=0)) # ``` # # Dieser Pfeil hat die Standardspitze [OpenHead](http://bokeh.pydata.org/en/latest/docs/reference/models/arrow_heads.html#bokeh.models.arrow_heads.OpenHead). Andere Arten von Pfeilspitzen sind [NormalHead](http://bokeh.pydata.org/en/latest/docs/reference/models/arrow_heads.html#bokeh.models.arrow_heads.NormalHead) und [VeeHead](http://bokeh.pydata.org/en/latest/docs/reference/models/arrow_heads.html#bokeh.models.arrow_heads.VeeHead). Der Typ des Pfeilkopfs kann durch die Eigenschaften `start` and `end` von `Arrow`-Objekten konfiguriert werden: # # ```python # p.add_layout(Arrow(start=OpenHead(), end=VeeHead(), # x_start=0, y_start=0, x_end=1, y_end=0)) # ``` # # Dies erzeugt einen Doppelpfeil mit `OpenHead` und `VeeHead`. Pfeilspitzen haben darüberhinaus den Standardsatz von Linien- und Fülleigenschaften, um deren Aussehen zu konfigurieren, z.B.: # # ```python # OpenHead(line_color="firebrick", line_width=4) # ``` # # Der Code und das Diagramm unten zeigen mehrere dieser Konfigurationen zusammen. # + from bokeh.models.annotations import Arrow from bokeh.models.arrow_heads import OpenHead, NormalHead, VeeHead p = figure(plot_width=600, plot_height=600) p.circle(x=[0, 1, 0.5], y=[0, 0, 0.7], radius=0.1, color=["navy", "yellow", "red"], fill_alpha=0.1) p.add_layout(Arrow(end=OpenHead(line_color="firebrick", line_width=4), x_start=0, y_start=0, x_end=1, y_end=0)) p.add_layout(Arrow(end=NormalHead(fill_color="orange"), x_start=1, y_start=0, x_end=0.5, y_end=0.7)) p.add_layout(Arrow(end=VeeHead(size=35), line_color="red", x_start=0.5, y_start=0.7, x_end=0, y_end=0)) show(p) # - # ### Legenden # # Wenn Diagramme mehrere Glyphen enthalten, ist es wünschenswert, eine Legende hinzuzufügen, um Betrachtern die Interpretation zu erleichtern. Bokeh kann Legenden anhand der hinzugefügten Glyphen leicht generieren. # #### Einfache Legenden # # Im einfachsten Fall könnt ihr einen String als `legend` an eine Glyph-Funktion übergeben: # # ```python # p.circle(x, y, legend="sin(x)") # ``` # # In diesem Fall erstellt Bokeh automatisch eine Legende, die eine Darstellung dieser Glyphe zeigt. # + import numpy as np x = np.linspace(0, 4*np.pi, 100) y = np.sin(x) p = figure(height=400) p.circle(x, y, legend_label="sin(x)") p.line(x, 2*y, legend_label="2*sin(x)", line_dash=[4, 4], line_color="orange", line_width=2) show(p) # - # #### Zusammengesetzte Legenden # # Im obigen Beispiel haben wir für jede Glyphenmethode ein anderes Etikett bereitgestellt. Manchmal werden zwei (oder mehr) verschiedene Glyphen mit einer einzigen Datenquelle verwendet. In diesem Fall können zusammengesetzte Legenden erstellt werden. Wenn ihr z.B. eine Sin-Kurve mit einer Linie und einer Markierung plottet, könnt ihr ihnen dieselbe Bezeichnung geben um sie dazu zu bringen, gemeinsam in der Legende zu erscheinen: # # ```python # p.circle(x, y, legend="sin(x)") # p.line(x, y, legend="sin(x)", line_dash=[4, 4], line_color="orange", line_width=2) # ``` # ### Farbbalken # # Farbbalken sind besonders nützlich, wenn wir die Farbe einer Glyphe entsprechend der Farbzuordnung variiert. Bokeh-Farbbalken werden mit einer Farbzuordnung konfiguriert und mit der `add_layout'-Methode zu Plots hinzugefügt: # # ```python # color_mapper = LinearColorMapper(palette="Viridis256", low=data_low, high=data_high) # color_bar = ColorBar(color_mapper=color_mapper, location=(0,0)) # p.add_layout(color_bar, 'right') # ``` # # Das folgende Beispiel zeigt ein vollständiges Beispiel, in dem auch die Farbzuordnung zur Umwandlung der Glyphenfarbe verwendet wird. # + from bokeh.sampledata.autompg import autompg from bokeh.models import LinearColorMapper, ColorBar from bokeh.transform import transform source = ColumnDataSource(autompg) color_mapper = LinearColorMapper(palette="Viridis256", low=autompg.weight.min(), high=autompg.weight.max()) p = figure(x_axis_label='Horsepower', y_axis_label='MPG', tools='', toolbar_location=None) p.circle(x='hp', y='mpg', color=transform('weight', color_mapper), size=20, alpha=0.6, source=autompg) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12, location=(0,0), title='Weight') p.add_layout(color_bar, 'right') show(p)
docs/bokeh/annotations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="wGgsxpQoOJH4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="da7a4911-7921-405d-b04a-def416b218d3" import numpy as np import matplotlib.pyplot as plt import pickle import os import keras import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Activation, Flatten, Dense, Dropout, BatchNormalization, Reshape from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, LeakyReLU, Conv2DTranspose, ReLU from tensorflow.keras.optimizers import Adam from tensorflow.keras import layers import datetime from keras import initializers # + id="Xt7PZeqQU-Ol" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 163} outputId="2b7136fe-437b-4e87-cf5e-4c7d617c481b" pip install gdown # + id="moRzA5auVBTQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 181} outputId="9a1486f4-2bf8-42d9-fe97-3a4378814d8c" import gdown gdown.download("https://drive.google.com/uc?id={0}".format("1-JVnG_wVJR3VgAwi6-Hhu2C-ZAyQ2-_9"),"gt.pickle",quiet = False) gdown.download("https://drive.google.com/uc?id={0}".format("1-7E0x-UGFjotUH8UJAWruM9Y0rwEzYzV"),"occ.pickle",quiet = False) # + id="8uPj2p2JWhAU" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="0d2ad905-5391-4ca3-cb06-c186b8cd87bd" # !ls # + id="-vMHgPQyWpAf" colab_type="code" colab={} pickle_in = open("occ.pickle","rb") x = pickle.load(pickle_in) pickle_in = open("gt.pickle","rb") y = pickle.load(pickle_in) # + id="Z1Unr-6_XWHP" colab_type="code" colab={} from skimage.transform import resize x = resize(x, (len(x),64,64,1),anti_aliasing=False) y= resize(y, (len(y),64,64,1),anti_aliasing=False) # + id="DtkUgx4TYyJB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="835a008b-aa2c-4fad-8873-2bbe1c15d1ca" print(x.shape) print(y.shape) # + id="YgO__Pu0X0kS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 223} outputId="40735d22-2dde-402d-c467-b1d41e93a425" fig = plt.figure(figsize = (6,6)) fig.add_subplot(1,2,1) plt.imshow(x[0,:,:,0], cmap = "gray") fig.add_subplot(1,2,2) plt.imshow(y[0,:,:,0], cmap = "gray") # + id="uyRlrXU2ZJ98" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 110} outputId="3d724cd4-3142-4433-a36b-701843d77232" def creategen(): generator = Sequential() generator.add(Conv2D(64,(5,5),strides = (2,2), input_shape = x.shape[1:], padding = "SAME", kernel_initializer = "random_normal" )) generator.add(BatchNormalization()) generator.add(ReLU()) generator.add(Dropout(0.3)) generator.add(Conv2D(128,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal" )) generator.add(BatchNormalization()) generator.add(ReLU()) generator.add(Dropout(0.3)) generator.add(Conv2D(256,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal" )) generator.add(BatchNormalization()) generator.add(ReLU()) generator.add(Dropout(0.3)) generator.add(Conv2DTranspose(128,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal", use_bias=False )) generator.add(BatchNormalization()) generator.add(ReLU()) #generator.add(Dropout(0.3)) generator.add(Conv2DTranspose(64,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal", use_bias=False )) generator.add(BatchNormalization()) generator.add(ReLU()) #generator.add(Dropout(0.3)) generator.add(Conv2DTranspose(1,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal", use_bias=False, activation = "sigmoid" )) return generator generator = creategen() # + id="o5r5OiHgcksx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 92} outputId="9e5c1828-b8ec-48d0-f6a3-6b1368814ea6" def create_disc(): discriminator = Sequential() discriminator.add(Conv2D(64,(5,5),strides = (2,2), input_shape = x.shape[1:], padding = "SAME", kernel_initializer = "random_normal" )) discriminator.add(BatchNormalization()) discriminator.add(ReLU()) discriminator.add(Dropout(0.3)) discriminator.add(Conv2D(128,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal" )) discriminator.add(BatchNormalization()) discriminator.add(ReLU()) discriminator.add(Dropout(0.3)) discriminator.add(Conv2D(256,(5,5),strides = (2,2), padding = "SAME", kernel_initializer = "random_normal" )) discriminator.add(BatchNormalization()) discriminator.add(ReLU()) discriminator.add(Dropout(0.3)) discriminator.add(Flatten()) discriminator.add(Dense(1, activation = "sigmoid")) return discriminator discriminator = create_disc() # + id="-gl2HB-DdzJa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 854} outputId="a5bda12e-9c43-44c1-8dcc-1c202d5d7a1d" generator.summary() # + id="J9TyFrELeW1N" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 746} outputId="a8a49532-94dc-46c4-f1f7-da212fa6252e" opt_disc = Adam(lr=0.00004) discriminator.trainable = True discriminator.compile(loss = "binary_crossentropy", optimizer = opt_disc) discriminator.summary() # + id="f23MaGg7e9JI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 854} outputId="65a1b827-e7d2-431f-b2a6-85e056b891c9" opt_gen = Adam(lr=0.00001) generator.compile(loss = "mean_squared_error", optimizer = opt_disc) generator.summary() # + id="QJN5wCYhgscV" colab_type="code" colab={} def creategan(generator,discriminator): gan = Sequential() gan.add(generator) discriminator.trainable = False gan.add(discriminator) return gan gan = creategan(generator,discriminator) # + id="WLn1TQOJhP6t" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 235} outputId="8f8c26e7-316b-4992-8544-bcd6b162792a" opt_gan = Adam(lr=0.00001) gan.compile(loss = "binary_crossentropy", optimizer = opt_gan) gan.summary() # + id="c5WhVpSUh2Yy" colab_type="code" colab={} def train (x, y, nepoch): gen_predict = None gan_inp = x gan_label = np.ones(64) gan_predict = None disc_inp = None disc_label = np.zeros(64*2) disc_label[64:] = 1 disc_predict = None #sess = tf.Session() for epoch in range(nepoch): for batch_ctr in range(64): gen_predict = generator.predict(gan_inp[batch_ctr*64:(batch_ctr+1)*64]) if(epoch%2==0): disc_inp = gen_predict disc_label = np.zeros(64) else: disc_inp = y[batch_ctr*64:(batch_ctr+1)*64] disc_label = np.ones(64) gen_label = y[batch_ctr*64:(batch_ctr+1)*64] d_loss = discriminator.train_on_batch(disc_inp,disc_label) gan_loss = gan.train_on_batch(gan_inp[batch_ctr*64:(batch_ctr+1)*64], gan_label) gen_loss = generator.train_on_batch(gan_inp[batch_ctr*64:(batch_ctr+1)*64],gen_label) print("Epoch {0} Gan Loss {1} Disc Loss {2} Gen Loss {3}".format(epoch,gan_loss,d_loss,gen_loss)) # + id="BO5q1AZdmqHw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 965} outputId="37fdfa31-2295-4ab9-a721-ec2c89401176" batch_size = 64 train(x,y,50) # + id="6ZmMkujvm1no" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 263} outputId="b98a860d-7e81-4ab4-b055-ca187eb37ee2" a = 4170 b = 4180 pred = generator.predict(x[a:b]) fig = plt.figure(figsize = (10,10)) for ctr in range(10): fig.add_subplot(1,10,ctr+1) plt.imshow(np.reshape(x[a+ctr], (64,64)), cmap = "gray") fig = plt.figure(figsize = (10,10)) for ctr in range(10): fig.add_subplot(1,10, ctr+1) plt.imshow(np.reshape(y[a+ctr], (64,64)),cmap = "gray") fig = plt.figure(figsize = (10,10)) for ctr in range(10): fig.add_subplot(1,10, ctr+1) plt.imshow(np.reshape(pred[ctr], (64,64)), cmap = "gray")
Applied AI Study Group #1 - July 2019/week1/GANExample.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### NumPy # NumPy is effective library for handling all calculations. NumPy array is similar as Python list, but much faster and more memory effective. # mosr common way to import NumPy package with np alias import numpy as np # .p.array creates numpy arrays from python lists lst = [1, 2, 3, 4, 5] l = np.array(lst) l np.array(lst, dtype = 'float64') # numpy arrays can be multidimensional m = np.array([range(i, i + 5) for i in lst]) m # ### Arrays from scratch # array of zeros np.zeros(10, dtype = int) np.ones((5, 4), dtype = float) # np.full creates array with your elements np.full((3, 5), 'hey') # array sequence with step np.arange(0, 100, 10) # evenly spaced array np.linspace(0, 1, 5) # creatin n by m array with uniformly distributed random values np.random.random((5, 2)) # n by m array with normally distributed random values with mean 50, std 20 np.random.normal(50, 20, (5, 5)) # n by m array with random integers np.random.randint(0, 100, (5, 5)) # n by n identity array np.eye(5) # ### NumPy array atrributes # let's create 1, 2, 3 dimensional arrays x1 = np.random.randint(10, size = 6) x2 = np.random.randint(10, size = (5, 5)) x3 = np.random.randint(10, size = (5, 5, 5)) # arrays has ndim (number of dimensions), shape (size of dimensions) and size (size of array) attributes print(x3.ndim) print(x3.shape) print(x3.size) # another useful attributes are dtype (type of elements) and nbytes (total memory usage of array) print(x2.dtype) print(x2.nbytes) # ### Indexing # In general elements can be obtained with index number starting from 0. In case of more than one dimension, indexes should be comma separated tuples. x1[0] x3 x3[2, 3, 1] # NumPy arrays are mutable x1[2] = 55 x1 # ### Slicing # Same notations used in NumPy array as in Python lists. x2[:2, :] # reversed selection x2[:2, ::-1] # ### Subarrays # When performing slicing, and assigning this subarray to new variable, you have to keep in mind that it's not copy of subarray. x2_sub = x2[:2, 1:4] x2_sub x2_sub[1, 1] = -99 x2_sub x2 # copy() method can help to obtain copy of subarray x2_copy = x2[:2, 2:].copy() x2_copy x2_copy[1, 2] = 1000 x2_copy x2 # ### Reshaping # Reshaping of numpy array can be performed with reshape() method. x = np.linspace(1, 10, 25) x x.reshape((5, 5)) # ### Concatenating # np.concatenate, np.vstack, np.hstack - perform concatenations x1 = np.array([1, 2, 3]) x2 = np.array([4, 5, 6]) np.concatenate([x1, x2]) np.hstack([x1, x2]) x1 = np.random.randint(10, size = (5, 5)) x2 = np.random.randint(10, size = 5) x1 x2 np.vstack([x1, x2]) # ### Splitting # Splitting is opposite of concatenation x1 = np.random.randint(100, size = 10) x1 np.split(x1, [2, 6]) # vertical splitting x = np.random.randint(100, size = (10, 10)) x np.vsplit(x, [5]) # same with horizontal split np.hsplit(x, [5]) # ### Vectorized operations # NumPy optimized for vectorized calculations. Traditional loops can be very slow. Let's compare performances. def sum_before(lst): res = [] for i in lst: res.append(i**5) return res lst = list(np.random.randint(1000, size = 10)) lst sum_before(lst) lst = list(np.random.randint(1000, size = 10000)) # %timeit sum_before(lst) # %timeit np.power(np.array(lst), 5) # ### Boolean operations # Same logic as in core Python mat = np.random.randint(100, size = (5, 3)) mat np.max(mat, axis = 0) np.mean(mat, axis = 1).reshape(5, 1) mat > 50 np.sum(mat > 50) # check if there any given true value np.any(mat == -99) np.any(mat > 90) np.all(mat > 0) # boolean masks mat[mat > 70] (mat > 50) & (mat%2 == 1) # '&' used for each element. python's and can't be used in this problem # ### Example import matplotlib.pyplot as plt import seaborn; seaborn.set() # %matplotlib inline # + mat = np.random.randint(100, size = (100, 2)) _ = plt.scatter(mat[:, 0], mat[:, 1]) plt.show() # - indices = np.random.choice(mat.shape[0], 15, replace = False) indices selection = mat[indices, :] selection.shape _ = plt.scatter(mat[:, 0], mat[:, 1], alpha = 0.3) _ = plt.scatter(selection[:, 0], selection[:, 1], facecolor = 'red', s = 50) plt.show() # ### Pandas # Pandas package built on top of NumPy package, and serve the purpose of data manipulations. The key element of Pandas is DataFrame, which consist of Series and Series are like ndarrays. import pandas as pd import numpy as np # Series are one-diemnsional array of indexed data. data = pd.Series([0.25, 0.5, 0.75, 1.0]) data # The main difference between Series and numpy arrays is that Series can have any indexes, when numpy arrays only ordered numbers. data = pd.Series([0.25, 0.5, 0.75, 1.0], index = ['a', 'b', 'c', 'd']) data # From this point, we can start thinkiing of pandas Series as python dictionaries. In dictionaries you have key:value, in series index:value. But series are more efficient than dictionaries, because all values in series should be one type. We can build series from dictionary directly: population_dict = {'California': 38332521, 'Texas': 26448193, 'New York': 19651127, 'Florida': 19552860 ,'Illinois': 12882135} population = pd.Series(population_dict) population # Series can be created from lists, from scalars, from dictionaries. If you choose given indexes, it will output shrinked dictionary: d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} s = pd.Series(d, index = [1,3]) s # DataFrames are generalized two-dimensional numpy arrays. DFs can have as series different indices, and different column names. ru = {1: 'a', 2: 'b', 3: 'v', 4: 'g'} en = {1: 'a', 2: 'b', 4 : 'd', 3: 'c'} df = pd.DataFrame({'en': en, 'ru': ru}) df # DFs has .index attribute, top get names of index df.index # columns attribute returns names of columns df.columns # ### Pandas Index object ind = pd.Index([2, 3, 5, 7, 11]) ind # index arrays can be treated as stabdard python arrays ind[1] ind[::2] # attributes of index arrays print(ind.size, ind.shape, ind.ndim, ind.dtype) # + # the main difference with numpy array is that index arrays are immutable #ind[0] = 1 # - # operations with index arrays indA = pd.Index([1,3,5,7,9]) indB = pd.Index([2,3,5,7,11]) # intersection indA & indB # union indA | indB #symmetric difference indA ^ indB #
Python_ds_libraries.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/", "height": 122} colab_type="code" id="REAT3H4WIvMM" outputId="47739075-a9a4-4d26-c6e4-1508b96e41d3" from google.colab import drive drive.mount('/content/gdrive') # + colab={} colab_type="code" id="TO8-LrpFL_Ky" from zipfile import ZipFile import pandas as pd from sklearn.utils import shuffle from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import MultiLabelBinarizer from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC, LinearSVC from sklearn.naive_bayes import MultinomialNB from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score from sklearn.metrics import average_precision_score, roc_auc_score, precision_recall_fscore_support from sklearn.metrics import multilabel_confusion_matrix,classification_report # + colab={} colab_type="code" id="q3ZkRnetJyu5" # Change the path of the data file zip_ref = ZipFile("/content/gdrive/My Drive/Co_lab/Blog/blog-authorship-corpus.zip", 'r') zip_ref.extractall("/tmp") zip_ref.close() # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="6eE6FXLULcvl" outputId="e4c7ce89-07bd-43da-d202-fc7f69c6458c" # !ls -l /tmp # + colab={} colab_type="code" id="eDEVWNuCNCSn" # + colab={} colab_type="code" id="csuEf3RDMzqK" df = pd.read_csv('/tmp/blogtext.csv') # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="ampdfhwQNAoe" outputId="f1faeb13-bf36-4807-e3fc-7f9142f9c65f" df.shape # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="zCy_ydIuNMJG" outputId="21bfa4b2-6dd9-4e37-d2be-f0e2d11123dd" df.head(5) # + colab={} colab_type="code" id="KALH_8EeNRxZ" from sklearn.utils import resample blog = resample(df,replace=True,n_samples=50000,random_state=7) # with replacement # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="GVdILDK4RuqJ" outputId="6a7f6cca-17ad-4ce9-a8f9-b20bb105b02b" blog.shape # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="-9qPUZeBRyA_" outputId="d4997201-bbc8-4a96-fc02-6bb83f94481a" blog.head(5) # + colab={} colab_type="code" id="XqltcaOKSyfv" #Preprocessing # + colab={} colab_type="code" id="LTUN2eJUboYO" import re # + colab={} colab_type="code" id="MITyJnAAc6vU" #converting text into lowercase # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="AmBgvYr2al3o" outputId="5b9293a7-5c21-4cbe-802f-dda17180ced2" blog['text'] = [text.lower() for text in blog['text']] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="dR43FBfKa5CM" outputId="7e1251b1-547d-48a1-e258-33c8e3b6b9ab" blog['text'][0:5] # + colab={} colab_type="code" id="naV4VPZnczz2" #Removing unwanted charecters # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="np5MMDlMTgsj" outputId="dfb316d6-b97f-455e-c8ea-d4f8cb0eb54a" blog['text'] = [re.sub("[^a-z0-9 ]+","", text) for text in blog['text']] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="g9hTHm-va5pE" outputId="cc9f503d-e999-470c-e629-3d6c6eee6fd1" blog['text'][0:5] # + colab={} colab_type="code" id="-KssDtAgctRL" #Removing Unwanted spaces # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="lsbIwgJlZ4yL" outputId="cd675de9-cd0d-455c-e07b-658dd631d3a9" blog['text'] = [re.sub("\s+"," ", text).strip() for text in blog['text']] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="yN2Cb66cbtGg" outputId="bf5f4e22-b1e3-4d0f-b645-436b8c8745cd" blog['text'][0:5] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="inEqSYLm7_k_" outputId="54a6526c-8f60-4ad6-cece-46cc3f33228d" import nltk from nltk import word_tokenize, pos_tag nltk.download('wordnet') from nltk.stem import PorterStemmer, WordNetLemmatizer nltk.download('stopwords') from nltk.corpus import stopwords nltk.download('punkt') from nltk import punkt # + colab={} colab_type="code" id="BYR-Sjk_b8NM" #removing stop words # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="9Zj4Vw9i6a_i" outputId="d5302826-711d-454a-c1b7-fe452bd7e1b8" stop = stopwords.words('english') blog['text'] = blog['text'].apply( lambda t : " ".join( word for word in t.split() if len(word)>2 if word not in stop ) ) # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="SW-Tgyii6idj" outputId="eb7376d2-48ff-476f-9703-62e2ed663b20" blog['text'][0:5] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="iXbQc3bH8TkK" outputId="fafc0786-ccae-40e1-eaa4-ed4b5e039f61" #### Lemmatize the text #Lemmatization lemmatizer = WordNetLemmatizer() # perform lemmatization on the title blog['text'] = blog['text'].apply( lambda t : " ".join( [lemmatizer.lemmatize(word) for word in t.split() ]) ) # + colab={"base_uri": "https://localhost:8080/", "height": 136} colab_type="code" id="HtZ_p41b6kY4" outputId="b12bcbf1-209c-4fa4-e74e-7b55525d6c87" blog['text'][0:6] # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="-wKDKWbG8hAS" outputId="fd5ca804-e339-4cd2-ddf0-fa9cf069231f" #As we want to make this into a multi-label classification problem, you are required to merge all the label columns together, so that we have all the labels together for a particular sentence blog.columns # + colab={"base_uri": "https://localhost:8080/", "height": 111} colab_type="code" id="qipIoDiu8wXx" outputId="b6419922-bea5-4ad5-9644-3d398a24e50b" blog.head(2) # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="b-hKyBnm88aI" outputId="42005cf8-8b58-4d69-f965-78cb3286c1ba" #### a. Label columns to merge: “gender”, “age”, “topic”, “sign” #Merge all four labels into one label blog['labels'] = blog.apply(lambda x : [x['gender'], str(x['age']), x['topic'], x['sign']], axis=1) # + colab={"base_uri": "https://localhost:8080/", "height": 111} colab_type="code" id="iBWYD6A_9IHP" outputId="21672850-1f0f-49e5-cecd-94626603b249" blog[['text','labels']][0:2] # + colab={} colab_type="code" id="xLuokTt7-vEt" #### b. After completing the previous step, there should be only two columns in your dataframe i.e. “text” and “labels” #Create a DataFrame with two columns text and length blog_df = pd.DataFrame() blog_df['text'] = blog['text'] blog_df['labels'] = blog['labels'] # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" id="86ZGTgry_DCf" outputId="fe1b0a61-dc01-4e16-c3c4-1a7a06429a96" blog_df.shape blog_df.columns blog_df.head() # + colab={} colab_type="code" id="Z41yu4k_AYom" ### 4. Separate features and labels, and split the data into training and testing (5 points) #Features X = blog_df['text'] # + colab={} colab_type="code" id="RE3SZYpGAgO1" #labels y = blog_df['labels'] # + colab={} colab_type="code" id="T0FH12tdAnqa" #Split Features and labels into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=7) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="m2VWoDoiA2mR" outputId="0a93878c-0bd7-49c7-ea91-6a9b75ae8fe1" #Shape of X_train and y_train X_train.shape, y_train.shape # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="DXiZhZCyA8CR" outputId="0aa06f75-6bc9-4c65-fc8c-a9bb7b361061" #Shape of X_test and y_test X_test.shape, y_test.shape # + colab={} colab_type="code" id="RCNcDHx-BMfM" ### 5. Vectorize the features (5 points) #### a. Create a Bag of Words using count vectorizer #### i. Use ngram_range=(1, 2) #### ii. Vectorize training and testing features #Create an instance of CountVectorizer countvect = CountVectorizer(ngram_range=(1,2), max_features=8000) # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="jFg3aVrFBT8I" outputId="ef7d44ca-fdc1-4734-d107-8b376ce4e33b" #Fit the CountVectorizer on Feature set countvect.fit(X) # + colab={} colab_type="code" id="Qrem47bTBbWT" #Transform training set and test set into count vectors (BoW) X_bow_train = countvect.transform(X_train) X_bow_test = countvect.transform(X_test) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="-Xl9B3-kBgzC" outputId="28092c6a-e036-477e-d6b6-deaea0b7ecf4" #Shape of sparse csr matrices with count vectors of training set and test set X_bow_train.shape, X_bow_test.shape # + colab={} colab_type="code" id="IGBK8PofBmbU" #### b. Print the term-document matrix #Function to create term-document matrix by chunking the sparse csr matrix def get_dtm_using_chunks(sparce_csr_matrix, size, chunk_size): #size=countvect.max_features #chunk_size=100 dtm = pd.DataFrame() if size < chunk_size: dtm = pd.concat([dtm, pd.DataFrame(sparce_csr_matrix[:,0:size].toarray())], axis=1) gc.collect() chunks_nb = int(size/chunk_size) print("Max. Number of Features : ", size) print("Number of chunks used : ", chunks_nb) iter_ints = range(0, chunks_nb) print("Started creating DTM matrix by chunking....") for i in iter_ints: j = i * chunk_size if i+1 < chunks_nb: k = j + chunk_size #print("k loop",i,j,k,"\t") dtm = pd.concat([dtm, pd.DataFrame(sparce_csr_matrix[:,j:k].toarray())], axis=1) gc.collect() else: #print("j loop",i,j,"\t") dtm = pd.concat([dtm, pd.DataFrame(sparce_csr_matrix[:,j:].toarray())], axis=1) gc.collect() print("...Done") return dtm # + colab={} colab_type="code" id="-d0CcRSwb6zI" import gc # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="opQ0Q0ZRBtB7" outputId="3d122d26-ef6a-4d6c-c468-ced1f0d9b023" print("Term-Document Matrix for Training-set count vector:") dtm_train = get_dtm_using_chunks(X_bow_train, countvect.max_features, 100) # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="RPCzYc7dBy4x" outputId="f6a3cc91-eafe-487c-8f8e-e06f6c7d87dd" print("Term-Document Matrix for Test-set count vector:") dtm_test = get_dtm_using_chunks(X_bow_test, countvect.max_features, 100) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="HPYUqiQLB3Qw" outputId="5825efe2-57d7-4fd4-dc84-64136f9a11d0" ##### Term-Document Matrix for training set dtm_train.columns = countvect.get_feature_names() dtm_train.shape # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="_BxMgIslB80S" outputId="e42472af-e1ea-4b72-b4af-7acd3871bcfd" dtm_train.columns dtm_train.head() ##### Term-Document Matrix for test set dtm_test.columns = countvect.get_feature_names() dtm_test.shape # + colab={"base_uri": "https://localhost:8080/", "height": 270} colab_type="code" id="JgFaQ4URCI7Y" outputId="6005e02f-38d8-4e79-e0da-f885fb2e71bf" dtm_test.columns dtm_test.head() # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="19KtlV2iCNp1" outputId="21e900d1-e22c-487f-a6c0-f04d73e5684d" ### 6. Create a dictionary to get the count of every label i.e. the key will be label name and value will be the total count of the label. (5 points) y_train.head() y_test.head() # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="dYFlxkUVCvWw" outputId="bba56482-450c-41cb-f9b0-bae2f2a5a442" (y_train.append(y_test)).shape # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="-I3ZrVBSCzdc" outputId="e76155e1-0e92-44a9-d0fd-85f3106b7f37" #Dictionary to find count of each label in the multiclass label from collections import defaultdict label_counts = defaultdict(int) for label in y_train.append(y_test): for item in label: label_counts[item]+= 1 for key in label_counts: print("{} : {}".format(key, label_counts.get(key))) label_counts.keys() # + [markdown] colab_type="text" id="yqJUyMn1c_1d" # ### 7. Transform the labels - (7.5 points) # # - As we have noticed before, in this task each example can have multiple tags. To deal with # such kind of prediction, we need to transform labels in a binary form and the prediction will be # a mask of 0s and 1s. For this purpose, it is convenient to use MultiLabelBinarizer from sklearn # + colab={} colab_type="code" id="LEbkb1lkC3xv" #### a. Convert your train and test labels using MultiLabelBinarizer mlb = MultiLabelBinarizer(classes = sorted(label_counts.keys())) y_train_mlb = mlb.fit_transform(y_train) y_test_mlb = mlb.fit_transform(y_test) # + colab={"base_uri": "https://localhost:8080/", "height": 272} colab_type="code" id="N0HcGwLuDYgf" outputId="a1af148d-c7a6-43f4-c791-e9776345f9f5" mlb.classes_ # + colab={"base_uri": "https://localhost:8080/", "height": 153} colab_type="code" id="uy6LQbKGcS6S" outputId="813446a9-f666-49f8-c37a-41774f3f7445" y_train_mlb[0:2] # + colab={"base_uri": "https://localhost:8080/", "height": 153} colab_type="code" id="zV3Zcu9qcU2x" outputId="14a9b1b3-e76f-4901-e4c2-1340a5de372d" y_test_mlb[0:2] # + colab={} colab_type="code" id="B9gDVeRvC9S_" ## 8. Choose a classifier - (5 points) # In this task, we suggest using the One-vs-Rest approach, which is implemented in OneVsRestClassifier class. In this approach k classifiers (= number of tags) are trained. As a # basic classifier, use LogisticRegression . It is one of the simplest methods, but often it performs good enough in text classification tasks. It might take some time because the # number of classifiers to train is large. # + colab={} colab_type="code" id="wZdJE04dE5za" #### a. Use a linear classifier of your choice, wrap it up in OneVsRestClassifier to train it on every label logreg_clf = LogisticRegression(solver='lbfgs', max_iter=1000, random_state=42) # + colab={} colab_type="code" id="3Y3C9wGCE-tL" #### b. One-vs-Rest approach OnevsRest_clf = OneVsRestClassifier(estimator=logreg_clf) # + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="uX-lkFODFCtI" outputId="5c9f17df-b6a3-4c36-b522-e801b40cf858" ### 9. Fit the classifier, make predictions and get the accuracy (5 points) #Fit the Classifier on on count vectors for Training dataset OnevsRest_clf.fit(X_bow_train, y_train_mlb) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="a_7UYS4PFGvh" outputId="70b44430-d80d-4d08-d96a-700c107a8744" #classifier's score for training data OnevsRest_clf.score(X_bow_train, y_train_mlb) # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="IJwojrvZFKnK" outputId="a48a810a-b185-4807-fee7-312d5fb10649" #classes present in the multiclass classification OnevsRest_clf.classes_ # + colab={"base_uri": "https://localhost:8080/", "height": 136} colab_type="code" id="dC7KLESNFYVP" outputId="0fde3b8d-2dd7-438e-ce90-49ca3f632264" #Predicted values on count vectors for Test dataset y_pred = OnevsRest_clf.predict(X_bow_test) y_pred # + [markdown] colab_type="text" id="2ANjKVUnZ1Y4" # #### a. Print the following # - i. Accuracy score # - ii. F1 score # - iii. Average precision score # - iv. Average recall score # - v. Tip: Make sure you are familiar with all of them. How would you expect the # things to work for the multi-label scenario? Read about micro/macro/weighted # averaging # # - Three metrics are aavilable for evaluation in multiclass classification - macro, micro and weigted.Here, we are using weighted as the parameter # # "macro" simply calculates the mean of the binary metrics, giving equal weight to each class. In problems where infrequent classes are nonetheless important, macro-averaging may be a means of highlighting their performance. On the other hand, the assumption that all classes are equally important is often untrue, such that macro-averaging will over-emphasize the typically low performance on an infrequent class. # # "weighted" accounts for class imbalance by computing the average of binary metrics in which each class’s score is weighted by its presence in the true data sample. # # "micro" gives each sample-class pair an equal contribution to the overall metric (except as a result of sample-weight). Rather than summing the metric per class, this sums the dividends and divisors that make up the per-class metrics to calculate an overall quotient. Micro-averaging may be preferred in multilabel settings, including multiclass classification where a majority class is to be ignored. # # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="wtZL2mF0Zhdd" outputId="f3011b94-8474-4402-a531-6de14e01784c" #Multilabel Confusion Matrix print(multilabel_confusion_matrix(y_test_mlb, y_pred)) # + colab={} colab_type="code" id="UB1CScw1Zkx2" #Classification Report report = classification_report(y_test_mlb, y_pred, output_dict=True, zero_division=1) # + colab={"base_uri": "https://localhost:8080/", "height": 359} colab_type="code" id="3iTQM_VrZocC" outputId="c8a78b70-a7a4-4bdf-86c9-ba83f88d94b9" #DataFrame to store Classification Report cr_df = pd.DataFrame(report).transpose() cr_df.head(10) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="PjyQnhrIZrl2" outputId="48342edf-0ae9-48bb-f996-f8370fc2c7b6" #Accuracy score print(accuracy_score(y_test_mlb, y_pred)) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="ODq3JesJZutz" outputId="331b1d7b-a7a2-4efa-c5df-ce5d7a5b798b" #F1 score print(f1_score(y_test_mlb, y_pred, average='weighted')) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="64ZnlgVSZygl" outputId="468f296f-54e0-4610-fee6-5f21c079032f" #Precision score print(precision_score(y_test_mlb, y_pred, average='weighted', zero_division=1)) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="kayREZ-uZ0H4" outputId="4a43806b-f66f-4524-d14d-2774fdff21a2" # Recall score print(recall_score(y_test_mlb, y_pred, average='weighted')) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="6xlX6Zk9aBXK" outputId="52d643cc-2b52-4f8a-bedf-7e4553dfa0fb" #Average Precision score print(average_precision_score(y_test_mlb, y_pred, average='weighted')) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="JtNMQG-KaE4A" outputId="f989f771-2309-443d-ac25-4686f16cdab7" #Average Recall score #support is the number of samples of the true positives that lie in that class. #avearge of the recall for each calss for the suport for the class weighted by total support for all classes sum((cr_df.iloc[0:80]['recall']) * (cr_df.iloc[0:80]['support']))/ sum(cr_df.iloc[0:80]['support']) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="h6so1SRYaIJV" outputId="b68a3b71-0656-4145-9fef-8876ffb8ff76" #ROC-AUC score print(roc_auc_score(y_test_mlb, y_pred, average='weighted')) # + colab={"base_uri": "https://localhost:8080/", "height": 136} colab_type="code" id="XUVwfp-4Ffhg" outputId="f9ce3d8a-6a37-473d-ece1-71ebf29eeb35" ### 10. Print true label and predicted label for any five examples (7.5 points) ##### True labels for five examples y_test_mlb # + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="aMFTeCBvZwpA" outputId="68a63fd1-c5b5-4b70-9e48-f82788ef905c" #Inverse Transform multiclass masked labels to true labels y_test_labels = mlb.inverse_transform(y_test_mlb) y_test_labels[0:5] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="aeXsXoKhaRtB" outputId="2eac363d-b688-4627-a281-7ea80fa7ca2e" y_test[0:5] # + colab={"base_uri": "https://localhost:8080/", "height": 136} colab_type="code" id="cGNxMuXxaO57" outputId="c0e05009-ed94-4a19-9a1d-811cda50cca2" ##### Predicted labels for five examples y_pred # + colab={"base_uri": "https://localhost:8080/", "height": 357} colab_type="code" id="Zf7iNNwEaVNS" outputId="6fd8e2ec-4ad0-41d0-815b-0ea52ff69f94" #Predicted Probabilities for test dataset proba = OnevsRest_clf.predict_proba(X_bow_test) proba[0] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="hUy5hfTjaX54" outputId="d5121f99-d846-4ff4-a155-c0bdfab019a0" #Inverse Transform multiclass probabilities to predicted labels usingig the probabilities above 0.5 threshold bitarray = OnevsRest_clf.label_binarizer_.inverse_transform(proba, threshold=0.5) classnames = mlb.inverse_transform(bitarray) classnames[0:6] # + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="5Vb6B2uFabfY" outputId="965369aa-d9a1-40df-9e5d-2473b9fcbf2f" #Inverse Transform multiclass masked labels to predicted labels y_pred_labels = mlb.inverse_transform(y_pred) y_pred_labels[0:6] # + [markdown] colab_type="text" id="1Ak0pb5Qad5N" # #### Observation: # - Train accuracy is 21.2% and Test accuracy is 16.1% # - We are not able to get good accuracy when we are applying Bag Of Words model using count vectorizer to extract features # - When we are combining four different target columns having mutiple classes, the classifier is not able to predict the classes accurately
Blog_Authorship_NLP.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # __Note__: This is best viewed on [NBViewer](http://nbviewer.ipython.org/github/tdhopper/stigler-diet/blob/master/content/articles/2015-07-30-sampling-from-a-hierarchical-dirichlet-process.ipynb). It is part of a series on [Dirichlet Processes and Nonparametric Bayes](https://github.com/tdhopper/notes-on-dirichlet-processes). # # %matplotlib inline # # Sampling from a Hierarchical Diriclet Process # # [As we saw earlier](http://stiglerdiet.com/blog/2015/Jul/28/dirichlet-distribution-and-dirichlet-process/) the Dirichlet process describes the _distribution_ of a random probability distribution. The Dirichlet process takes two parameters: a base distribution $H_0$ and a dispersion parameter $\alpha$. A sample from the Dirichlet process is itself a probability distribution that _looks like_ $H_0$. On average, the larger $\alpha$ is, the closer a sample from $\text{DP}(\alpha H_0)$ will be to $H_0$. # # Suppose we're feeling masochistic and want to input a distribution sampled from a Dirichlet process as base distribution to a new Dirichlet process. (It will turn out that there are good reasons for this!) Conceptually this makes sense. But can we construct such a thing in practice? Said another way, can we build a sampler that will draw samples from a probability distribution drawn from these nested Dirichlet processes? We might initially try construct a sample (a probability distribution) from the first Dirichlet process before feeding it into the second. # # But recall that fully constructing a sample (a probability distribution!) from a Dirichlet process would require drawing a countably infinite number of samples from $H_0$ and from the beta distribution to generate the weights. This would take forever, even with Hadoop! # # [<NAME>, et al](http://danroy.org/papers/RoyManGooTen-ICMLNPB-2008.pdf) helpfully described a technique of using _stochastic memoization_ to construct a distribution sampled from a Dirichlet process in a just-in-time manner. This process provides us with the equivalent of the [Scipy `rvs`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.rvs.html) method for the sampled distribution. Stochastic memoization is equivalent to the [Chinese restaurant process](http://www.cs.princeton.edu/courses/archive/fall07/cos597C/scribe/20070921.pdf): sometimes you get seated an an occupied table (i.e. sometimes you're given a sample you've seen before) and sometimes you're put at a new table (given a unique sample). # # Here is our memoization class again: # + from numpy.random import choice from scipy.stats import beta class DirichletProcessSample(): def __init__(self, base_measure, alpha): self.base_measure = base_measure self.alpha = alpha self.cache = [] self.weights = [] self.total_stick_used = 0. def __call__(self): remaining = 1.0 - self.total_stick_used i = DirichletProcessSample.roll_die(self.weights + [remaining]) if i is not None and i < len(self.weights) : return self.cache[i] else: stick_piece = beta(1, self.alpha).rvs() * remaining self.total_stick_used += stick_piece self.weights.append(stick_piece) new_value = self.base_measure() self.cache.append(new_value) return new_value @staticmethod def roll_die(weights): if weights: return choice(range(len(weights)), p=weights) else: return None # - # Let's illustrate again with a standard normal base measure. We can construct a function `base_measure` that generates samples from it. # + from scipy.stats import norm base_measure = lambda: norm().rvs() # - # Because the normal distribution has continuous support, we can generate samples from it forever and we will never see the same sample twice (in theory). We can illustrate this by drawing from the distribution ten thousand times and seeing that we get ten thousand unique values. # + from pandas import Series ndraws = 10000 print "Number of unique samples after {} draws:".format(ndraws), draws = Series([base_measure() for _ in range(ndraws)]) print draws.unique().size # - # However, when we feed the base measure through the stochastic memoization procedure and then sample, we get many duplicate samples. The number of unique samples goes down as $\alpha$ increases. # + norm_dp = DirichletProcessSample(base_measure, alpha=100) print "Number of unique samples after {} draws:".format(ndraws), dp_draws = Series([norm_dp() for _ in range(ndraws)]) print dp_draws.unique().size # - # At this point, we have a function `dp_draws` that returns samples from a probability distribution (specifically, a probability distribution sampled from $\text{DP}(\alpha H_0)$). We can use `dp_draws` as a base distribution for another Dirichlet process! norm_hdp = DirichletProcessSample(norm_dp, alpha=10) # How do we interpret this? `norm_dp` is a sampler from a probability distribution that looks like the standard normal distribution. `norm_hdp` is a sampler from a probability distribution that "looks like" the distribution `norm_dp` samples from. # # Here is a histogram of samples drawn from `norm_dp`, our first sampler. import matplotlib.pyplot as plt pd.Series(norm_dp() for _ in range(10000)).hist() _=plt.title("Histogram of Samples from norm_dp") # And here is a histogram for samples drawn from `norm_hdp`, our second sampler. pd.Series(norm_hdp() for _ in range(10000)).hist() _=plt.title("Histogram of Samples from norm_hdp") # The second plot doesn't look very much like the first! The level to which a sample from a Dirichlet process approximates the base distribution is a function of the dispersion parameter $\alpha$. Because I set $\alpha=10$ (which is relatively small), the approximation is fairly course. In terms of memoization, a small $\alpha$ value means the stochastic memoizer will more frequently reuse values already seen instead of drawing new ones. # # This nesting procedure, where a sample from one Dirichlet process is fed into another Dirichlet process as a base distribution, is more than just a curiousity. It is known as a [Hierarchical Dirichlet Process, and it plays an important role in the study of Bayesian Nonparametrics](http://www.cs.berkeley.edu/~jordan/papers/hdp.pdf) (more on this in a future post). # # Without the stochastic memoization framework, constructing a sampler for a hierarchical Dirichlet process is a daunting task. We want to be able to draw samples from a distribution drawn from the second level Dirichlet process. However, to be able to do that, we need to be able to draw samples from a distribution sampled from a _base distribution of the second-level Dirichlet process_: this base distribution is a _distribution drawn from the first-level Dirichlet process_. # # Though it appeared that we would need to be able to fully construct the first level sample (by drawing a countably infinite number of samples from the first-level base distribution). However, stochastic memoization allows us to only construct the first distribution just-in-time as it is needed at the second-level. # # We can define a Python class to encapsulate the Hierarchical Dirichlet Process as a base class of the Dirichlet process. class HierarchicalDirichletProcessSample(DirichletProcessSample): def __init__(self, base_measure, alpha1, alpha2): first_level_dp = DirichletProcessSample(base_measure, alpha1) self.second_level_dp = DirichletProcessSample(first_level_dp, alpha2) def __call__(self): return self.second_level_dp() # Since the Hierarchical DP is a Dirichlet Process inside of Dirichlet process, we must provide it with both a first and second level $\alpha$ value. norm_hdp = HierarchicalDirichletProcessSample(base_measure, alpha1=10, alpha2=20) # We can sample directly from the probability distribution drawn from the Hierarchical Dirichlet Process. pd.Series(norm_hdp() for _ in range(10000)).hist() _=plt.title("Histogram of samples from distribution drawn from Hierarchical DP") # `norm_hdp` is not equivalent to the Hierarchical Dirichlet Process; it samples from a _single distribution_ sampled from this HDP. Each time we instantiate the `norm_hdp` variable, we are getting a sampler for a unique distribution. Below we sample five times and get five different distributions. for i in range(5): norm_hdp = HierarchicalDirichletProcessSample(base_measure, alpha1=10, alpha2=10) _=pd.Series(norm_hdp() for _ in range(100)).hist() _=plt.title("Histogram of samples from distribution drawn from Hierarchical DP") _=plt.figure() # In a later post, I will discuss how these tools are applied in the realm of Bayesian nonparametrics.
2015-07-30-sampling-from-a-hierarchical-dirichlet-process.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Reading cell_image dataset and saving the data for future purposes # ### Brief overview # 1. With the help of open CV i am reading each and every cell images given in the dataset. # 2. I am dividing data in two parts : parasitized_data and uninfected_data using os library # 3. After this i am storing contents of parasitized_data and uninfected_data in a list named 'data' and image labels are stored in a different list named 'labels'. # 4. With the help of matplotlib.pyplot i am testing that my data list is able to plot the image or not. # # 5. At last i am converting data and labels list into a numpy array for faster processing and shuffling the contents image_data and labels respectively so that it can be passed on to further processing area of the project # + import numpy as np import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os # - import cv2 import matplotlib.pyplot as plt import seaborn as sns import os from PIL import Image from keras.preprocessing.image import img_to_array #from keras.preprocessing.image import load_img #from keras.utils import np_utils # + # Here we are simply storing the labels of the images in parasitized_data and uninfected_data parasitized_data = os.listdir('C:/<prefix_path>/cell_images/Parasitized/') print(parasitized_data[:10]) #printing first 10 image's labels of parasitized_data uninfected_data = os.listdir('C:/<prefix_path>/cell_images/Uninfected/') print('\n') print(uninfected_data[:10]) #printing first 10 image's labels of uninfected_data # + # Here we are resizing the images and storing the image data into a list called 'data' and labels are stored in list called 'labels' data = [] labels = [] for img in parasitized_data: try: img_read = plt.imread('C:/<prefix_path>/slop/cell_images/Parasitized/' + "/" + img) img_resize = cv2.resize(img_read, (50, 50)) img_array = img_to_array(img_resize) data.append(img_array) labels.append(1) except: None for img in uninfected_data: try: img_read = plt.imread('C:/<prefix_path>/slop/cell_images/Uninfected/' + "/" + img) img_resize = cv2.resize(img_read, (50, 50)) img_array = img_to_array(img_resize) data.append(img_array) labels.append(0) except: None # + # Taking a short test to check if we are able to retrieve images from data plt.imshow(data[794]) plt.show() # - # convertion of list into numpy array for faster processing image_data = np.array(data) labels = np.array(labels) #shuffling contents image_data and labels respectively idx = np.arange(image_data.shape[0]) np.random.shuffle(idx) image_data = image_data[idx] labels = labels[idx]
Scripts/Read_cell_images.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # MSQ: Necessary Structures # # This notebook outlines and creates the necessary code structures to implement the MSQ. # # NOTE: this code is written in Python 2.7.x, but all attempts are made to use Python3-compliant syntax. # Import relevant libraries from __future__ import division, print_function import numpy as np import scipy.stats as stats from scipy.stats.mstats import mquantiles from scipy.optimize import minimize # The following is a very compact description of the method. See the authors' paper for a much more in-depth discussion. # # ## Main Method Objects # # The key idea is that we define two objects: # # - a set of *quantiles* of some distribution, denote this $\mathbf{q}$, of size $s$; # - a set of *functions of quantiles*, which map a set of quantiles to a vector of reals. denote this $\Phi$. # # This skips a lot of details. For example: # # - the above set of quantiles and function of quantiles should be thought of as being applied to a *vector* of random variables of length $J$. # - For each $j$ random variable, the functions of quantiles should produce a vector of length $M$. Thus the total number of elements in the final vector of reals will be $JM$. # - Finally, technically the $\Phi$ vector of functions of quantiles is a cocmposition of two functions, $\mathbf{g}, \mathbf{h}$ in the text. I will use $\Phi$ in the following. # # That said, I will use the minimal notation needed to describe the process, and use an example to explore and illustate the details of the process. # # Assume we have two things: # # 1. A set of M vectors of emperical realizations of the DGP we are trying to fit -- i.e. empirical distributions drawn from the true unknown DGP # - call these the "empirical" values # - denote empirical quantiles of these data $\hat{\mathbf{q}}$ # - denote empirical functions of these quantiles $\hat{\Phi}_j$ # 2. A parameterized, simulation-based DGP, from which we can simulate draws conditional on a parameter $\theta$, # - call these the "theoretical" values # - denote theoretical quantiles of these data $\mathbf{q}_{\theta}$ # - denote theoretical functions of these quantiles $\Phi_{\theta, j}$ # # # We will explore this in more detail in the example below. # # To fit the theoretical model to the empirical data, choose the parameter $\theta$ to minimize the following quadratic objective function: # # $$ # \hat{\theta} = \underset{\theta \in \Theta}{\textrm{argmin}} \; \left(\hat{\mathbf{\Phi}} - \mathbf{\Phi}_{\theta}\right)^{\textrm{T}} \mathbf{W}_{\theta} \left(\hat{\mathbf{\Phi}} - \mathbf{\Phi}_{\theta}\right). # $$ # # Here $\mathbf{W}_{\theta}$ is a symmetric positive definite weighting matrix. # # In addition, the bolded $\Phi$ values are defined as the "stacked" vectors, for each of the $J$ random variables: # # $$ # \mathbf{\Phi} = \left(\Phi_{1}^{\textrm{T}}, \Phi_{2}^{\textrm{T}}, ..., \Phi_{j}^{\textrm{T}}, ..., \Phi_{J}^{\textrm{T}} \right)^{\textrm{T}} # $$ # # # for both $\hat{\Phi}$ and $\Phi_{\theta}$. # ## Illustration By Example # # We'll use the example of the $\alpha$-stable distribution to demonstrate the estimation method. # # As discussed in the notebook "An Aside on Alpha Stable Distributions," the $\alpha$-stable distribution is a four-parameter distribution denoted $S(\alpha, \beta, \mu, \sigma)$ where: # # - $\alpha \in (0,2]$, is the "tail index:" it measures the thickness of tails of the distribution. # - $\beta \in [-1,1]$ is the "skewness" parameter. # - $\sigma \in \mathbb{R}^{+}$ is the "scale" or "dispersion" parameter # - $\mu \in \mathbb{R}$ is the location parameter # # There are three special cases of the family of stable distributions: # # - Normal: $S(\alpha=2, \beta=NA, \frac{\sigma}{\sqrt{2}}, \mu) \rightarrow \mathscr{N}(\mu, \sigma^2)$ # - Cauchy: $S(\alpha=1, \beta=0, \sigma, \mu)$ # - Levy: $S(\alpha=0.5, \beta=1, \sigma, \mu)$ # # # Importantly, the $\alpha$ parameter governs whether moments of the distribution exist. For $X \sim S(\alpha, \beta, \mu, \sigma)$: # # $$\mathbb{E} \left[ X^{p}\right] \lt \infty \; \forall p \lt \alpha .$$ # # # We use a quantiles-based estimator defined by McCulloch (1986). # # Let's define the two functions of parameters: # # * The theoretical function of parameters, $\Phi_{\theta}$: # # $$ # \Phi_{\theta}=\left( # \begin{array}{c} # \frac{ q_{0.95, \theta} \,-\, q_{0.05, \theta} } { q_{0.75, \theta} \,-\, q_{0.25, \theta} } \\ # \frac{ (q_{0.95, \theta} \,-\, q_{0.5, \theta}) \,+\, (q_{0.05, \theta} \,-\, q_{0.5, \theta}) } { q_{0.95, \theta} \,-\, q_{0.05, \theta} } \\ # (q_{0.75, \theta} \,-\, q_{0.25, \theta}) \sigma \\ # q_{0.5, \theta} \sigma + \mu # \end{array} # \right) # $$ # # # * The empirical function of parameters, $\hat{\Phi}$: # # $$ # \hat{\Phi}=\left( # \begin{array}{c} # \frac{ \hat{q}_{0.95} \,-\, \hat{q}_{0.05} } { \hat{q}_{0.75} \,-\, \hat{q}_{0.25} } \\ # \frac{ (\hat{q}_{0.95} \,-\, \hat{q}_{0.5}) \,+\, (\hat{q}_{0.05} \,-\, \hat{q}_{0.5}) } { \hat{q}_{0.95} \,-\, \hat{q}_{0.05} } \\ # (\hat{q}_{0.75} \,-\, \hat{q}_{0.25}) \\ # \hat{q}_{0.5} # \end{array} # \right) # $$ # # # Dominicy and Verdas (2013) follow McCulloch (1986) and standardize the empirical data which comprises $\hat{\Phi}$, and thus additionally standardize the theoretical measurements. # # The theoretical function of parameters $\Phi_{\theta}$ is obtained by drawing a simulated sample of data from the distribution implied by $\theta$, which we will denote as $\overset{\sim}{\Phi}_{\theta}$. # # Finally, to represent $\Phi_{\theta}$ we draw $R$ simulation paths and find the average value: # # $$ # \overset{\sim}{\Phi}_{\theta}^{R} = \frac{1}{R}\sum_{r=1}^{R} \overset{\sim}{\Phi}_{\theta}^{r}. # $$ # # We find the $\hat{\theta}$ by minimizing the quadratic objective: # # $$ # \hat{\theta} = \underset{\theta \in \Theta}{\textrm{argmin}} \; \left(\hat{\mathbf{\Phi}} - \mathbf{\overset{\sim}{\Phi}}_{\theta}^{R} \right)^{\textrm{T}} \mathbf{W}_{\theta} \left(\hat{\mathbf{\Phi}} - \mathbf{\overset{\sim}{\Phi}}_{\theta}^{R}\right). # $$ # # # There are a few more details which we cover as we proceed. # # # ## Code Structures # + # Let's define some functions: def h(q): # Assume qhat = qhat_{.05}, qhat_{.25}, qhat_{.50}, qhat_{.75}, qhat_{.95} return np.array([ q[-1] - q[0], q[-1] - 2 * q[2] + q[0], q[-2] - q[1], q[2] ]) def g(q): # Assume qhat = qhat_star_{.05}, qhat_star_{.25}, qhat_star_{.50}, qhat_star_{.75}, qhat_star_{.95} return np.array([ 1.0 / (q[-2] - q[1]), 1.0 / (q[-1] - q[0]), 1.0, 1.0 ]) # Test this: def Phi_hat_alt(q): return h(q) * g(q) def Phi_hat(q): ''' q is a vector of quantiles in ascending order. The function will error-check for this. ''' # Check if q is in order: #assert np.all(np.diff(q) >= 0), "Quantiles q are not in ascending order: q="+str(q) return np.array([ (q[-1] - q[0]) / (q[-2] - q[1]), (q[-1] - 2 * q[2] + q[0]) / (q[-1] - q[0]), q[-2] - q[1], q[2] ]) def Phi_theta_plain(q, mu, sigma): ''' q is a vector of quantiles in ascending order. The function will error-check for this. mu and sigma are float values for the mu, sigma values in the function. ''' # Assert that q is in ascending order! #assert np.all(np.diff(q) >= 0), "Quantiles q are not in ascending order: q="+str(q) return np.array( [ (q[-1] - q[0]) / (q[-2] - q[1]), (q[-1] - 2 * q[2] + q[0]) / (q[-1] - q[0]), (q[-2] - q[1]) * sigma, q[2] * sigma + mu] ) def Phi_theta(q, theta): ''' q is a vector of quantiles in ascending order. The function will error-check for this. mu and sigma are float values for the mu, sigma values in the function. ''' # Assert that q is in ascending order! #assert np.all(np.diff(q) >= 0), "Quantiles q are not in ascending order: q="+str(q) # Recall: #theta = {'alpha':theta_vec[0], # 'beta':theta_vec[1], # 'mu':theta_vec[2], # 'sigma':theta_vec[3]} if theta[0] != 1.0: zeta = theta[2] + theta[1]*theta[3]*np.tan(np.pi * theta[0] / 2.0) # zeta= mu + beta * sigma * tan( pi * alpha / 2) else: zeta = theta[2] # mu return np.array( [ (q[-1] - q[0]) / (q[-2] - q[1]), (q[-1] - 2 * q[2] + q[0]) / (q[-1] - q[0]), (q[-2] - q[1]) * theta[3], q[2] * theta[3] + zeta] ) def Phi_theta_dict(q, theta): ''' q is a vector of quantiles in ascending order. The function will error-check for this. mu and sigma are float values for the mu, sigma values in the function. ''' # Assert that q is in ascending order! #assert np.all(np.diff(q) >= 0), "Quantiles q are not in ascending order: q="+str(q) # Recall: #theta = {'alpha':theta_vec[0], # 'beta':theta_vec[1], # 'mu':theta_vec[2], # 'sigma':theta_vec[3]} if theta['alpha'] != 1.0: zeta = theta['mu'] + theta['beta']*theta['sigma']*np.tan(np.pi * theta['alpha'] / 2.0) # zeta= mu + beta * sigma * tan( pi * alpha / 2) else: zeta = theta['mu'] # mu return np.array( [ (q[-1] - q[0]) / (q[-2] - q[1]), (q[-1] - 2 * q[2] + q[0]) / (q[-1] - q[0]), (q[-2] - q[1]) * theta['sigma'], q[2] * theta['sigma'] + zeta] ) # Generate data def generate_data(theta, N, R, rng): ''' The parameter theta contains the alpha-stable distribution parameters. theta must be a dict with keys: alpha, beta, mu, sigma. N is length of vector of IID draws, R is number of vector. rng is a numpy RandomState instance. seed is for a random number generator.''' #assert theta['alpha'] > 0 and theta['alpha'] <= 2, "alpha not in (0,1]: alpha = "+str(theta['alpha']) #assert theta['beta'] >= -1 and theta['beta'] <= 1, "beta not in [-1,1]: beta = "+str(theta['beta']) #assert theta['sigma'] >= 0 , "sigma not >= 0: sigma = "+str(theta['sigma']) # Generate the data return stats.levy_stable.rvs(alpha=theta['alpha'], beta=theta['beta'], loc=theta['mu'], scale=theta['sigma'], size=(N, R), random_state=rng) def generate_data_vec(theta, N, R, rng, testing=False): ''' Same as "generate_data" but with theta as an ordered numpy vector. The parameter theta contains the alpha-stable distribution parameters. theta values must be in the order: alpha, beta, mu, sigma. N is length of vector of IID draws, R is number of vector. rng is a numpy RandomState instance. seed is for a random number generator.''' #if testing: # assert theta[0] > 0 and theta[0] <= 2, "alpha not in (0,1]: alpha = "+str(theta[0]) # assert theta[1] >= -1 and theta[1] <= 1, "beta not in [-1,1]: beta = "+str(theta[1]) # assert theta[3] >= 0 , "sigma not >= 0: sigma = "+str(theta[3]) # Generate the data return stats.levy_stable.rvs(alpha=theta[0], beta=theta[1], loc=theta[2], scale=theta[3], size=(N, R), random_state=rng) def find_emperical_quantiles(data, q): ''' data is a 1D or 2D vector of data, q are the quantiles. ''' # Draw quantiles from the data. NOTE: Assume that data is (N,R) # shape. Note that returned values will have shape: (len(q), R) # NOTE2: this is only for exposition; just directly use mquantiles. return mquantiles(a=data, prob=q, alphap=0.4, betap=0.4, axis=0) def find_theoretical_quantiles_squiggle_R(theta, N, R, q, rng): ''' Construct the thereotical quantiles by simulation. Given theta, N, R, q, and rng, return a vector of the five quantiles associated with this distribution. Parameters: ----------- theta: dict of stable distribution parameters. Must be a dict with keys: alpha, beta, mu, sigma N: int, number of observations per simulation R: int, number of simulations to run q: vector of floats; the quantiles values. Assumed in ascending order. rng: a NumPy RandomState object. Allows reproducibility. Returns: ----------- q_hat: vector of floats, the average of quantilels over R simulations ''' # Assert that q is in ascending order! #assert np.all(np.diff(q) > 0), "Quantiles q are not in ascending order: q="+str(q) # Generate data: # NOTE: data is (N,R) shape: data = generate_data(theta, N, R, rng) # Find the quantiles: # Draw quantiles from the data. NOTE: Assume that data is (N,R) # shape. Note that returned values will have shape: (len(q), R) quantiles_R = mquantiles(a=data, prob=q, alphap=0.4, betap=0.4, axis=0) # Average over each quantile; the resulting vector will be #in ascending order: return np.apply_along_axis(func1d=np.mean, axis=1, arr=quantiles_R) #theory_quantiles def find_theoretical_quantiles_squiggle_R_vec(theta_vec, N, R, q, rng, testing=False): ''' Construct the thereotical quantiles by simulation. Given theta, N, R, q, and rng, return a vector of the five quantiles associated with this distribution. Parameters: ----------- theta: vector of stable distribution parameters. Must be a numpy array with floats in this order: alpha, beta, mu, sigma N: int, number of observations per simulation R: int, number of simulations to run q: vector of floats; the quantiles values. Assumed in ascending order. rng: a NumPy RandomState object. Allows reproducibility. Returns: ----------- q_hat: vector of floats, the average of quantilels over R simulations ''' # Assert that q is in ascending order! #if testing: # assert np.all(np.diff(q) > 0), "Quantiles q are not in ascending order: q="+str(q) # Generate data: # NOTE: data is (N,R) shape: data = generate_data_vec(theta_vec, N, R, rng) # Find the quantiles: # Draw quantiles from the data. NOTE: Assume that data is (N,R) # shape. Note that returned values will have shape: (len(q), R) quantiles_R = mquantiles(a=data, prob=q, alphap=0.4, betap=0.4, axis=0) # Average over each quantile; the resulting vector will be #in ascending order: return np.apply_along_axis(func1d=np.mean, axis=1, arr=quantiles_R) #theory_quantiles = def sparsity_function(): pass def G_hat(): # Diagonal matrix # Diagonal elements are g( q_hat^{*}_{j} ) # Full thing: # # g(q_hat^{*}) = ( g(q_hat^{*}_{1})^T, g(q_hat^{*}_2)^T, ... , g(q_hat^{*}_{J})^T )^T # pass # + # Next steps: # Generate a sample of data from a "mystery dist" # Choose starting theta # run estimation *step 1 only*. q = [0.05, 0.25, 0.5, 0.75, 0.95] mystery_theta = {'alpha':1.5, 'beta':-0.5, 'mu':0.5, 'sigma':1.2} # Cauchy: alpha=1, beta=0, loc=mu=0.0, scale=sigma/2.0 = 1.0/2.0 # Using raw data: # array([ 1.33024131, -0.57463142, -0.16851961, 0.96667289]) # Using standardized sample, with sigma=std(data): #array([ 1.33023827, -0.57449001, 0.06295755, 0.21148216]) ''' Optimization terminated successfully. (Exit mode 0) Current function value: 3.93901180299e-08 Iterations: 15 Function evaluations: 95 Gradient evaluations: 15 Took:7.11473720074 min. Out[7]: fun: 3.9390118029863406e-08 jac: array([-0.00065797, 0.00016368, 0.00025707, 0.00022284, 0. ]) message: 'Optimization terminated successfully.' nfev: 95 nit: 15 njev: 15 status: 0 success: True x: array([ 1.33023827, -0.57449001, 0.06295755, 0.21148216]) ''' # SO NOTE: THIS APPEARS WRONG! using std. # Next: # - try with 'use sigma/mu to stdize sample' # - update W_theta # - ...email # RNG setup: seed0 = 567891234 rng = np.random.RandomState(seed0) # Draw sample of mystery data: Msample = 200 empirical_data = generate_data(theta=mystery_theta, N=Msample, R=1, rng=rng) #N=10000 #R=200 N=7500 R=150 # Standardize the sample? # Need to ask authors about this! z_empirical_data = (empirical_data - np.mean(empirical_data) ) / np.std(empirical_data) # NOTE: confusion over what "standardize the sample" means. Here are there options: # 1. don't standardize # 2. standardize using mean, std. # 3. for each theta_check, after generatefs all the samples, # figure out quantiles, and then a,b,mu, sig, use *that* mu andd sig to normalize. # Still not clear why would do this (3) one. But whatevs. # SO, start and try out the (2) version...yes? # Process: # Form the quantiles over the data # Form W0 # Choose a theta0 # Generate theta_squiggle_R from theta0 # Find the quandratic value # Iterate # Get data quantiles: W0 = np.eye(4) #empirical_q = mquantiles(a=z_empirical_data, prob=q, alphap=0.4, betap=0.4, axis=0).compressed() # Remove masking empirical_q = mquantiles(a=empirical_data, prob=q, alphap=0.4, betap=0.4, axis=0).compressed() # Remove masking theta_hat = Phi_hat(empirical_q) theta0 = {'alpha':1.2, 'beta':-0.25, 'mu':0.5, 'sigma':0.5} # Levy: alpha=0.5, beta=1.0, loc=mu, scale=sigma/2.0 # Note: *internal* to the function, unpack these! theta_vec = np.array([theta0['alpha'], theta0['beta'], theta0['mu'], theta0['sigma'], ]) def quadratic_objective_old_dict_style(theta, W, theta_hat, seed, N, R, qvals): #unpack: #theta = {'alpha':theta_vec[0], # 'beta':theta_vec[1], # 'mu':theta_vec[2], # 'sigma':theta_vec[3]} # Generate theta_squiggle_R from theta0: rng = np.random.RandomState(seed) theta_squiggle_R_q = find_theoretical_quantiles_squiggle_R(theta=theta, N=N, R=R, q=qvals, rng=rng) theta_squiggle_R = Phi_theta_dict(q=theta_squiggle_R_q, theta=theta) # mu=theta['mu'], sigma=theta['sigma']) theta_minus_theta = theta_hat - theta_squiggle_R return np.dot(theta_minus_theta, W0).dot(theta_minus_theta) def quadratic_objective(theta_vec, W, theta_hat, seed, N, R, qvals): # Generate theta_squiggle_R from theta0: # NOTE: this takes in the "theta_hat" already calculated. Need to think # about whether to *always* recalcuate the the theta_hat based on the # empirical data, **standardized by the theoretical vavlues**. # I *presume* that will be more expensive. rng = np.random.RandomState(seed) theta_squiggle_R_q = find_theoretical_quantiles_squiggle_R_vec(theta_vec=theta_vec, N=N, R=R, q=qvals, rng=rng) theta_squiggle_R = Phi_theta(q=theta_squiggle_R_q, theta=theta_vec) # mu=theta_vec[2], sigma=theta_vec[3]) theta_minus_theta = theta_hat - theta_squiggle_R return np.dot(theta_minus_theta, W0).dot(theta_minus_theta) def quadratic_objective_vec_recalculate_theta_hat(theta_vec, W, seed, N, R, qvals, verbose=False, the_data=empirical_data): # Generate theta_squiggle_R from theta0: # This version takes in the empirical data and *always* recalcuates # the the theta_hat based on the # empirical data, **standardized by the theoretical vavlues**. # I *presume* that will be more expensive. # Note that I am *binding* the empirical data to the function. Will see how that goes... # Recall: # theta = {'alpha':theta_vec[0], # 'beta':theta_vec[1], # 'mu':theta_vec[2], # 'sigma':theta_vec[3]} if verbose: print("mu="+str(theta_vec[2])) print("sigma="+str(theta_vec[3])) # First find theta-hat: standardized_data = (the_data - theta_vec[2]) / theta_vec[3] # Now find the quantiles: empirical_q = mquantiles(a=standardized_data, prob=q, alphap=0.4, betap=0.4, axis=0).compressed() # Remove masking # *now* find the theta-hat: theta_hat = Phi_hat(empirical_q) # Now rest of the run: rng = np.random.RandomState(seed) theta_squiggle_R_q = find_theoretical_quantiles_squiggle_R_vec(theta_vec=theta_vec, N=N, R=R, q=qvals, rng=rng) theta_squiggle_R = Phi_theta(q=theta_squiggle_R_q, theta=theta_vec) #mu=theta_vec[2], sigma=theta_vec[3]) theta_minus_theta = theta_hat - theta_squiggle_R return np.dot(theta_minus_theta, W0).dot(theta_minus_theta) seed1=1236789 quadratic_objective(theta_vec, W0, theta_hat, seed1, N, R, q) # Let's examine: #theta_vec_true = np.array([theta0['alpha'], theta0['beta'], theta0['mu'], theta0['sigma'], ]) print(quadratic_objective(theta_vec, W0, theta_hat, seed1, N, R, q)) print(quadratic_objective_old_dict_style(theta0, W0, theta_hat, seed1, N, R, q)) print(quadratic_objective_vec_recalculate_theta_hat(theta_vec, W0, seed1, N, R, q)) # + theta_hat def G_theta(q): return np.diag(g(q)) def Omega_theta(q): return np.diag(h(q)) def Wstar_theta(q): pass g(empirical_q) h(empirical_q) #np.diag(g(empirical_q)) #np.diag(h(empirical_q)) #W0 #G_theta(empirical_q) Omega_theta(empirical_q) # - # Denote by $\hat{G}_j$ a M x M diagonal matrix with diagonal elements $g(\hat{q}_{j}^{*})$. # # We gather all these vectors into # $$g( \hat{q}^{*}) = \left( g(\hat{q}_{1}^{*})^{T}, ..., g(\hat{q}_{J}^{*})^{T} \right)^{T} $$ # # with the corresponding block diagonal JM x JM matrix # # $$\hat{G} = diag(diag(g(\hat{q}_{1}^{*}), ..., diag(g(\hat{q}_{J}^{*}))).$$ # # Similarly, let $G_{\theta}$ be a JM × JM diagonal matrix composed of J diagonal blocks, each of size M : # # $$G_{\theta} = diag(diag( g(q_{\theta,1}^{*} )), . . . , diag( g(q_{\theta,M}^{*} ))).$$ # # # A result: $\hat{G} \rightarrow G_{\theta}$ as ________. # # **Major Q:** what is the convergence iteration here? How do we go from $\hat{q}_{k}^{*} \rightarrow \hat{q}_{k+1}^{*}?$ # # **Are we doing the following?** # # - choose W0. # - estimate $\theta$ (and corresponding qs with $\theta$... # - *that's iteration k=1* # - **NOW**, use $theta$ to create $W_{theta,1}$ # - repeat from step 1 # - decide convergence on what criteria? # # # # ### Some Qs: # # - standardizing the sample # - construction of $\Phi_{\theta}$ in p237, what is role of $\zeta$? # # # # # WHERE AT: # # Updated the Phi_theta function to include the zeta value. # # **BUT** getting the wrong sign on mu. Need to think about -- see if can swtichc back and get "old"results. # # Also need to think more about iteration to $W_{\theta}$. Need to be careful about what exactly the iteration steps are. # # Need also to think aa # # Also need to email Qs. # + # NEW TRIAL: just trying out a "simple" two-step estimator. Key note: see Sheppard 6.4.1 # Recall: def quadratic_objective(theta_vec, W, theta_hat, seed, N, R, qvals): # Generate theta_squiggle_R from theta0: # NOTE: this takes in the "theta_hat" already calculated. Need to think # about whether to *always* recalcuate the the theta_hat based on the # empirical data, **standardized by the theoretical vavlues**. # I *presume* that will be more expensive. rng = np.random.RandomState(seed) theta_squiggle_R_q = find_theoretical_quantiles_squiggle_R_vec(theta_vec=theta_vec, N=N, R=R, q=qvals, rng=rng) theta_squiggle_R = Phi_theta(q=theta_squiggle_R_q, theta=theta_vec) # mu=theta_vec[2], sigma=theta_vec[3]) theta_minus_theta = theta_hat - theta_squiggle_R return np.dot(theta_minus_theta, W0).dot(theta_minus_theta) from time import time t0=time() near_zero = 1.0e-8 res = minimize(fun=quadratic_objective_vec_recalculate_theta_hat, x0=theta_vec, args=(W0, seed1, N, R, q), method='SLSQP', jac=None, bounds=[(near_zero, 2.0), (-1.0+near_zero, 1.0-near_zero), (None, None), (near_zero, None)], options={"disp":True} ) t1=time() print("Took:"+str( (t1-t0)/60. )+ " min.") try: print(res.x) print("printed res.x -- res is an object, x is attribute") except: print(res['x']) print("printed res['x'] -- res is a dict, x is key") # Next step: # Need to implement the 2-step estimator, with the recommended update of the W matrix. # + # Usign old version: from time import time t0=time() #quadratic_objective_vec near_zero = 1.0e-8 res = minimize(fun=quadratic_objective, x0=theta_vec, args=(W0, theta_hat, seed1, N, R, q), method='SLSQP', jac=None, bounds=[(near_zero, 2.0), (-1.0+near_zero, 1.0-near_zero), (None, None), (near_zero, None)], options={"disp":True} ) #res = minimize(fun=quadratic_objective, x0=theta_vec, args=(W0, theta_hat, seed1, N, R, q), method='SLSQP', # jac=None, bounds=[(0.51, 2.0), (-0.99999999, 0.9999999), (None, None), (0.0, None)], options={"disp":True} ) t1=time() print("Took:"+str( (t1-t0)/60. )+ " min.") res # + # USING THE NEW -ALWAYS-RECALCUALTE VERSION: from time import time t0=time() near_zero = 1.0e-12 res = minimize(fun=quadratic_objective_vec_recalculate_theta_hat, x0=theta_vec, args=(W0, seed1, N, R, q), method='SLSQP', jac=None, bounds=[(near_zero, 2.0), (-1.0+near_zero, 1.0-near_zero), (None, None), (near_zero, None)], options={"disp":True} ) t1=time() print("Took:"+str( (t1-t0)/60. )+ " min.") res # + # REsults with standardized-my-theory-values version: ''' Optimization terminated successfully. (Exit mode 0) Current function value: 6.39496039618e-07 Iterations: 9 Function evaluations: 60 Gradient evaluations: 9 Took:0.344144268831 min. Out[12]: fun: 6.3949603961751021e-07 jac: array([-0.00169004, -0.00146682, 0.001104 , 0.00482058, 0. ]) message: 'Optimization terminated successfully.' nfev: 60 nit: 9 njev: 9 status: 0 success: True x: array([ 1.35001977, -0.58735602, -0.09799538, 0.97669182]) ''' # [ 1.3334765 , -0.58013206, 0.034585 , 1.03876482]) # NEW: # 1.33501652, -0.5832553 , -0.31480513, 1.03965954 #TRUE: # # mystery_theta = {'alpha':1.5, # 'beta':-0.5, # 'mu':0.5, # So note that mu is not correct. # 'sigma':1.2} # Still not gotten great. # ======================================================= # REsults with data *not* standardized version: ''' Optimization terminated successfully. (Exit mode 0) Current function value: 5.65339794279e-08 Iterations: 10 Function evaluations: 63 Gradient evaluations: 10 Took:0.227895700932 min. Out[20]: fun: 5.6533979427881372e-08 jac: array([ -8.66875749e-04, 3.26018435e-04, -6.81478371e-05, -9.61340689e-04, 0.00000000e+00]) message: 'Optimization terminated successfully.' nfev: 63 nit: 10 njev: 10 status: 0 success: True x: array([ 1.35006237, -0.58585084, -0.14527886, 0.9652678 ]) ''' # REsults with data standardized by mean, stdev, version: ''' Optimization terminated successfully. (Exit mode 0) Current function value: 9.45908866437e-09 Iterations: 18 Function evaluations: 112 Gradient evaluations: 18 Took:0.31707701683 min. Out[16]: fun: 9.4590886643706467e-09 jac: array([ 4.14401579e-04, -5.15464206e-05, 1.52895583e-04, 1.10592089e-04, 0.00000000e+00]) message: 'Optimization terminated successfully.' nfev: 112 nit: 18 njev: 18 status: 0 success: True x: array([ 1.35011253, -0.5861334 , 0.06476111, 0.21112074]) ''' # + theta_minus_theta # + # Find the quandratic value: val = np.dot(theta_minus_theta, W0) val = np.dot(val, theta_minus_theta) val # - # # Appendix A: Next Extension # # Extensions: # # - Weighted empirical data.
in_progress/MSQ-Necessary-Structure.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os import csv total_months = 0 total_amount = 0 monthly_change = [] month_count = [] greatest_increase = 0 greatest_increase_month = 0 greatest_decrease = 0 greatest_decrease_month = 0 csvpath = os.path.join("..","main.py","budget_data.csv") with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) row = next(csvreader) previous_row = int(row[1]) total_months += 1 total_amount += int(row[1]) greatest_increase = int(row[1]) greatest_increase_month = row[0] for row in csvreader: total_months += 1 total_amount += int(row[1]) revenue_change = int(row[1]) - previous_row monthly_change.append(revenue_change) previous_row = int(row[1]) month_count.append(row[0]) if int(row[1]) > greatest_increase: greatest_increase = int(row[1]) greatest_increase_month = row[0] if int(row[1]) < greatest_decrease: greatest_decrease = int(row[1]) greatest_decrease_month = row[0] average_change = sum(monthly_change)/ len(monthly_change) highest = max(monthly_change) lowest = min(monthly_change) print(f"Financial Analysis") print(f"---------------------------") print(f"Total Months: {total_months}") print(f"Total: ${total_amount}") print(f"Average Change: ${average_change:.2f}") print(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})") print(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})") output_file = os.path.join('budget_data_revised.txt') with open(output_file, 'w',) as txtfile: txtfile.write(f"Financial Analysis\n") txtfile.write(f"---------------------------\n") txtfile.write(f"Total Months: {total_months}\n") txtfile.write(f"Total: ${total_amount}\n") txtfile.write(f"Average Change: ${average_change}\n") txtfile.write(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})\n") txtfile.write(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})\n") # -
PyBank/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/jajinkya/Macroeconomic-factors-influencing-emission-of-Carbon-Dioxide/blob/main/C02_emission.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="Skan2yJX3CYK" # ### Data Retrieval and Basic Operations # + id="ORJhDiqlgdqw" outputId="293d5b80-75b1-4c8f-935c-9832c0a34515" colab={"base_uri": "https://localhost:8080/"} # cd "/content/drive/My Drive/Global Warming/co2_prediction" # + id="bh2TOrvw2xbe" outputId="54276a56-4746-474f-f09c-b5921fd02da9" colab={"base_uri": "https://localhost:8080/"} #import required library import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline # + id="rtm9OD0zpRzv" root_folder = "/content/drive/My Drive/Global Warming/co2_prediction/" def read_merge_csv(root_folder, year="2014"): dfs=[] for subdir, dir, files in os.walk(root_folder): for file in files: filename = file.split(".")[0] # prepare name for column df = pd.read_csv(root_folder+str(file)) df.columns.values[0] = "geo" # considering only csv's having more than 50 countries if year in df.columns and df.shape[0]>50: df = df[["geo", year]] df.columns = ["geo", filename] dfs.append(df) # merge all files using key geo master_df = dfs[0] for i in range(len(dfs)-1): master_df = pd.merge(master_df, dfs[i+1], how="inner", left_on="geo",right_on="geo") return master_df # + id="pw34C7EvmVLy" outputId="fc0284ea-3e58-43f0-e822-a0fc348c9af0" colab={"base_uri": "https://localhost:8080/"} emission = read_merge_csv(root_folder) emission.head() # + id="zpQyrGmamZ6t" outputId="51499df3-2d1c-4745-dd4d-7d9b01c7eae0" colab={"base_uri": "https://localhost:8080/"} emission.shape # + id="lxAGI-xT16Hz" outputId="4eddecb1-f829-4a42-e6b7-5b3ee550bb72" colab={"base_uri": "https://localhost:8080/"} emission.info() # + [markdown] id="HpCA28PKVk4M" # Most of the columns don't have any missing values except `market_value_of_listed_companies_percent_of_gdp ` and `eg_use_comm_cl_zs` which is 16 and 2 respectively. # + id="L9z-lwru5FTW" outputId="797bd909-1f51-406c-df60-f3ffadadaf8e" colab={"base_uri": "https://localhost:8080/"} #countries name which has missing values for market_value_of_listed_companies_percent_of_gdp country = emission[['geo']][emission['market_value_of_listed_companies_percent_of_gdp'].isnull()] country # + id="MUFLTPeq5b7A" outputId="0c656997-2e1d-45f9-af14-f47482387280" colab={"base_uri": "https://localhost:8080/"} # count of countries which don't have missing values for market_value_of_listed_companies_percent_of_gdp emission[['geo','co2_emissions_tonnes_per_person']][~emission['market_value_of_listed_companies_percent_of_gdp'].isnull()].shape # + [markdown] id="ycoar9rX4kCk" # Handling of Missing Value # + [markdown] id="OcmO56YL4uxi" # As our size of data is already small we can't drop the rows of which any one of the feature has missing values. So we need to choose suitable imputation method to fill those missing values. And for that we can use [`sklearn.impute()`](https://scikit-learn.org/stable/modules/impute.html#impute) method. In this we are using `IterativeImputer` method to fill missing values. # # # + id="M676knwPBVNw" # import required imputation library from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer from sklearn.neighbors import KNeighborsRegressor # model to impute the values # + id="DhVXmgbUjlnl" outputId="fe4b3b16-5eab-4540-88f5-2bacc47b54ad" colab={"base_uri": "https://localhost:8080/"} imputing_data = emission.drop(['geo','co2_emissions_tonnes_per_person'], axis=1,) kn_reg = KNeighborsRegressor(weights='distance') # model instatiation imputer = IterativeImputer(estimator= kn_reg, missing_values= np.nan, random_state=0) # instantiation of imputer imputed_data = pd.DataFrame(imputer.fit_transform(imputing_data), columns= imputing_data.columns) imputed_data.head() # + id="veV8z11QjumV" outputId="75afbe8e-ae9e-4092-8888-d9b14f26bba3" colab={"base_uri": "https://localhost:8080/"} imputed_data.isnull().sum() # + id="wM41OzfKpAGN" outputId="e1e64ba6-75fa-43e3-b38b-dad0a0d1b9c5" colab={"base_uri": "https://localhost:8080/"} # add the imputed column to original dataset emission[["market_value_of_listed_companies_percent_of_gdp", "eg_use_comm_cl_zs"]] = imputed_data[["market_value_of_listed_companies_percent_of_gdp", "eg_use_comm_cl_zs"]] emission.head() # + id="JXH99RDqp7SE" outputId="6d1eff91-f617-471b-d2fa-0afb0e744ca3" colab={"base_uri": "https://localhost:8080/"} emission.isnull().sum() # + id="BiyIkekMp_sv" outputId="f0d4b815-da2b-434b-82d6-175e858ec01f" colab={"base_uri": "https://localhost:8080/"} #fill the imputed values to emission dataset emission.loc[country.index,['geo','market_value_of_listed_companies_percent_of_gdp', "eg_use_comm_cl_zs"]] # + [markdown] id="2rKV3dM2SJkd" # ### Exploratory Data Analysis # + id="a_IzBC_sSbnZ" outputId="b8c95745-3177-4860-8bd5-e0ad7740771a" colab={"base_uri": "https://localhost:8080/"} emission.head() # overview of data # + [markdown] id="JShZBRKB-OKs" # #### Univariate Analysis # + [markdown] id="CzGV-RKg_bRz" # ##### Heatmap # To see how multiple features are correlated with each other. # + id="iZBYLeaT1jva" outputId="42a46a02-524f-4bac-f886-7c00b06d4c1f" colab={"base_uri": "https://localhost:8080/"} plt.figure(figsize=(20,10)) matrix = np.triu(emission.corr()) sns.heatmap(emission.corr(), annot=True,mask= matrix) # + [markdown] id="PhRD4WbsGzMa" # ##### Violin Plot # + id="_z2pBAzeSiO3" # function to plot violin plots def violin_plot(column:'list', dataframe:'dataframe'): plt.figure(figsize=(16,10)) for index, val in enumerate(column): plt.subplot(5,3,index+1) sns.violinplot(dataframe[val], inner='quartile',data = dataframe) plt.tight_layout() return plt.show() # + id="WFggeOJ3WwIs" outputId="135c90cb-880e-4334-aa62-e435740caa94" colab={"base_uri": "https://localhost:8080/"} column = list(emission.columns) column.remove('geo') # since in geo feature do not have numerrical value remove it violin_plot(column,emission) # + id="yYX0xR2lGVLV" outputId="6229609e-30c8-4273-bd8a-21f1859b979e" colab={"base_uri": "https://localhost:8080/"} emission.columns # + [markdown] id="ZhYoEJzulG03" # **Observations** # - As we see most of the plots shown us that data are normally distributed with rightly skewed mostly of them excpet `forest_coverage_percent`. # - Out of skewed data features ; # - oil_consumption_per_cap # - yearly_co2_emissions_1000_tonnes # - exports_percent_of_gdp # - imports_percent_of_gdp # - population_total # # this features of total features needs attention for outliers; because most of the linear models are sensitive to outliers. # + [markdown] id="7L5NhhbPXam_" # ##### Box Plot # + id="NNGYAxjISgSp" # function to plot box plots def box_plot(column:'list', dataframe:'dataframe'): plt.figure(figsize=(16,10)) for index, val in enumerate(column): plt.subplot(5,3,index+1) plt.boxplot(dataframe[val], vert= False, showmeans= True, data = dataframe) plt.xlabel(val) plt.tight_layout() return plt.show() # + id="-uOp-PtsS7qX" outputId="b4c17e4b-d050-4eef-8a17-2b33723560ab" colab={"base_uri": "https://localhost:8080/"} column = list(emission.columns) column.remove('geo') box_plot(column, emission) # + [markdown] id="0N01t3aA_JXa" # #### Bivariate Analysis # + [markdown] id="qPKN-vPmIZHV" # To do bivariate analysis most of the time we often choose distplot or scatter plot. Scatter plots might give glimpse of trend between two variables which we are plotted. # + [markdown] id="H_qEIV27JDJo" # ##### Scatter Plot # + id="KEBlLXchJH9b" def plot_scatter(on_x:'list', on_y: 'varname', dataframe:'dataframe'): plt.figure(figsize=(25,20)) for index, val in enumerate(on_x): plt.subplot(5,3,index+1) sns.scatterplot(x = dataframe[val], y= dataframe[on_y], data = dataframe) plt.ylabel(on_y) plt.tight_layout() plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) return plt.show() # + id="LmSErkXEKLuI" outputId="e25b2303-4b39-495c-d5d9-954b198157bf" colab={"base_uri": "https://localhost:8080/"} column = list(emission.columns) column.remove('geo') column.remove('co2_emissions_tonnes_per_person') y = 'co2_emissions_tonnes_per_person' plot_scatter(column, y,emission) # + [markdown] id="KeAtd8fET0fY" # #### Outliers Treatment # As we observed by boxplots there is outliers and we noted that outliers are too sensitive to the linear models. We need to handle them; one of the simplest method is drop that much amount from the feaures but it is not right choice cause our dataset is small so we should have to choose another way to handle them. Here we are using capping of outliers method to cap outliers. # + id="hTjLa9uBUPLv" outputId="4fe2afb5-8d5b-4a6b-8b11-42ba4c1d9d53" colab={"base_uri": "https://localhost:8080/"} # check for different quantiles to check for sudden rise emission.describe(percentiles=[0.1,0.25,0.5,0.75,0.90,0.95,0.99,0.995]) # + id="ERdx6cB9WXme" # creating a list of features to treat for outliers features = ["co2_emissions_tonnes_per_person", "income_per_person_gdppercapita_ppp_inflation_adjusted", "coal_consumption_per_cap", "electricity_use_per_person", "oil_consumption_per_cap", "electricity_generation_per_person", "yearly_co2_emissions_1000_tonnes", "market_value_of_listed_companies_percent_of_gdp", "exports_percent_of_gdp", "imports_percent_of_gdp", "eg_use_comm_cl_zs", "population_total"] # + id="o4xNtrVlRcVB" outputId="f6a87766-5db3-47ea-e175-994e3d90f23c" colab={"base_uri": "https://localhost:8080/"} # cap the outliers to 99th percentile value for i in features: q2 = emission[i].quantile(0.99) emission[i][emission[i]>q2]=q2 # + id="rZZ6omouWjKn" outputId="36a21201-c458-42e1-e1b9-124a23d8eeea" colab={"base_uri": "https://localhost:8080/"} emission.describe() # + id="9Z6NYYDUXbPA" outputId="c108b0b8-e523-458a-b23e-e3a15c92caf7" colab={"base_uri": "https://localhost:8080/"} # after capping the outliers box_plot(features,emission) # + id="uV5_Fghyp1Dk" outputId="0ad4037d-0969-4778-bdd6-e53ee13cf1dd" colab={"base_uri": "https://localhost:8080/"} size = emission['population_total'] plt.figure(figsize=(10,8)) plt.scatter(x = "forest_coverage_percent", y='co2_emissions_tonnes_per_person', s =size/1000000, alpha=0.8, data=emission) plt.xlabel("Forest coverage percent") plt.ylabel("CO$_{2}$ emission in tonnes per person") plt.title("Countrywise CO$_{2}$emission against forest coverage of 2014") plt.tight_layout() # + id="OEjRaIT6FS8F" outputId="bd1d54dc-7d5a-43b7-f4d0-926375c78280" colab={"base_uri": "https://localhost:8080/"} # lets check for contribution of each country to the co2 emission per capita # a countries which are contributing abvove median value of the co2_emissions_tonnes_per_person co2_emission_contribute = emission[emission["co2_emissions_tonnes_per_person"] > emission["co2_emissions_tonnes_per_person"].median()] plt.figure(figsize=(20,10)) sns.barplot(x="geo",y="co2_emissions_tonnes_per_person", order=co2_emission_contribute.sort_values("co2_emissions_tonnes_per_person", ascending=False).geo, data=co2_emission_contribute, ) plt.xlabel("Country") plt.xticks(rotation=90) plt.title("CO$_{2}$ emission per capita in 2014",fontdict={'size':15}) plt.tight_layout() # + id="eWC-LMQ8DU8Z" outputId="c51fb135-6f09-4b63-eb63-b27cee0d2fbb" colab={"base_uri": "https://localhost:8080/"} emission.shape # + [markdown] id="V7A8UHNEkMl_" # As you see `Qatar`, `Kuwait`,`UAE` and `Saudi Arabia`are top four countries which have most CO$_{2}$ emissions per capita for 2014. One thing which I want to mention here that is top four countries which emit CO$_{2}$ are arabian countries. Lets check those countries average over remaining 57 countries dataset. # + id="BA0Pgj7LB9Tv" outputId="b60aaa8c-a158-466c-dcfa-78a4302412bf" colab={"base_uri": "https://localhost:8080/"} arab_country = ['Qatar', 'Kuwait', 'United Arab Emirates', 'Saudi Arabia'] arab_country_emission = emission[emission['geo'].isin(arab_country)] arab_country_emission # + id="jNTtX2ZvGmoE" outputId="40ec916f-8aac-4045-855b-ec741fc18951" colab={"base_uri": "https://localhost:8080/"} arab_country_emission['co2_emissions_tonnes_per_person'].mean() # + id="IFsX-TZ-G9E-" emission_country = emission.set_index('geo') rest_countries = emission_country.drop(arab_country, axis=0) # + id="1NHyvrJWJCqd" outputId="3a6b2511-a279-411b-b979-e241377c4537" colab={"base_uri": "https://localhost:8080/"} rest_countries['co2_emissions_tonnes_per_person'].mean() # + [markdown] id="v3QbJueAJX1H" # As you can notice that in 2014 CO$_{2}$ emission per person for the `Qatar`, `Kuwait`,`UAE` and `Saudi Arabia` is 25.32 tonnes per person while rest 57 countries has 6.34 tonnes/person on average. # That means in 2014 this 4 countries had emitted almost 4 times the rest of the 57 countries emission on average. # + [markdown] id="RV6jqshsmtWn" # ### Data Preprocessing # + id="EiiL-N64kB9b" outputId="2c6968c2-f80b-4947-c435-f9c30a2c589e" colab={"base_uri": "https://localhost:8080/"} emission.describe() # + [markdown] id="d4NOF290pwnK" # As you noticed each feature has different unit representation and values are differ by large values across features. So we need to bring them on the same scale. That's why we need pre-processing of data. # + [markdown] id="CxSUnb9J9twW" # #### Scale the Data # + id="bdTS-K9xpss_" # import required library to preprocess the data from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler # + id="4FcpcQVxsJUH" scaling_df= emission.drop(['geo'], axis=1) # + id="6YfTwTMLsW51" scaler = StandardScaler() # instantiation of scaler method # + id="csumaHm_tPv9" scaled_df = scaler.fit_transform(scaling_df) # + id="TlauuuGY1xG4" outputId="7078155a-9345-41d4-e51e-c3b2634d8b99" colab={"base_uri": "https://localhost:8080/"} column = emission.drop(['geo'], axis=1).columns scaled_df = pd.DataFrame(scaled_df,columns=column) scaled_df.describe() # + [markdown] id="_XAKxPqU5D3X" # #### Splitting data into X_train and y_train # Since rule of thumb for test dataset size is atleast 100 observations; but we don't have 100 obseravtions in our total dataset. So we don't split it into test dataset. # And another reason is that since our problem statment states that we need to find features which are most contributing to CO$_{2}$ emissions for 2014. # + id="zT58OcDQ1zJi" outputId="7065a9f3-9d8c-4a8e-f707-e32201895bba" colab={"base_uri": "https://localhost:8080/"} scaled_df.head() # + id="uedNpr1Y9GsQ" X_train = scaled_df.drop("co2_emissions_tonnes_per_person", axis=1) y_train = scaled_df["co2_emissions_tonnes_per_person"] # + id="zoVSAP4i9bdK" outputId="4b2078ba-b89e-40ec-9984-85eba5b03533" colab={"base_uri": "https://localhost:8080/"} X_train.shape # + id="SUvLN_Tp9ey_" outputId="820bc4ab-5738-4b68-aef8-8767de909260" colab={"base_uri": "https://localhost:8080/"} y_train.shape # + [markdown] id="9L1Kn_K093kh" # ### Model Build # + id="91VQpknY97pT" # import required library from sklearn.linear_model import Lasso from sklearn.metrics import r2_score from sklearn.model_selection import GridSearchCV, KFold # + [markdown] id="qxgKPqOGZJR_" # ###### Lasso Regression # + id="m0Vavnyu-16S" lasso_reg = Lasso(alpha=0.001, random_state= 42) # + id="GgQAr1FV_EvO" lasso_reg.fit(X_train, y_train) y_train_pred = lasso_reg.predict(X_train) # + id="84Lbeedr_suA" outputId="f26a756a-a127-4374-aa4a-664e15783f9d" colab={"base_uri": "https://localhost:8080/"} r2_score(y_train, y_train_pred) # + id="0fa6u52LAMi9" # lasso model parameters model_parameters = list(lasso_reg.coef_) model_parameters.insert(0, lasso_reg.intercept_) model_parameters = [round(x, 3) for x in model_parameters] features = X_train.columns features = features.insert(0, "constant") model_param = pd.DataFrame([features, model_parameters]) # + id="Rk4wkPC3AQUB" outputId="c389017b-509b-4ddd-961c-9ee0cad91870" colab={"base_uri": "https://localhost:8080/"} model_param = model_param.T model_param.columns = ['Features', 'parameter'] model_param.set_index('Features') # + [markdown] id="oTew7RzTZT2e" # ##### Hyperparameter Tuning of Lasso Regression # + id="BfyUEpScBxdh" outputId="1c585ec1-cb38-47c6-ed8a-eb2e7de98fb9" colab={"base_uri": "https://localhost:8080/"} # grid search CV # set up cross validation scheme folds = KFold(n_splits = 3, shuffle = True, random_state = 42) # specify range of hyperparameters params = {'alpha': [0.001, 0.01, 1.0, 5.0, 10.0]} # grid search # lasso model model = Lasso(random_state=42) model_cv = GridSearchCV(estimator = model, param_grid = params, scoring= 'r2', cv = folds, return_train_score=True, verbose = 1) model_cv.fit(X_train, y_train) # + id="IrFNwk3dH1Aw" outputId="f89c23f2-5600-43bf-80aa-f55f6f05bf83" colab={"base_uri": "https://localhost:8080/"} cv_results = pd.DataFrame(model_cv.cv_results_) cv_results.head() # + id="_EsoNLOaH2LB" outputId="2634232c-c895-49e1-9b61-0f726f7cae69" colab={"base_uri": "https://localhost:8080/"} # plot cv_results['param_alpha'] = cv_results['param_alpha'].astype('float32') plt.plot(cv_results['param_alpha'], cv_results['mean_train_score']) plt.plot(cv_results['param_alpha'], cv_results['mean_test_score']) plt.xlabel('alpha') plt.ylabel('r2 score') plt.xscale('log') plt.show() # + id="qpgdIDAHIBmn" outputId="01c60f70-7fd0-4036-d277-e0a48b65aced" colab={"base_uri": "https://localhost:8080/"} model_cv.best_params_ # + id="hVgNHHdBISFX" outputId="5bcd1151-41d8-4db3-9a71-62b460d0199e" colab={"base_uri": "https://localhost:8080/"} model_cv.best_estimator_ # + id="QgZ35oTfJGHT" outputId="007f36cf-8fc3-4ef4-c42e-366011ed4020" colab={"base_uri": "https://localhost:8080/"} model_cv.best_score_ # + id="aUFFJNRnIbly" outputId="f0a57ec9-838a-4842-845f-25e2ac7a60c5" colab={"base_uri": "https://localhost:8080/"} # model with optimal alpha # lasso regression lm = Lasso(alpha=0.01) lm.fit(X_train, y_train) # predict y_train_pred = lm.predict(X_train) print(r2_score(y_true=y_train, y_pred=y_train_pred)) # + [markdown] id="UAdHfjumUR6G" # Here we get $R^2$ score of 0.89 on training side with optimal model using `GridSearchCV` # + id="5lCXti9aJnkZ" # lasso model parameters model_parameters = list(lm.coef_) model_parameters.insert(0, lm.intercept_) model_parameters = [round(x, 3) for x in model_parameters] features = X_train.columns features = features.insert(0, "constant") model_param = pd.DataFrame([features, model_parameters]) # + [markdown] id="mWIIthWHVBvt" # Summary of the model parameters: # + id="OuN7CNqNKHbJ" outputId="3f754916-c6b6-4446-c446-5d4bd18f6f91" colab={"base_uri": "https://localhost:8080/"} model_param = model_param.T model_param.columns = ['Features', 'parameter'] model_param.set_index('Features') # + [markdown] id="zlxbLiHMZpSn" # ##### Collinearity Checking Using `VIF` for Optimal Model # + id="OOVSloTmKIU7" X_train = X_train.drop(['electricity_generation_per_person', 'exports_percent_of_gdp'], axis= 1) # + [markdown] id="O6D0bbf1WE2a" # Now lets check multi-collinearity between features. To check that we use `variance_inflation_factor` from `statsmodels`. # + id="_rkYH9VafMSQ" outputId="20a1a55a-9f77-45e7-c33f-80d688c7fdfd" colab={"base_uri": "https://localhost:8080/"} X_train.columns # + id="mguwCyMEV_wM" outputId="6cf0260b-bbcf-410f-9af8-fdf68e2f6dd1" colab={"base_uri": "https://localhost:8080/"} from statsmodels.stats.outliers_influence import variance_inflation_factor # checking VIF vif = pd.DataFrame() vif["features"] = X_train.columns vif["VIF"] = [variance_inflation_factor(X_train.values,i) for i in range(X_train.shape[1])] vif["VIF"] = round(vif["VIF"],2) vif = vif.sort_values(by="VIF",ascending=False) vif # + [markdown] id="EeVoVevXacH-" # As general rule of thumb for optimal value of `VIF` should be less than 5. We can notice that top two are violating this norm so we can't rely on the parameter value significantly. We need to remove one by one from it and check again for vif . # + id="umUg60mmV_se" # drop the first feature and again tune the model and check for VIF X_train = X_train.drop('income_per_person_gdppercapita_ppp_inflation_adjusted',axis=1) # + id="gP0OincffjuN" outputId="1643273c-db1c-4032-e2af-b73df5d0f363" colab={"base_uri": "https://localhost:8080/"} X_train.columns # + id="925CkQJlV_nn" outputId="8d5dbd2c-be01-4aa1-9919-b4545b5d31eb" colab={"base_uri": "https://localhost:8080/"} # using 3 folds folds = KFold(n_splits=3, shuffle=True, random_state=42) params = {"alpha": [0.0001, 0.001,0.01,0.1,1.0,5.0,10.0]} model = Lasso(random_state=42) model_cv = GridSearchCV(estimator=model, param_grid = params, scoring="r2", cv=folds, n_jobs=-1, verbose=1, return_train_score=True,) model_cv.fit(X_train, y_train) # + id="8q2_pHTNV_kE" outputId="031bd4dc-375b-4482-92e9-76cc861ae3fd" colab={"base_uri": "https://localhost:8080/"} cv_results = pd.DataFrame(model_cv.cv_results_) cv_results.head() # + id="Q-PAhYZWV_fU" outputId="f01efa10-13f6-40f4-b766-d29ecb657c8d" colab={"base_uri": "https://localhost:8080/"} model_cv.best_estimator_ # + id="SPuFEydgV_YC" outputId="d29c6bf5-f2b9-4b42-869f-6daedf228d36" colab={"base_uri": "https://localhost:8080/"} # plotting cv_results['param_alpha'] = cv_results['param_alpha'].astype('float32') plt.plot(cv_results['param_alpha'], cv_results['mean_train_score']) plt.plot(cv_results['param_alpha'], cv_results['mean_test_score']) plt.xlabel('alpha') plt.ylabel('r2 score') plt.xscale('log') plt.show() # + id="55Dd8juldGti" outputId="d9e3dc0f-04ef-4151-9461-7b96bcd7bef0" colab={"base_uri": "https://localhost:8080/"} model_cv.best_params_ # + id="Y8LNoxokSCLV" outputId="fe2abd18-d2cf-4474-d30e-acd703a4b5ee" colab={"base_uri": "https://localhost:8080/"} # build model using alpha = 0.01 lm = Lasso(alpha=0.01, random_state=42) lm.fit(X_train,y_train) # + id="mA0Dh3XeSmr8" outputId="1ccabbec-f8bc-45c1-c46b-70033ed7c76b" colab={"base_uri": "https://localhost:8080/"} y_train_pred = lm.predict(X_train) r2_score(y_train, y_train_pred) # + id="jYLD7C2HdxVl" # lasso model parameters model_parameters = list(lm.coef_) model_parameters.insert(0, lm.intercept_) model_parameters = [round(x, 3) for x in model_parameters] features = X_train.columns features = features.insert(0, "constant") model_param = pd.DataFrame([features, model_parameters]) # + id="1-vErgzRdxVz" outputId="fac0ac35-d7ef-4c5c-86c5-ce28a9a72ac6" colab={"base_uri": "https://localhost:8080/"} model_param = model_param.T model_param.columns = ['Features', 'parameter'] model_param.set_index('Features') # + id="zYcuT50ggTEl" outputId="ccde2d28-0476-4f48-8b07-d7c73133956e" colab={"base_uri": "https://localhost:8080/"} # checking VIF vif = pd.DataFrame() vif["features"] = X_train.columns vif["VIF"] = [variance_inflation_factor(X_train.values,i) for i in range(X_train.shape[1])] vif["VIF"] = round(vif["VIF"],2) vif = vif.sort_values(by="VIF",ascending=False) vif # + [markdown] id="GPtASPGUgYlP" # Now all the features are under the assumed threshold value of `VIF` which is 5. So we can say that this model is optimal one. # + [markdown] id="Y7uO0cZnMZZT" # ### Validation of Linear models Assumptions # + [markdown] id="HUsP7mKCMvy1" # #### Normality Assumption: # In this we do check whether or not error of the model is normaly distributed. To visually check that we often plot qqplot of the residual. # + id="8IqTCx0AMog5" residual = y_train_pred - y_train # + id="iH0N52IIhb-s" outputId="3b847652-5fc4-42b7-e035-9582695113d1" colab={"base_uri": "https://localhost:8080/"} import statsmodels.api as sm # qq plot sm.qqplot(residual,line="q") plt.show() # + [markdown] id="DFVSmd58h0FU" # Most of the residual values reside on the theoretical quantiles value so we can say that error are normally distributed with flat tail side on both side. # + [markdown] id="xrwmgxyRiTsW" # #### Independent Errors Assumptions # + id="d7wmRVOuQB4Q" outputId="4b29dd17-33bb-40eb-d593-a6a7b9a1c4ce" colab={"base_uri": "https://localhost:8080/"} sns.residplot(y_train_pred, residual, color="g") # + [markdown] id="aPHCCyf0jDdh" # We can't see any pattern in residual plot so: # - **Independence of error terms assumption validated** # # As well as variance also constant around the mean value. # - **Homoscedasticity i.e. constant variance assumption also validated.** # + [markdown] id="FSwuL3zko229" # ##### Auto-Correlation Assumption # + id="1eFxt_t-RHTz" from statsmodels.graphics.tsaplots import plot_acf # + id="fSKq218vnGJ8" outputId="8229ab71-404d-4f10-926f-ea80d6d2fd20" colab={"base_uri": "https://localhost:8080/"} from statsmodels.stats.stattools import durbin_watson #quantitative method durbin_watson(residual) # + [markdown] id="LZokZz-Pq29X" # Since as per rule of thumb of threshold value of the above test should not be greater than 2 for any autocorrelation. # So **There is no auto-correlation.** # + id="x3Hg9sdmn4HJ" outputId="4a2ad0be-dafa-4f06-a59c-9694820b579f" colab={"base_uri": "https://localhost:8080/"} plot_acf(residual,) plt.show() # + id="xC4izNIOn8Mh" # + [markdown] id="SCwrEUVXtVgu" # ### Summary of the Project # + id="8JOXvOdntrkr" outputId="50d0b8bd-6976-4341-cf9a-c2458261358f" colab={"base_uri": "https://localhost:8080/"} model_param.sort_values('parameter', ascending=False) # + [markdown] id="2lgAAupFzPm-" # **A picture is worth a thousand words.** # # # ![World electricity production by Source ,2017](https://www.world-nuclear.org/getmedia/c907634e-4bb5-4a41-970e-40b8ec55c1a6/world-electricity-production.png.aspx) # + [markdown] id="B7MQ1Ul8zhof" # As above image tells us that still we rely to attain our need of power on the source such as **Coal**, **Gas**. # Our model also tries to show that top most four features which are contributing to CO$_{2}$ emission. # Most Influential Features: # - Electricity use per capita # - industry percent of gdp # - Oil cunsumption per capita # - Coal cunsupltion per capita # # # + [markdown] id="tDemjHc13o2X" # - Also we can conclude that alternative and nuclear energy use and forest coverage percent help to reduce CO$_{2}$ emission because it is negatively influence model dependent variable. # - So we should try to attain our power need through alternative energy resources such as renewable energy sources of which most of them are clean energy sources. # - Also we know that forest are acts like **`Carbon Pool`**. We need to increase forest coverage percent of our total area which would helps us. # + id="RLC4ovr5_cMN"
C02_emission.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Predicting crop yield using weather and satellite observations with DL Platform # # In this tutorial, you will find corn in Iowa, calculate the vegetation indices, and calculate the weather variables necessary to develop a predictive model to find a crop yield using the Descartes Labs Platform. Some of our platform services used in this tutorial include: # * Catalog # * Metadata # * Places # * Raster # * Scenes # * Tasks # + import descarteslabs as dl from descarteslabs.client.services.tasks import AsyncTasks, as_completed from descarteslabs.client.services import Catalog from descarteslabs.client.services import Storage from matplotlib import colors from mpl_toolkits.axes_grid1 import make_axes_locatable from pprint import pprint import calendar import folium import json import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas import pickle import shapely import shapely.geometry import sklearn import sklearn.cluster import sklearn.ensemble import sys # Create storage and catalog clients storage_client = Storage() catalog_client = Catalog() # - # ## Finding Corn # Use the NASS dataset for corn in Iowa counties along with Descartes Labs Places and Scenes to create a colormap of corn in Crawford County, Iowa. # load yield reference data with open('nass_county_iowa_corn_2017.json') as f: reference = json.load(f) # find Crawford County, IA slug = dl.places.find('iowa_west-central_crawford')[0]['slug'] county_shape = dl.places.shape(slug) geometry = shapely.geometry.shape(county_shape['geometry']) geometry # search scenes to find imagery scenes, geo_ctx = dl.scenes.search( geometry, products=['usda:cdl'], start_datetime='2017-01-01', end_datetime='2018-01-01', limit=500 ) scenes, geo_ctx # rasterize all contained scenes into an ndarray using the geo context. arr = scenes.mosaic("class", geo_ctx, mask_alpha=False) arr.shape # one band, 1310 pixels tall by 1587 pixels wide # + # filter the ndarray to just corn corn = np.where(arr == 1, 1, 0)[0,:,:] # create the colormap colorlist = ['w', 'y'] cmap = colors.ListedColormap(colorlist) bounds = [0, 1, 2] norm = colors.BoundaryNorm(bounds, cmap.N) # plot the map fig, ax = plt.subplots(figsize=(8, 8)) cax = plt.imshow(corn, cmap=cmap, norm=norm) plt.title('Corn in Crawford County, Iowa (2016)') cbar = fig.colorbar(cax, ticks=[0.5, 1.5], orientation='vertical', fraction=0.036, pad=0.04) cbar.ax.set_yticklabels(['Other', 'Corn']) plt.axis('off') plt.tight_layout() # - # ## Calculate vegetation indices # To calculate vegetation indices, you will use Scenes to search for NDVI imagery, rasterize the contained scenes into an ndarray, and then plot the results against our colormap. # search for NDVI scenes # note: we pass in geo_ctx instead of AOI to ensure returned scenes are in the correct coordinate reference system scenes, geo_ctx = dl.scenes.search( geo_ctx, products=['8291fd932b469d8d81701dd6079d64b0fabc5f93:moody:l8_2017_veg_healthmax:v1'], start_datetime='2017-01-01', end_datetime='2017-12-31', limit=500 ) scenes # rasterize all contained scenes into an ndarray using the geo context. arr = scenes.mosaic('veg_healthmax', geo_ctx, mask_alpha=False)[0, :, :] arr.shape #same shape as previous steps # filter the ndarray to just corn corn_ndvi = np.where(corn == 1, arr, 0) # plot the results against our colormap fig, ax = plt.subplots(figsize=(8, 8)) cax = plt.imshow(corn_ndvi) cbar = fig.colorbar( cax, ticks=[0, 240], orientation='vertical', fraction=0.036, pad=0.04 ) cbar.ax.set_yticklabels(['Low max NDVI', 'High max NDVI']) plt.axis('off') plt.tight_layout() # ## Calculate weather variables # To calculate the weather variables, you will use Raster to create a global tiling across our area of interest, use Catalog to create a product in your Descartes Labs user namespace, retrieve a stack of images using Scenes and their IDs using Metadata, and finally use Raster to create a stack of DLTiles. # # Once you have the tiles, you will use the Tasks service to create a task to predict water over the DLTiles and then test the function. After the function has been tested, you will use Tasks to run the job that will predict water. # + # create a global tiling across our AOI shape = dl.places.shape('north-america_united-states_iowa') resolution = 30 tile_dimension = 2048 pad = 0 tiles = dl.raster.dltiles_from_shape( resolution=resolution, tilesize=tile_dimension, pad=pad, shape=shape ) print('Number of tiles = {}'.format(len(tiles['features']))) # + # create a product in your Descartes Labs user namespace from descarteslabs.client.services.catalog import Catalog auth = dl.Auth() # get Descartes Labs username user = auth.payload['name'] # generate product ID from username product_id = '{}:{}:demo:crop:iowa'.format( auth.namespace, user.lower().replace(' ', '') ) product_title = '{} Growing Degree Days'.format(user) print(f""" The next cells will create the following product: title: {product_title} id: {product_id} """) # + # check if product already exists, remove if it does already_exists = list(filter(lambda p: p.get('id') == product_id, dl.Catalog().own_products())) if already_exists: print("Product already exists, removing existing one...") dl.Catalog().remove_product(product_id, cascade=True) print("...done") # add product to your user namespace product = dl.Catalog().add_product( product_id, title=product_title, description="GDD calculated from GSOD for crop demo" )['data']['id'] print(product) # add bands band_id = dl.Catalog().add_band( product_id, 'gdd', jpx_layer=0, srcfile=0, srcband=1, nbits=16, dtype='Int16', nodata=0, data_range=[0, 2**16 - 1], type='spectral', default_range=(0, 5500), data_unit_description='0.01 celsius', colormap_name='viridis' )['data']['id'] print(band_id) print("Done! View your product here: https://catalog.descarteslabs.com/?/product/{}".format(product_id)) # + tile = tiles['features'][0] start_date = '2017-05-01' end_date = '2017-10-15' product = 'fcd57a7bf668c5b65d49c5e32130a2c0a5281322:daily:gsod:interp:dev-v0' bands = ['tavg'] # search scenes to find imagery related to our tile geo context tile_geo_ctx = dl.scenes.DLTile.from_key(tile.properties.key) scenes, geo_ctx = dl.scenes.search( tile_geo_ctx, products=[product], start_datetime=start_date, end_datetime=end_date ) # load scenes into a 4D ndarray new_image_stack, new_meta = scenes.stack( bands, tile_geo_ctx, raster_info=True, mask_alpha=False, bands_axis=-1 ) # search metadata related to our tile geometry to get our image IDs available_scenes = dl.metadata.search( products=[product], geom=tile['geometry'], start_datetime=start_date, end_datetime=end_date ) # scene IDs ids = [scene['id'] for scene in available_scenes['features']] # retrieve our stack of rasters as a 4D ndarray old_image_stack, old_meta = dl.raster.stack( ids, bands=bands, dltile=tile, cutline=shape, data_type='Int32' ) # + # sort our new and old image stacks by date old_dates = [a.properties.acquired for a in available_scenes.features] new_dates = [a.properties.acquired for a in scenes] old_dates.sort() new_dates.sort() # - # identify if any dates do not match for o, n in zip(old_dates, new_dates): if o != n: print(f"These don't match: {o} ... {n}") # + # remove duplicated values old = np.unique(old_image_stack) new = np.unique(new_image_stack) print(old.dtype, new.dtype) print(len(old), len(new)) # - dl.scenes.display(old_image_stack[-1], bands_axis=-1, colormap='viridis') dl.scenes.display(new_image_stack[-1], bands_axis=-1, colormap='viridis') # create the function that creates the task to predict water over a DLTile def calculate_gdd_task(tile, shape, start_date, end_date, input_product, output_product): """ predict water over dltile with Tasks """ import descarteslabs as dl from descarteslabs.client.services.catalog import Catalog from descarteslabs.client.services.storage import Storage storage_client = Storage() catalog = Catalog() import os import numpy as np import pickle def search_and_raster(product, tile, shape, start_date, end_date): scenes, geo_ctx = dl.scenes.search( tile['geometry'], products=[product], start_datetime=start_date, end_datetime=end_date ) tile_geo_ctx = dl.scenes.DLTile.from_key(tile['properties']['key']) image_stack, meta = scenes.stack( ['tavg'], tile_geo_ctx, raster_info=True, mask_alpha=False, bands_axis=-1 ) print(image_stack.shape) # expecting (100, 2048, 2048, 1) dl.scenes.display(image_stack[0], bands_axis=-1) uniques = np.unique(image_stack[0]) print(f"first layer has {uniques} unique values") return image_stack[:, :, :, 0], meta[0] def calc_gdd(image_stack): ''' calculate gdd for each pixel''' gdd = image_stack - 1000 gdd = np.where(gdd < 0, 0, gdd) # calculate cumulative GDD # scale to fit in uint16 cum_gdd = cum_gdd = np.ndarray.astype((np.sum(gdd, axis=0) / 100), 'uint16') return cum_gdd ''' predict water over each compositing period ''' outdir = os.path.join(os.path.expanduser('~'), 'temp') if not os.path.isdir(outdir): os.makedirs(outdir) key = tile['properties']['key'] outfile = 'gdd_{}_{}_{}.tif'.format(key, start_date, end_date) # get imagery and stats for each product image_stack, meta = search_and_raster(input_product, tile, shape, start_date, end_date) stats = calc_gdd(image_stack) # save to product to Catalog upload_id = catalog.upload_ndarray( stats, output_product, outfile, raster_meta=meta ) return "Processed dltile {}\nupload_id {}".format(key, upload_id) # test the task function calculate_gdd_task( tiles['features'][0], shape, '2017-05-01', '2017-10-15', 'fcd57a7bf668c5b65d49c5e32130a2c0a5281322:daily:gsod:interp:dev-v0', product_id ) # + # run the tasks to predict water from descarteslabs.client.services.tasks import AsyncTasks, as_completed at = AsyncTasks() # get the correct python version to match the image version = "{}.{}".format(sys.version_info[0], sys.version_info[1]) image_link='us.gcr.io/dl-ci-cd/images/tasks/public/py{}/default:v2019.02.12'.format(version) async_function = at.create_function(calculate_gdd_task, name="demo-crop-yield", memory='10Gi', image=image_link, task_timeout=5000 ) # + # submit the tasks input_product = 'fcd57a7bf668c5b65d49c5e32130a2c0a5281322:daily:gsod:interp:dev-v0' tasks = [async_function(tile, shape, '2017-05-01', '2017-10-15', input_product, product_id) for tile in tiles['features']] # - # ## Monitor the tail generation tasks from IPython.display import IFrame IFrame('https://monitor.descarteslabs.com', width="100%", height="600px") # + # Data are now available through the programmatic API available_scenes = dl.metadata.search(products=[product_id]) print(len(available_scenes['features'])) # - # ## Develop a predictive model # ### Train a model # + from sklearn.tree import DecisionTreeRegressor features = [] values = [] for slug in sorted(reference.keys()): features.append(reference[slug]['gdd'] + reference[slug]['ndvi']) values.append(reference[slug]['yld']) regr = DecisionTreeRegressor(max_depth=7) regr.fit(features, values) print('r2 = {}'.format(regr.score(features, values))) # - # ### Predict yield over Illinois # + with open('nass_county_illinois_corn_2017_predictor.json') as f: predict_data = json.load(f) features = [] values = [] geometries = [] for slug in sorted(predict_data.keys()): features.append(list(predict_data[slug]['gdd']) + list(predict_data[slug]['ndvi'])) values.append(predict_data[slug]['yld']) geometries.append({'properties': {'name': slug}, 'geometry': predict_data[slug]['geometry'], 'type': 'Feature'}) yield_predictions = regr.predict(np.array(features)) # - # ### Plot the predictions # + df = pandas.DataFrame.from_dict({'yield': yield_predictions, 'name': sorted(predict_data.keys())}) counties = {'type': 'FeatureCollection', 'features': geometries} m = folium.Map(location=[40.0468423, -89.1366099], zoom_start=6) m.choropleth(geo_data=counties, data=df, columns=['name', 'yield'], key_on='feature.properties.name', fill_color='YlGn', fill_opacity=1, legend_name='Predicted Corn Yield - 2017 (bu/acre)') m
crop_yield/descartes-labs-crop-yield-demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Accessing Cloud Optimized GeoTIFF (COG) - HTTPS Example # ## Summary # # In this notebook, we will access data for the Harmonized Landsat Sentinel-2 (HLS) Operational Land Imager Surface Reflectance and TOA Brightness Daily Global 30m v2.0 (L30) ([10.5067/HLS/HLSL30.002](https://doi.org/10.5067/HLS/HLSL30.002)) data product. These data are archived and distributed as Cloud Optimized GeoTIFF (COG) files, one file for each spectral band. # # We will access a single COG file, L30 red band (0.64 – 0.67 μm), from inside the AWS cloud (us-west-2 region, specifically) and load it into Python as an `xarray` `dataarray`. This approach leverages S3 native protocols for efficient access to the data. # # ## Requirements # # ### 1. AWS instance running in us-west-2 # # NASA Earthdata Cloud data in S3 can be directly accessed via temporary credentials; this access is limited to requests made within the US West (Oregon) (code: us-west-2) AWS region. # # ### 2. Earthdata Login # # An Earthdata Login account is required to access data, as well as discover restricted data, from the NASA Earthdata system. Thus, to access NASA data, you need Earthdata Login. Please visit https://urs.earthdata.nasa.gov to register and manage your Earthdata Login account. This account is free to create and only takes a moment to set up. # # ### 3. netrc File # # You will need a netrc file containing your NASA Earthdata Login credentials in order to execute the notebooks. A netrc file can be created manually within text editor and saved to your home directory. For additional information see: [Authentication for NASA Earthdata](https://nasa-openscapes.github.io/2021-Cloud-Hackathon/tutorials/04_NASA_Earthdata_Authentication.html#authentication-via-netrc-file). # # ## Learning Objectives # # - how to configure you Python work environment to access Cloud Optimized geoTIFF (COG) files # - how to access HLS COG files # - how to plot the data # --- # ## Cloud Optimized GeoTIFF (COG) # # Using Harmonized Landsat Sentinel-2 (HLS) version 2.0 # ### Import Packages import os from osgeo import gdal import rasterio as rio import rioxarray import hvplot.xarray import holoviews as hv # ## Workspace Environment Setup # # For this exercise, we are going to open up a context manager for the notebook using the rasterio.env module to store the required GDAL configurations we need to access the data from Earthdata Cloud. While the context manager is open (rio_env.__enter__()) we will be able to run the open or get data commands that would typically be executed within a with statement, thus allowing us to more freely interact with the data. We’ll close the context (rio_env.__exit__()) at the end of the notebook. # # GDAL environment variables must be configured to access COGs from Earthdata Cloud. Geospatial data access Python packages like rasterio and rioxarray depend on GDAL, leveraging GDAL’s “Virtual File Systems” to read remote files. GDAL has a lot of environment variables that control it’s behavior. Changing these settings can mean the difference being able to access a file or not. They can also have an impact on the performance. rio_env = rio.Env(GDAL_DISABLE_READDIR_ON_OPEN='TRUE', GDAL_HTTP_COOKIEFILE=os.path.expanduser('~/cookies.txt'), GDAL_HTTP_COOKIEJAR=os.path.expanduser('~/cookies.txt')) rio_env.__enter__() # In this example we're interested in the HLS L30 data collection from NASA's LP DAAC in Earthdata Cloud. Below we specify the s3 URL to the data asset in Earthdata Cloud. This URL can be found via Earthdata Search or programmatically through the CMR and CMR-STAC APIs. https_url = 'https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/HLSL30.020/HLS.L30.T11SQA.2021333T181532.v2.0/HLS.L30.T11SQA.2021333T181532.v2.0.B04.tif' # ## HTTPS Data Access # # Read in the HLS s3 URL for the L30 red band (0.64 – 0.67 μm) into our workspace using `rioxarray`, an extension of `xarray` used to read geospatial data. da = rioxarray.open_rasterio(https_url) da # The file is read into Python as an `xarray` `dataarray` with a **band**, **x**, and **y** dimension. In this example the **band** dimension is meaningless, so we'll use the `squeeze()` function to remove **band** as a dimension. da_red = da.squeeze('band', drop=True) da_red # Plot the `dataarray`, representing the L30 red band, using `hvplot`. da_red.hvplot.image(x='x', y='y', cmap='gray', aspect='equal') # Exit the context manager. rio_env.__exit__()
how-tos/Earthdata_Cloud__Single_File__HTTPS_Access_COG_Example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # OpenCV Filters Webcam # # In this notebook, several filters will be applied to webcam images. # # Those input sources and applied filters will then be displayed either directly in the notebook or on HDMI output. # # To run all cells in this notebook a webcam and HDMI output monitor are required. # ## 1. Start HDMI output # ### Step 1: Load the overlay from pynq.overlays.base import BaseOverlay from pynq.lib.video import * base = BaseOverlay("base.bit") # ### Step 2: Initialize HDMI I/O # monitor configuration: 640*480 @ 60Hz Mode = VideoMode(640,480,24) hdmi_out = base.video.hdmi_out hdmi_out.configure(Mode,PIXEL_BGR) hdmi_out.start() # ## 2. Applying OpenCV filters on Webcam input # ### Step 1: Specify webcam resolution # camera (input) configuration frame_in_w = 640 frame_in_h = 480 # ### Step 2: Initialize camera from OpenCV # + import cv2 videoIn = cv2.VideoCapture(0) videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, frame_in_w); videoIn.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_in_h); print("capture device is open: " + str(videoIn.isOpened())) # - # ### Step 3: Send webcam input to HDMI output # + import numpy as np ret, frame_vga = videoIn.read() if (ret): outframe = hdmi_out.newframe() outframe[:] = frame_vga hdmi_out.writeframe(outframe) else: raise RuntimeError("Error while reading from camera.") # - # ### Step 4: Edge detection # Detecting edges on webcam input and display on HDMI out. # + import time num_frames = 20 readError = 0 start = time.time() for i in range (num_frames): # read next image ret, frame_vga = videoIn.read() if (ret): outframe = hdmi_out.newframe() laplacian_frame = cv2.Laplacian(frame_vga, cv2.CV_8U, dst=outframe) hdmi_out.writeframe(outframe) else: readError += 1 end = time.time() print("Frames per second: " + str((num_frames-readError) / (end - start))) print("Number of read errors: " + str(readError)) # - # ### Step 5: Canny edge detection # Detecting edges on webcam input and display on HDMI out. # # Any edges with intensity gradient more than maxVal are sure to be edges and those below minVal are sure to be non-edges, so discarded. Those who lie between these two thresholds are classified edges or non-edges based on their connectivity. If they are connected to “sure-edge” pixels, they are considered to be part of edges. Otherwise, they are also discarded. As we only need a single output channel reconfigure the HDMI output to work in grayscale mode. This means that our output frame is in the correct format for the edge detection algorith, # + num_frames = 20 Mode = VideoMode(640,480,8) hdmi_out = base.video.hdmi_out hdmi_out.configure(Mode,PIXEL_GRAY) hdmi_out.start() start = time.time() for i in range (num_frames): # read next image ret, frame_webcam = videoIn.read() if (ret): outframe = hdmi_out.newframe() cv2.Canny(frame_webcam, 100, 110, edges=outframe) hdmi_out.writeframe(outframe) else: readError += 1 end = time.time() print("Frames per second: " + str((num_frames-readError) / (end - start))) print("Number of read errors: " + str(readError)) # - # ### Step 6: Show results # Now use matplotlib to show filtered webcam input inside notebook. # + # %matplotlib inline from matplotlib import pyplot as plt import numpy as np frame_canny = cv2.Canny(frame_webcam, 100, 110) plt.figure(1, figsize=(10, 10)) frame_vga = np.zeros((480,640,3)).astype(np.uint8) frame_vga[:,:,0] = frame_canny frame_vga[:,:,1] = frame_canny frame_vga[:,:,2] = frame_canny plt.imshow(frame_vga) plt.show() # - # ### Step 7: Release camera and HDMI videoIn.release() hdmi_out.stop() del hdmi_out
boards/Pynq-Z2/base/notebooks/video/opencv_filters_webcam.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #Taking what we have learned from analyzing the kaggle dataset, we decided that we needed more information to try to # predict profit. We are applying what we learned from our Kaggle analysis to our the numbers dataset. # + #<NAME> Kendra Final Project #importing pandas, csv, import csv import pandas as pd import matplotlib.pyplot as plt import numpy as np import statistics #To create testing and training dfs and labels from sklearn.model_selection import train_test_split # To model the Gaussian Navie Bayes classifier from sklearn.naive_bayes import GaussianNB # To calculate the accuracy score of the model from sklearn.metrics import accuracy_score #confusion matrix from sklearn.metrics import confusion_matrix, classification_report #To get a count or tally of a category in our df from collections import Counter #for pre-processing to fit all numeric data on the standard scale from sklearn.preprocessing import StandardScaler #for applying PCA function on training and testing sets from sklearn.decomposition import PCA #logistic regression from sklearn.linear_model import LogisticRegression #SVMs from sklearn.svm import SVC #For association rule mining from apyori import apriori #This will allow us to silence the warnings import warnings warnings.simplefilter("ignore") #For the confusion matrix import seaborn as sns # + #Functions that we are going to use in our file: #Creating a function that will change a column data type to category def cat_fun(df, column): df[column] = df[column].astype("category") return(df[column]) #Creating a function that will remove anything in our df and replace it with nothing def remove(df, column, object_to_remove): df[column] = df[column].str.replace(object_to_remove, "") return(df[column]) #Creating a function that will discretize our columns based on quartiles def quartile_discretize(df, column, categories): df[column] = pd.qcut(df[column], 4, labels = categories) return(df[column]) #Creating a function that will merge our dfs with a left join def left_merge_2_conditions(df1, df2, column1, column2): df = pd.merge(df1, df2, how = "left", on=[column1, column2]) return(df) #Creating a function that groups by, counts, creates a new column from the index, drops the index and changes the column names def groupby_count(df, groupby_column, count_column): new_df = pd.DataFrame(df.groupby(groupby_column)[count_column].count()) new_df.columns = ["count"] new_df[groupby_column] = new_df.index.get_level_values(0) new_df.reset_index(drop = True, inplace = True) return(new_df) #Creating a function that groups by, counts, creates a new column from the index, drops the index and changes the column names def groupby_2_count(df, groupby_column1, groupby_column2, count_column): new_df = pd.DataFrame(df.groupby([groupby_column1, groupby_column2 ])[count_column].count()) new_df.columns = ["count"] new_df[groupby_column1] = new_df.index.get_level_values(0) new_df[groupby_column2] = new_df.index.get_level_values(1) new_df.reset_index(drop = True, inplace = True) return(new_df) #Creating a function that groups by, counts, creates a new column from the index, drops the index and changes the column names def groupby_3_count(df, groupby_column1, groupby_column2, groupby_column3, count_column): new_df = pd.DataFrame(df.groupby([groupby_column1, groupby_column2, groupby_column3 ])[count_column].count()) new_df.columns = ["count"] new_df[groupby_column1] = new_df.index.get_level_values(0) new_df[groupby_column2] = new_df.index.get_level_values(1) new_df[groupby_column3] = new_df.index.get_level_values(2) new_df.reset_index(drop = True, inplace = True) return(new_df) # Going to use matplotlib for plotting... # To create a plot we followed the following formula: # df.plot(x-axis, y-axis, kind = type of plot, color = [(we specified colors to use here)], legend = False (we did not # want a legend displayed), title = "Title") then we added a ylabel with plt.ylabel("Type label here") and an x label # with plt.xlabel("type label here"). Finally, we wanted to change the direction of the xtick names from a 90 degree angle # to no angle with plt.xticks(rotation = rotation angle desired) def bar_graph_count(df, x_column, y_column, title): g = df.plot(x_column, y_column, kind = "bar", legend = False, title = title) g = plt.ylabel(y_column) g = plt.xlabel(x_column) return(g) #This will calculate the exponential moving average of the columns we want #exponential moving averages give more weight to the most recent data and less weight to older data def exp_moving_avg(d, column_to_be_meaned): d["exp_moving_avg"] = d[column_to_be_meaned].ewm(com = 0.5,adjust=False).mean() exp_moving_avg = list(d["exp_moving_avg"]) #Adding a 0 to the first entry to exp_moving_avg exp_moving_avg = [0] + exp_moving_avg #Removing the last entry in the list exp_moving_avg.pop() #Creating a column named exp_moving_avg with the results d["exp_moving_avg"] = exp_moving_avg return(exp_moving_avg) #This will calculate the cumulative moving average def cumulative_moving_avg(d): d["moving_avg"] = d.expanding(min_periods = 1).mean() moving_avg = list(d["moving_avg"]) #Adding a 0 to the first entry to moving avg cumulative_moving_avg = [0] + moving_avg #Removing the last entry in the list cumulative_moving_avg.pop() return(cumulative_moving_avg) #This will get the list of all of the entries in the column that we are interested in for calculating the averages def getting_list_of_entries(df, column_interested_in, column_to_be_meaned): avg_people = pd.DataFrame(df.groupby([column_interested_in, "released"])[column_to_be_meaned].mean()) avg_column_scores = pd.DataFrame() column_interested = list(df[column_interested_in].unique()) return([avg_people, column_interested]) #This will make a df for our moving averages that we are calculating def making_df(people_df, column_interested_in, released, person, cumulative_avg, exp_avg): df_2 = pd.DataFrame({column_interested_in: person, "released": released, "cumulative_mean": cumulative_avg, "exp_mean": exp_avg}) return(df_2) #This includes the functions above, and will calculate the exponential and cumulative moving averages for which ever #column we specify and return a df will the column interested in, released, cumulative_mean, exp_mean def calculating_moving_avg(df, column_interested_in, column_to_be_meaned, ty): people_df = pd.DataFrame() people = getting_list_of_entries(df, column_interested_in, column_to_be_meaned) cumulative_avg = [] avg_people = people[0] avg_people for person in people[1]: d = avg_people.groupby(column_interested_in).get_group(person) cumulative_avg = cumulative_moving_avg(d) exp_avg = exp_moving_avg(d, column_to_be_meaned) d.reset_index(inplace = True) released = d["released"] df = pd.DataFrame({column_interested_in: person, "released": released, ty+"_cumulative_mean_"+column_interested_in : cumulative_avg, ty+"_exp_mean_"+column_interested_in: exp_avg}) people_df = people_df.append(df) return(people_df) #Confusion Matrix Graph Function def confusion_matrix_graph (cm, accuracy_label, type_of_df): g = plt.figure(figsize=(2,2)) g = sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r', cbar = False); g = plt.ylabel('Actual'); g = plt.xlabel('Predicted'); g = all_sample_title = type_of_df +' Accuracy Score: {0}'.format(round(accuracy_label, 4)) g = plt.title(all_sample_title, size = 12); return(g) # - #reading in the V2_TN_reports.csv that we scraped movies = pd.read_csv("V2_TN_reports_dates.csv", encoding = "ISO-8859-1") movies.head() #We are dropping the first column named Unnamed:0 movies.drop("Unnamed: 0", axis = 1, inplace = True) movies.shape #We have 1987 movies and 19 columns in our current df #We are going to drop any rows if they have nas or missing values for budget movies.dropna(inplace = True) len(movies) #We are going to check to see if we have any duplicates movies.drop_duplicates(subset ="Title", keep = "first", inplace = True) len(movies.Title.unique()) #We had 16 movies with missing values... #Now we are going to drop any movies with 0s in budget movies = movies[movies["ProductionBudget"] != "$0"] movies = movies.reset_index() len(movies) #We did not have any movies with a 0 budget #We are going to drop any movies with a DomesticBoxOffice of 0 movies = movies[movies["DomesticBoxOffice"] != "$0"] movies = movies.reset_index() len(movies) # + #We had 19 movies with missing domestic box office info #We are going to change column names to something a little more user friendly. First, we will look at the column names movies.columns # - movies.drop(['level_0', 'index'], axis = 1, inplace = True) column_names = ["creative_type", "domestic_box_office", "genre", "inflated_adj_dom_box_office", "int_box_office", "max_theaters", "open_wkend_rev", "open_wkend_theaters", "budget", "production_method", "released", "released_ww", "year", "year_ww", "source", "distributor", "engagements", "title", "world_wide_box_office"] movies.columns = column_names movies.head() #Looking at the data type for each column in our df movies.dtypes movies.creative_type.describe() # Eventually, we need to change the following to numeric: # domestic_box_office # inflated_adj_dom_box_office # int_box_office # max_theathers # open_wkend_rev # open_wkend_theaters # budget # engagements # world_wide_box_office # We need to change the following to category: # creative_type # genre # production_method # source # distributor # We need to change the following to date: # released # released ww #Once we are done cleaning the data we are going to change the data types of the above questions. #If we change them now, when we clean the df and removed rows, the old categories #remain, and still show as possible categories. #First we need to replace the $ and ',' in the columns to be changed to numeric #First, creating a list of columns that we want to change to numeric numeric_columns = ["domestic_box_office", "inflated_adj_dom_box_office", "int_box_office", "max_theaters", "open_wkend_rev", "open_wkend_theaters", "budget", "engagements", "world_wide_box_office"] #We are using our remove function which takes the following arguments: df, column, item to remove movies["domestic_box_office"] = remove(movies, "domestic_box_office", "$") movies["domestic_box_office"] = remove(movies, "domestic_box_office", ",") movies["inflated_adj_dom_box_office"] = remove(movies, "inflated_adj_dom_box_office", "$") movies["inflated_adj_dom_box_office"] = remove(movies, "inflated_adj_dom_box_office", ",") movies["int_box_office"] = remove(movies, "int_box_office", "$") movies["int_box_office"] = remove(movies, "int_box_office", ",") movies["max_theaters"] = remove(movies, "max_theaters", ",") movies["open_wkend_theaters"] = remove(movies, "open_wkend_theaters", ",") movies["open_wkend_rev"] = remove(movies, "open_wkend_rev", "$") movies["open_wkend_rev"] = remove(movies, "open_wkend_rev", ",") movies["budget"] = remove(movies, "budget", "$") movies["budget"] = remove(movies, "budget", ",") movies["engagements"] = remove(movies, "engagements", ",") movies["world_wide_box_office"] = remove(movies, "world_wide_box_office", "$") movies["world_wide_box_office"] = remove(movies, "world_wide_box_office", ",") #Changing all of the columns in numeric_columns to numeric movies[numeric_columns] = movies[numeric_columns].apply(pd.to_numeric) # We need to change the following to date: released, released ww movies["released"] = pd.to_datetime(movies["released"]) movies["released_ww"] = pd.to_datetime(movies["released_ww"]) #Separating the month, day and year into their own columns in case we would like to analyze based on month, day or year movies["month"], movies["day"] = movies["released"].dt.month, movies["released"].dt.day movies["month_ww"], movies["day_ww"] = movies["released_ww"].dt.month, movies["released_ww"].dt.day #Checking data types again movies.dtypes #Changing the month to an ordered category cat = list(range(1,13)) #Changing the month data type from int to ordered category movies["month"] = pd.Categorical(movies["month"], ordered = True, categories = cat) movies["month_ww"] = pd.Categorical(movies["month_ww"], ordered = True, categories = cat) #Checking to see if it worked movies.month.dtype #Creating columns named domestic_profit, int_profit, ww_profit #We want to be able to look at the profit for each movie... Therefore we are creating a #profit column which is gross - budget movies["dom_profit"] = movies["domestic_box_office"] - movies["budget"] movies["int_profit"] = movies["int_box_office"] - movies["budget"] movies["ww_profit"] = movies["world_wide_box_office"] - movies["budget"] #Looking to see if that helped movies.head() #Creating a percent profit column to have a normalized way to compare profits. #percent_profit = profit/budget*100 movies["dom_percent_profit"] = movies["dom_profit"]/movies["budget"]*100 movies["int_percent_profit"] = movies["int_profit"]/movies["budget"]*100 movies["ww_percent_profit"] = movies["ww_profit"]/movies["budget"]*100 #checking to see that worked movies.head() #Writing the clean version of the df to a csv file #movies.to_csv("clean.csv", index = False) # + # #For some reason the functions do not work without rereading in the csv file... # movies = pd.read_csv("clean.csv", encoding = "ISO-8859-1") # - len(movies.domestic_box_office.unique()) #Aggregating a moving average column and calculating the mean average pp for each creative type; #by calculating the mean pp for all creative types but for only the movies prior to the #movie we are calculting the mean for. dom_ct_ma = calculating_moving_avg(movies, "creative_type", "dom_percent_profit", "dom") int_ct_ma = calculating_moving_avg(movies, "creative_type", "int_percent_profit", "int") ww_ct_ma = calculating_moving_avg(movies, "creative_type", "ww_percent_profit", "ww") # #Genres: dom_genre_ma = calculating_moving_avg(movies, "genre", "dom_percent_profit", "dom") int_genre_ma = calculating_moving_avg(movies, "genre", "int_percent_profit", "int") ww_genre_ma = calculating_moving_avg(movies, "genre", "ww_percent_profit", "ww") # production_method: dom_pm_ma = calculating_moving_avg(movies, "production_method", "dom_percent_profit", "dom") int_pm_ma = calculating_moving_avg(movies, "production_method", "int_percent_profit", "int") ww_pm_ma = calculating_moving_avg(movies, "production_method", "ww_percent_profit", "ww") # source dom_source_ma = calculating_moving_avg(movies, "source", "dom_percent_profit", "dom") int_source_ma = calculating_moving_avg(movies, "source", "int_percent_profit", "int") ww_source_ma = calculating_moving_avg(movies, "source", "ww_percent_profit", "ww") # distributor: dom_distributor_ma = calculating_moving_avg(movies, "distributor", "dom_percent_profit", "dom") int_distributor_ma = calculating_moving_avg(movies, "distributor", "int_percent_profit", "int") ww_distributor_ma = calculating_moving_avg(movies, "distributor", "ww_percent_profit", "ww") #Month dom_month_ma = calculating_moving_avg(movies, "month", "dom_percent_profit", "dom") int_month_ma = calculating_moving_avg(movies, "month", "int_percent_profit", "int") ww_month_ma = calculating_moving_avg(movies, "month", "ww_percent_profit", "ww") # + #We are going to use our left_merge_2_conditions function: #Inputs: df1, df2, column to merge on 1 and column to merge on 2 #Creating a movies domestic df movies_dom = left_merge_2_conditions(movies, dom_ct_ma, "creative_type", "released") movies_dom = left_merge_2_conditions(movies_dom, dom_genre_ma, "genre", "released") movies_dom = left_merge_2_conditions(movies_dom, dom_pm_ma, "production_method", "released") movies_dom = left_merge_2_conditions(movies_dom, dom_source_ma, "source", "released") movies_dom = left_merge_2_conditions(movies_dom, dom_distributor_ma, "distributor", "released") movies_dom = left_merge_2_conditions(movies_dom, dom_month_ma, "month", "released") #Creating a movies_int df movies_int = left_merge_2_conditions(movies, int_ct_ma, "creative_type", "released") movies_int = left_merge_2_conditions(movies_int, int_genre_ma, "genre", "released") movies_int = left_merge_2_conditions(movies_int, int_pm_ma, "production_method", "released") movies_int = left_merge_2_conditions(movies_int, int_source_ma, "source", "released") movies_int = left_merge_2_conditions(movies_int, int_distributor_ma, "distributor", "released") movies_int = left_merge_2_conditions(movies_int, int_month_ma, "month", "released") #Creating a movies_ww df movies_ww = left_merge_2_conditions(movies, ww_ct_ma, "creative_type", "released") movies_ww = left_merge_2_conditions(movies_ww, ww_genre_ma, "genre", "released") movies_ww = left_merge_2_conditions(movies_ww, ww_pm_ma, "production_method", "released") movies_ww = left_merge_2_conditions(movies_ww, ww_source_ma, "source", "released") movies_ww = left_merge_2_conditions(movies_ww, ww_distributor_ma, "distributor", "released") movies_ww = left_merge_2_conditions(movies_ww, ww_month_ma, "month", "released") # - #Looking at the movies_dom df head len(movies_dom) #Getting the column names for movies_dom movies_dom.columns #removing released_ww, year_ww, world_wide_box_office, month_ww, day_ww, int_profit, ww_profit columns_to_remove = ["released_ww", "year_ww", "world_wide_box_office", "month_ww", "day_ww", "int_profit", "ww_profit", "int_percent_profit", "ww_percent_profit", "int_box_office", "domestic_box_office", "inflated_adj_dom_box_office", "max_theaters", "engagements", "dom_profit"] movies_dom.drop(columns_to_remove, axis = 1, inplace = True) movies_dom.columns #Creating an aggregated column to see if the open_wken_rev/open_wkend_theaters shows if a movie is in more demand movies_dom["open_wkend_rev/open_wkend_theaters"] = movies_dom["open_wkend_rev"]/movies_dom["open_wkend_theaters"] # + #We are removing any rows that have 0s for the newly calculated columns #Looking to see what happens if we remove all the movies with a 0 for exp_mean_director and exp_mean_star movies_dom = movies_dom[movies_dom["dom_cumulative_mean_creative_type"] != 0] movies_dom = movies_dom[movies_dom["dom_cumulative_mean_genre"] != 0] movies_dom = movies_dom[movies_dom["dom_cumulative_mean_production_method"] != 0] movies_dom = movies_dom[movies_dom["dom_cumulative_mean_source"] != 0] movies_dom = movies_dom[movies_dom["dom_cumulative_mean_distributor"] != 0] movies_dom = movies_dom[movies_dom["dom_cumulative_mean_month"] != 0] movies_dom.dropna(inplace = True) # - len(movies_dom) #We still have 1859 movies in our df #Changing creative_type, genre, production_method, source, distributor to category #We are using our cat_fun which takes the following inputs: df, column to change movies_dom["creative_type"] = cat_fun(movies_dom, "creative_type") movies_dom["genre"] = cat_fun(movies_dom, "genre") movies_dom["production_method"] = cat_fun(movies_dom, "production_method") movies_dom["source"] = cat_fun(movies_dom, "source") movies_dom["distributor"] = cat_fun(movies_dom, "distributor") #Repeating the above process for movies_int #Looking at the movies_int columns movies_int.columns #Removing columns that might unduly influence our prediction method for movies_int columns_to_remove = ["domestic_box_office", "inflated_adj_dom_box_office", "int_box_office", "max_theaters", "world_wide_box_office", "engagements", "dom_profit", "int_profit", "ww_profit", "dom_percent_profit", "ww_percent_profit", "released", "year", "month", "day"] movies_int.drop(columns_to_remove, axis = 1, inplace = True) movies_int.columns #Aggregating a new column for open_wken_rev_by_theater; we think that it might show if a movie is more in demand or not. #If a movie made $1 million, but was only shown in 100 theaters and another movie made $1 million but was shown, in 300 #theaters, it might show that movie 1 was more in demand than movie 2... movies_int["open_wkend_rev/open_wkend_theaters"] = movies_int["open_wkend_rev"]/movies_int["open_wkend_theaters"] # + #We are removing any rows that have 0s for the newly calculated columns #Looking to see what happens if we remove all the movies with a 0 for exp_mean_director and exp_mean_star movies_int = movies_int[movies_int["int_cumulative_mean_creative_type"] != 0] movies_int = movies_int[movies_int["int_cumulative_mean_genre"] != 0] movies_int = movies_int[movies_int["int_cumulative_mean_production_method"] != 0] movies_int = movies_int[movies_int["int_cumulative_mean_source"] != 0] movies_int = movies_int[movies_int["int_cumulative_mean_distributor"] != 0] movies_int = movies_int[movies_int["int_cumulative_mean_month"] != 0] movies_int.dropna(inplace = True) # - #We still have 1859 movies after removing any of the aggregated columns with a 0 in them len(movies_int) #Changing creative_type, genre, production_method, source, distributor to category #We are using our cat_fun which takes the following inputs: df, column to change movies_int["creative_type"] = cat_fun(movies_int, "creative_type") movies_int["genre"] = cat_fun(movies_int, "genre") movies_int["production_method"] = cat_fun(movies_int, "production_method") movies_int["source"] = cat_fun(movies_int, "source") movies_int["distributor"] = cat_fun(movies_int, "distributor") #repeating the process for ww movies_ww.columns #Removing columns that would be unfair in our prediction methods columns_to_remove = ["domestic_box_office", "inflated_adj_dom_box_office", "int_box_office", "max_theaters", "engagements", "world_wide_box_office", "dom_profit", "int_profit", "ww_profit", "dom_percent_profit", "int_percent_profit"] movies_ww.drop(columns_to_remove, axis = 1, inplace = True) movies_ww.columns #Aggregating a new column for open_wken_rev_by_theater; we think that it might show if a movie is more in demand or not. #If a movie made $1 million, but was only shown in 100 theaters and another movie made $1 million but was shown, in 300 #theaters, it might show that movie 1 was more in demand than movie 2... movies_ww["open_wkend_rev/open_wkend_theaters"] = movies_ww["open_wkend_rev"]/movies_ww["open_wkend_theaters"] #We are removing any rows that have 0s for the newly calculated columns #Looking to see what happens if we remove all the movies with a 0 for exp_mean_director and exp_mean_star movies_ww = movies_ww[movies_ww["ww_cumulative_mean_creative_type"] != 0] movies_ww = movies_ww[movies_ww["ww_cumulative_mean_genre"] != 0] movies_ww = movies_ww[movies_ww["ww_cumulative_mean_production_method"] != 0] movies_ww = movies_ww[movies_ww["ww_cumulative_mean_source"] != 0] movies_ww = movies_ww[movies_ww["ww_cumulative_mean_distributor"] != 0] movies_ww = movies_ww[movies_ww["ww_cumulative_mean_month"] != 0] len(movies_ww) #We still have 1859 movies in our df #Changing creative_type, genre, production_method, source, distributor to category #We are using our cat_fun which takes the following inputs: df, column to change movies_ww["creative_type"] = cat_fun(movies_ww, "creative_type") movies_ww["genre"] = cat_fun(movies_ww, "genre") movies_ww["production_method"] = cat_fun(movies_ww, "production_method") movies_ww["source"] = cat_fun(movies_ww, "source") movies_ww["distributor"] = cat_fun(movies_ww, "distributor") # + # movies_dom.to_csv("movies_dom.csv") # movies_int.to_csv("movies_int.csv") # movies_ww.to_csv("movies_ww.csv") # + #We have the same movies with the same discrete columns in our 3 dfs... Therefore, we are only going to perform #exploratory data analysis on one, but it will mimic the other 2 dfs # + #What is the breakdown of genre in our df? #Getting the count of movies for each genre in our df and saving it as a pandas df. #We are grouping by genre and then getting the count of the genre column in each group by #we could have used any column to get the count of... #We are using the groupby_count function that takes the following arguments (df, groupby_column, count_column) movies_dom_genre = groupby_count(movies_dom, "genre", "genre") movies_dom_genre # - #Using our bar_graph_count function to visualize the movies_genre group #It takes the following inputs: df, x_column, y_column, title movies_dom_genre.sort_values(['count'], ascending=[False], inplace = True) bar_graph_count(movies_dom_genre, "genre", "count", "Visualization of the Number of Movies per Genre") #Creating a data frame of the movies creative_type count movies_ct = groupby_count(movies_dom, "creative_type", "creative_type") movies_ct["creative_type"] #Sorting the df, so the bar graph will be in descending order movies_ct.sort_values(['count'], ascending=[False], inplace = True) bar_graph_count(movies_ct, "creative_type", "count", "Visualization of the Number of Movies per Creative Type") movies_year = groupby_count(movies_dom, "year", "genre") movies_year bar_graph_count(movies_year, "year", "count", "Visualization of the Number of Movies per Year") movies_month = groupby_count(movies_dom, "month", "genre") movies_month bar_graph_count(movies_month, "month", "count", "Visualization of the Number of Movies per Month") movies_source = groupby_count(movies_dom, "source", "genre") movies_source movies_source.sort_values(['count'], ascending=[False], inplace = True) bar_graph_count(movies_source, "source", "count", "Visualization of the Number of Movies per Source") movies_distributor = groupby_count(movies_dom, "distributor", "genre") movies_distributor movies_distributor = movies_distributor[movies_distributor["count"] > 0] movies_distributor movies_distributor.sort_values(['count'], ascending=[False], inplace = True) bar_graph_count(movies_distributor, "distributor", "count", "Visualization of the Number of Movies per Distributor") movies_production_method = groupby_count(movies_dom, "production_method", "genre") movies_production_method movies_production_method.sort_values(['count'], ascending=[False], inplace = True) bar_graph_count(movies_production_method, "production_method", "count", "Visualization of the Number of Movies per Production Method") # + ###################################################################################################################### # # We are ready to create our testing and training dfs, we are going to see if we can predict percent_profit # For the domestic movies we have a company called "Flops are Us" and we want to see if we can predict if a # movie will be a flop or not after the first weekend. # # We will also try to predict percent profit without the open_wkend_rev and open_wken_rev/open_wkend_theaters # ###################################################################################################################### # + ################################################################# #Naive Bayes #**All Numerica Data *** ################################################################# # - #Creating a test_train df for each of our 3 dfs test_train_movies_dom = movies_dom.copy() test_train_movies_int = movies_int.copy() test_train_movies_ww = movies_ww.copy() test_train_movies_dom.columns #Need to remove "creative_type", "genre", "production_method", "released", "source", "distributor", "title" columns_to_remove = ["creative_type", "genre", "production_method", "released", "source", "distributor", "title", "open_wkend_rev/open_wkend_theaters", "open_wkend_rev", "budget", "year", "month", "day", "open_wkend_theaters"] columns_to_remove_ex = ["dom_cumulative_mean_creative_type", "dom_cumulative_mean_genre", "dom_cumulative_mean_production_method", "dom_cumulative_mean_source", "dom_cumulative_mean_distributor", "dom_cumulative_mean_month"] columns_to_remove_cumulative = ["dom_exp_mean_creative_type", "dom_exp_mean_genre", "dom_exp_mean_production_method", "dom_exp_mean_source", "dom_exp_mean_distributor", "dom_exp_mean_month"] test_train_movies_dom.drop(columns_to_remove, axis = 1, inplace = True) test_train_movies_dom_ex = test_train_movies_dom.copy() test_train_movies_dom_cumulative = test_train_movies_dom.copy() test_train_movies_dom_ex.drop(columns_to_remove_ex, axis = 1, inplace = True) test_train_movies_dom_cumulative.drop(columns_to_remove_cumulative, axis = 1, inplace = True) test_train_movies_dom.columns test_train_movies_int.columns #Need to remove "creative_type", "genre", "production_method", "released_ww", "source", "distributor", "title" columns_to_remove = ["creative_type", "genre", "production_method", "released_ww", "source", "distributor", "title"] test_train_movies_int.drop(columns_to_remove, axis = 1, inplace = True) test_train_movies_ww.columns #Need to remove "creative_type", "genre", "production_method", "released_ww", "released", "source", "distributor", "title" columns_to_remove = ["creative_type", "genre", "production_method", "released_ww", "released", "source", "distributor", "title"] test_train_movies_ww.drop(columns_to_remove, axis = 1, inplace = True) # + #We have to descritze percent profit... We are interested if we will have a negative percent profit or a positive percent profit categories = ["negative", "positive"] #Negative anything less than or equal to .0001 #positive anything greater than .0001 test_train_movies_dom["percent_profit"] = pd.cut(test_train_movies_dom["dom_percent_profit"], [-101, 0.0001, 999999], labels = categories) test_train_movies_dom_ex["percent_profit"] = pd.cut(test_train_movies_dom["dom_percent_profit"], [-101, 0.0001, 999999], labels = categories) test_train_movies_dom_cumulative["percent_profit"] = pd.cut(test_train_movies_dom["dom_percent_profit"], [-101, 0.0001, 999999], labels = categories) # test_train_movies_int["percent_profit"] = pd.cut(test_train_movies_int["int_percent_profit"], [-101, 0.0001, 999999], labels = categories) # test_train_movies_ww["percent_profit"] = pd.cut(test_train_movies_ww["ww_percent_profit"], [-101, 0.0001, 999999], labels = categories) # - #Getting the count of each category in our test_train_movies_dom df test_train_movies_dom_count = test_train_movies_dom.groupby("percent_profit")["percent_profit"].count() test_train_movies_dom_count # + # We are going to create a testing and training df that contains 386 negative, 386 positive percent_profits #First we are going to subset the positive percent profits and the negative per+cent_profits positive = test_train_movies_dom[test_train_movies_dom["percent_profit"] == "positive"] test_train_movies_dom = test_train_movies_dom[test_train_movies_dom["percent_profit"] == "negative"] positive_ex = test_train_movies_dom_ex[test_train_movies_dom_ex["percent_profit"] == "positive"] test_train_movies_dom_ex = test_train_movies_dom_ex[test_train_movies_dom_ex["percent_profit"] == "negative"] positive_cumulative = test_train_movies_dom_cumulative[test_train_movies_dom_cumulative["percent_profit"] == "positive"] test_train_movies_dom_cumulative = test_train_movies_dom_cumulative[test_train_movies_dom_cumulative["percent_profit"] == "negative"] #Getting the length to make sure that we have 204 negative, 771 postive in our df print(len(positive)) print(len(test_train_movies_dom)) # - #Now getting a random sample of 198 entries in the positive df and setting the seed to 123 #to reproduce the results positive = positive.sample(n = 204, random_state = 1201) positive_ex = positive_ex.sample(n = 204, random_state = 1201) positive_cumulative = positive_cumulative.sample(n = 204, random_state = 1201) #Getting the length to make sure that it worked print(len(positive)) #Adding the positive movies back to the test_train_movies_pp df test_train_movies_dom = pd.concat([test_train_movies_dom, positive]) test_train_movies_dom_ex = pd.concat([test_train_movies_dom_ex, positive_ex]) test_train_movies_dom_cumulative = pd.concat([test_train_movies_dom_cumulative, positive_cumulative]) #Getting the length to make sure that the 2 df were combined correctly and if it did we would have 408 movies in our df len(test_train_movies_dom) # + # #Repeating the process for test_train_movies_int # #Getting the count of each category in our test_train_movies_int df # test_train_movies_int_count = test_train_movies_int.groupby("percent_profit")["percent_profit"].count() # test_train_movies_int_count # + # # We are going to create a testing and training df that contains 420 negative, 420 positive percent_profits # #First we are going to subset the positive percent profits and the negative per+cent_profits # positive = test_train_movies_int[test_train_movies_int["percent_profit"] == "positive"] # test_train_movies_int = test_train_movies_int[test_train_movies_int["percent_profit"] == "negative"] # #Getting the length to make sure that we have 229 negative, 739 postive in our df # print(len(positive)) # print(len(test_train_movies_int)) # + # #Now getting a random sample of 420 entries in the positive df and setting the seed to 123 # #to reproduce the results # positive = positive.sample(n = 229, random_state = 1201) # #Getting the length to make sure that it worked # print(len(positive)) # + # #Adding the positive movies back to the test_train_movies_pp df # test_train_movies_int = pd.concat([test_train_movies_int, positive]) # #Getting the length to make sure that the 2 df were combined correctly and if it did we would have 458 movies in our df # len(test_train_movies_int) # + # #Repeating the process for test_train_movies_ww # #Getting the count of each category in our test_train_movies_ww df # test_train_movies_ww_count = test_train_movies_ww.groupby("percent_profit")["percent_profit"].count() # test_train_movies_ww_count # + #We do not have sufficient information to predict a negative or positive percent profit for world wide movies # We need more movies with a negative world wide percent profit... Although this is extremely interesting and # suggests that movies that have a negative domestic profit should release the movie internationally to recover # + # #Changing the data type of month day and year to numeric # columns = ["month", "day"] # columns_ww = ["month_ww", "day_ww"] # test_train_movies_dom[columns] = test_train_movies_dom[columns].apply(pd.to_numeric) # test_train_movies_dom_ex[columns] = test_train_movies_dom_ex[columns].apply(pd.to_numeric) # test_train_movies_dom_cumulative[columns] = test_train_movies_dom_cumulative[columns].apply(pd.to_numeric) # # test_train_movies_ww[columns_ww] = test_train_movies_ww[columns_ww].apply(pd.to_numeric) # + # test_train_movies_dom.reset_index(inplace = True) # test_train_movies_int.reset_index(inplace = True) # test_train_movies_dom.drop("level_0", axis = 1, inplace = True) # test_train_movies_int.drop("level_0", axis = 1, inplace = True) # - # #removing the label from the test_train_movies_dom and int df and saving it in a label df test_train_movies_dom_label = test_train_movies_dom["percent_profit"] test_train_movies_dom.drop("percent_profit", axis = 1, inplace = True) test_train_movies_dom_ex_label = test_train_movies_dom_ex["percent_profit"] test_train_movies_dom_ex.drop("percent_profit", axis = 1, inplace = True) test_train_movies_dom_cumulative_label = test_train_movies_dom_cumulative["percent_profit"] test_train_movies_dom_cumulative.drop("percent_profit", axis = 1, inplace = True) #repeating the process for int # test_train_movies_int_label = test_train_movies_int["percent_profit"] # test_train_movies_int.drop("percent_profit", axis = 1, inplace = True) #Creating 4 df: 1: the training df with label removed, 2: the testing df with label removed, 3: the training label, 4: testing label from sklearn.model_selection import train_test_split dom_train, dom_test, dom_train_label, dom_test_label = train_test_split(test_train_movies_dom, test_train_movies_dom_label, test_size = .3, random_state = 116) dom_ex_train, dom_ex_test, dom_ex_train_label, dom_ex_test_label = train_test_split(test_train_movies_dom_ex, test_train_movies_dom_ex_label, test_size = .3, random_state = 116) dom_cum_train, dom_cum_test, dom_cum_train_label, dom_cum_test_label = train_test_split(test_train_movies_dom_cumulative, test_train_movies_dom_cumulative_label, test_size = .3, random_state = 116) # int_train, int_test, int_train_label, int_test_label = train_test_split(test_train_movies_int, test_train_movies_int_label, test_size = .3, random_state = 123) #Getting a count of percent_profit in our test label scores in out test label #We want to have roughly the same number of positive and negative movies in our test df print(Counter(dom_test_label)) # print(Counter(int_test_label)) # + #Using the standard scale to help preprocess and normalize the data # performing preprocessing part sc = StandardScaler() dom_train = sc.fit_transform(dom_train) dom_test = sc.transform(dom_test) dom_ex_train = sc.fit_transform(dom_ex_train) dom_ex_test = sc.transform(dom_ex_test) dom_cum_train = sc.fit_transform(dom_cum_train) dom_cum_test = sc.transform(dom_cum_test) # int_train = sc.fit_transform(int_train) # int_test = sc.transform(int_test) # + #Attempt 1: all variables clf = GaussianNB() clf.fit(dom_train, dom_train_label) test_predicted_dom_nb = clf.predict(dom_test) clf.fit(dom_ex_train, dom_ex_train_label) test_predicted_dom_ex_nb = clf.predict(dom_ex_test) clf.fit(dom_cum_train, dom_cum_train_label) test_predicted_dom_cum_nb = clf.predict(dom_cum_test) # clf.fit(int_train, int_train_label) # test_predicted_int_nb = clf.predict(int_test) # - #Accuracy for dom dom_accuracy_nb = accuracy_score(dom_test_label, test_predicted_dom_nb, normalize = True) cm = confusion_matrix(dom_test_label, test_predicted_dom_nb) confusion_matrix_graph(cm, dom_accuracy_nb, "Dom") dom_ex_accuracy_nb = accuracy_score(dom_ex_test_label, test_predicted_dom_ex_nb, normalize = True) cm = confusion_matrix(dom_ex_test_label, test_predicted_dom_ex_nb) confusion_matrix_graph(cm, dom_ex_accuracy_nb, "Dom") dom_cum_accuracy_nb = accuracy_score(dom_cum_test_label, test_predicted_dom_cum_nb, normalize = True) cm = confusion_matrix(dom_cum_test_label, test_predicted_dom_cum_nb) confusion_matrix_graph(cm, dom_cum_accuracy_nb, "Dom")
assets/all_html/2019_10_14_Final_Project_V2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Chapter 5: Bits & Numbers # + [markdown] slideshow={"slide_type": "skip"} # After learning about the basic building blocks of expressing and structuring the business logic in programs, we focus our attention on the **data types** Python offers us, both built-in and available via the [standard library](https://docs.python.org/3/library/index.html) or third-party packages. # # We start with the "simple" ones: Numeric types in this chapter and textual data in [Chapter 6](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/06_text_00_lecture.ipynb). An important fact that holds for all objects of these types is that they are **immutable**. To reuse the bag analogy from [Chapter 1](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/01_elements_00_lecture.ipynb#Objects-vs.-Types-vs.-Values), this means that the $0$s and $1$s making up an object's *value* cannot be changed once the bag is created in memory, implying that any operation with or method on the object creates a *new* object in a *different* memory location. # # [Chapter 7](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/07_sequences_00_lecture.ipynb), [Chapter 8](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/08_mappings_00_lecture.ipynb), and [Chapter 9](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/09_arrays_00_lecture.ipynb) then cover the more "complex" data types, including, for example, the `list` type. Finally, Chapter 10 completes the picture by introducing language constructs to create custom types. # # We have already seen many hints indicating that numbers are not as trivial to work with as it seems at first sight: # # - [Chapter 1](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/01_elements_00_lecture.ipynb#%28Data%29-Type-%2F-%22Behavior%22) reveals that numbers may come in *different* data types (i.e., `int` vs. `float` so far), # - [Chapter 3](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/03_conditionals_00_lecture.ipynb#Boolean-Expressions) raises questions regarding the **limited precision** of `float` numbers (e.g., `42 == 42.000000000000001` evaluates to `True`), and # - [Chapter 4](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/04_iteration_00_lecture.ipynb#Infinite-Recursion) shows that sometimes a `float` "walks" and "quacks" like an `int`, whereas the reverse is true. # # This chapter introduces all the [built-in numeric types](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex): `int`, `float`, and `complex`. To mitigate the limited precision of floating-point numbers, we also look at two replacements for the `float` type in the [standard library](https://docs.python.org/3/library/index.html), namely the `Decimal` type in the [decimals](https://docs.python.org/3/library/decimal.html#decimal.Decimal) and the `Fraction` type in the [fractions](https://docs.python.org/3/library/fractions.html#fractions.Fraction) module. # + [markdown] slideshow={"slide_type": "slide"} # ## The `int` Type # + [markdown] slideshow={"slide_type": "skip"} # The simplest numeric type is the `int` type: It behaves like an [integer in ordinary math](https://en.wikipedia.org/wiki/Integer) (i.e., the set $\mathbb{Z}$) and supports operators in the way we saw in the section on arithmetic operators in [Chapter 1](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/01_elements_00_lecture.ipynb#%28Arithmetic%29-Operators). # # One way to create `int` objects is by simply writing its value as a literal with the digits `0` to `9`. # + slideshow={"slide_type": "slide"} a = 42 # + [markdown] slideshow={"slide_type": "skip"} # Just like any other object, the `42` has an identity, a type, and a value. # + slideshow={"slide_type": "fragment"} id(a) # + slideshow={"slide_type": "fragment"} type(a) # + slideshow={"slide_type": "fragment"} a # + [markdown] slideshow={"slide_type": "skip"} # A nice feature in newer Python versions is using underscores `_` as (thousands) separators in numeric literals. For example, `1_000_000` evaluates to `1000000` in memory; the `_` is ignored by the interpreter. # + slideshow={"slide_type": "slide"} 1_000_000 # + [markdown] slideshow={"slide_type": "skip"} # We may place the `_`s anywhere we want. # + slideshow={"slide_type": "fragment"} 1_2_3_4_5_6_7_8_9 # + [markdown] slideshow={"slide_type": "skip"} # It is syntactically invalid to write out leading `0` in numeric literals. The reason for that will become apparent in the next section. # + slideshow={"slide_type": "fragment"} 042 # + [markdown] slideshow={"slide_type": "skip"} # Another way to create `int` objects is with the [int()](https://docs.python.org/3/library/functions.html#int) built-in that casts `float` or properly formatted `str` objects as integers. So, decimals are truncated (i.e., "cut off"). # + slideshow={"slide_type": "slide"} int(42.11) # + slideshow={"slide_type": "fragment"} int(42.87) # + [markdown] slideshow={"slide_type": "skip"} # Whereas the floor division operator `//` effectively rounds towards negative infinity (cf., the "*(Arithmetic) Operators*" section in [Chapter 1](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/01_elements_00_lecture.ipynb#%28Arithmetic%29-Operators)), the [int()](https://docs.python.org/3/library/functions.html#int) built-in effectively rounds towards `0`. # + slideshow={"slide_type": "fragment"} int(-42.87) # + [markdown] slideshow={"slide_type": "skip"} # When casting `str` objects as `int`, the [int()](https://docs.python.org/3/library/functions.html#int) built-in is less forgiving. We must not include any decimals as shows by the `ValueError`. Yet, leading and trailing whitespace is gracefully ignored. # + slideshow={"slide_type": "slide"} int("42") # + slideshow={"slide_type": "fragment"} int("42.0") # + slideshow={"slide_type": "fragment"} int(" 42 ") # + [markdown] slideshow={"slide_type": "skip"} # The `int` type follows all rules we know from math, apart from one exception: Whereas mathematicians to this day argue what the term $0^0$ means (cf., this [article](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero)), programmers are pragmatic about this and simply define $0^0 = 1$. # + slideshow={"slide_type": "skip"} 0 ** 0 # + [markdown] slideshow={"slide_type": "slide"} # ### Binary Representations # + [markdown] slideshow={"slide_type": "skip"} # As computers can only store $0$s and $1$s, `int` objects are nothing but that in memory as well. Consequently, computer scientists and engineers developed conventions as to how $0$s and $1$s are "translated" into integers, and one such convention is the **[binary representation](https://en.wikipedia.org/wiki/Binary_number)** of **non-negative integers**. Consider the integers from $0$ through $255$ that are encoded into $0$s and $1$s with the help of this table: # + [markdown] slideshow={"slide_type": "slide"} # |Bit $i$| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | # |-------|-----|-----|-----|-----|-----|-----|-----|-----| # | Digit |$2^7$|$2^6$|$2^5$|$2^4$|$2^3$|$2^2$|$2^1$|$2^0$| # | $=$ |$128$| $64$| $32$| $16$| $8$ | $4$ | $2$ | $1$ | # + [markdown] slideshow={"slide_type": "skip"} # A number consists of exactly eight $0$s and $1$s that are read from right to left and referred to as the **bits** of the number. Each bit represents a distinct multiple of $2$, the **digit**. For sure, we start counting at $0$ again. # # To encode the integer $3$, for example, we need to find a combination of $0$s and $1$s such that the sum of digits marked with a $1$ is equal to the number we want to encode. In the example, we set all bits to $0$ except for the first ($i=0$) and second ($i=1$) as $2^0 + 2^1 = 1 + 2 = 3$. So the binary representation of $3$ is $00~00~00~11$. To borrow some terminology from linear algebra, the $3$ is a linear combination of the digits where the coefficients are either $0$ or $1$: $3 = 0*128 + 0*64 + 0*32 + 0*16 + 0*8 + 0*4 + 1*2 + 1*1$. It is *guaranteed* that there is exactly *one* such combination for each number between $0$ and $255$. # # As each bit in the binary representation is one of two values, we say that this representation has a base of $2$. Often, the base is indicated with a subscript to avoid confusion. For example, we write $3_{10} = 00000011_2$ or $3_{10} = 11_2$ for short omitting leading $0$s. A subscript of $10$ implies a decimal number as we know it from elementary school. # # We use the built-in [bin()](https://docs.python.org/3/library/functions.html#bin) function to obtain an `int` object's binary representation: It returns a `str` object starting with `"0b"` indicating the binary format and as many $0$s and $1$s as are necessary to encode the integer omitting leading $0$s. # + slideshow={"slide_type": "slide"} bin(3) # + [markdown] slideshow={"slide_type": "skip"} # We may pass a `str` object formatted this way as the argument to the [int()](https://docs.python.org/3/library/functions.html#int) built-in, together with `base=2`, to create an `int` object, for example, with the value of `3`. # + slideshow={"slide_type": "fragment"} int("0b11", base=2) # + [markdown] slideshow={"slide_type": "skip"} # Moreover, we may also use the contents of the returned `str` object as a **literal** instead: Just like we type, for example, `3` without quotes (i.e., "literally") into a code cell to create the `int` object `3`, we may type `0b11` to obtain an `int` object with the same value. # + slideshow={"slide_type": "fragment"} 0b11 # + [markdown] slideshow={"slide_type": "skip"} # It is convenient to use the underscore `_` to separate the `"0b"` prefix from the bits. # + slideshow={"slide_type": "fragment"} 0b_11 # + [markdown] slideshow={"slide_type": "skip"} # Another example is the integer `123` that is the sum of $64 + 32 + 16 + 8 + 2 + 1$: Thus, its binary representation is the sequence of bits $01~11~10~11$, or to use our new notation, $123_{10} = 1111011_2$. # + slideshow={"slide_type": "skip"} bin(123) # + [markdown] slideshow={"slide_type": "skip"} # Analogous to typing `123` into a code cell, we may write `0b1111011`, or `0b_111_1011` to make use of the underscores, and create an `int` object with the value `123`. # + slideshow={"slide_type": "skip"} 0b_111_1011 # + [markdown] slideshow={"slide_type": "skip"} # `0` and `255` are the edge cases where we set all the bits to either $0$ or $1$. # + slideshow={"slide_type": "slide"} bin(0) # + slideshow={"slide_type": "skip"} bin(1) # + slideshow={"slide_type": "skip"} bin(2) # + slideshow={"slide_type": "fragment"} bin(255) # + [markdown] slideshow={"slide_type": "skip"} # Groups of eight bits are also called a **byte**. As a byte can only represent non-negative integers up to $255$, the table above is extended conceptually with greater digits to the left to model integers beyond $255$. The memory management needed to implement this is built into Python, and we do not need to worry about it. # # For example, `789` is encoded with ten bits and $789_{10} = 1100010101_2$. # + slideshow={"slide_type": "fragment"} bin(789) # + [markdown] slideshow={"slide_type": "skip"} # To contrast this bits encoding with the familiar decimal system, we show an equivalent table with powers of $10$ as the digits: # # |Decimal| 3 | 2 | 1 | 0 | # |-------|------|------|------|------| # | Digit |$10^3$|$10^2$|$10^1$|$10^0$| # | $=$ |$1000$| $100$| $10$ | $1$ | # # Now, an integer is a linear combination of the digits where the coefficients are one of *ten* values, and the base is now $10$. For example, the number $123$ can be expressed as $0*1000 + 1*100 + 2*10 + 3*1$. So, the binary representation follows the same logic as the decimal system taught in elementary school. The decimal system is intuitive to us humans, mostly as we learn to count with our *ten* fingers. The $0$s and $1$s in a computer's memory are therefore no rocket science; they only feel unintuitive for a beginner. # + [markdown] slideshow={"slide_type": "slide"} # #### Arithmetic with Bits # + [markdown] slideshow={"slide_type": "skip"} # Adding two numbers in their binary representations is straightforward and works just like we all learned addition in elementary school. Going from right to left, we add the individual digits, and ... # + slideshow={"slide_type": "slide"} 1 + 2 # + slideshow={"slide_type": "fragment"} bin(1) + " + " + bin(2) + " = " + bin(3) # + [markdown] slideshow={"slide_type": "skip"} # ... if any two digits add up to $2$, the resulting digit is $0$ and a $1$ carries over. # + slideshow={"slide_type": "fragment"} 1 + 3 # + slideshow={"slide_type": "fragment"} bin(1) + " + " + bin(3) + " = " + bin(4) # + [markdown] slideshow={"slide_type": "skip"} # Multiplication is also quite easy. All we need to do is to multiply the left operand by all digits of the right operand separately and then add up the individual products, just like in elementary school. # + slideshow={"slide_type": "slide"} 4 * 3 # + slideshow={"slide_type": "fragment"} bin(4) + " * " + bin(3) + " = " + bin(12) # + slideshow={"slide_type": "fragment"} bin(4) + " * " + bin(1) + " = " + bin(4) # multiply with first digit # + slideshow={"slide_type": "fragment"} bin(4) + " * " + bin(2) + " = " + bin(8) # multiply with second digit # + [markdown] slideshow={"slide_type": "skip"} # The "*Further Resources*" section at the end of this chapter provides video tutorials on addition and multiplication in binary. Subtraction and division are a bit more involved but essentially also easy to understand. # + [markdown] slideshow={"slide_type": "slide"} # ### Hexadecimal Representations # + [markdown] slideshow={"slide_type": "skip"} # While in the binary and decimal systems there are two and ten distinct coefficients per digit, another convenient representation, the **hexadecimal representation**, uses a base of $16$. It is convenient as one digit stores the same amount of information as *four* bits and the binary representation quickly becomes unreadable for larger numbers. The letters "a" through "f" are used as digits "10" through "15". # # The following table summarizes the relationship between the three systems: # + [markdown] slideshow={"slide_type": "slide"} # |Decimal|Hexadecimal|Binary|$~~~~~~$|Decimal|Hexadecimal|Binary|$~~~~~~$|Decimal|Hexadecimal|Binary|$~~~~~~$|...| # |-------|-----------|------|--------|-------|-----------|------|--------|-------|-----------|------|--------|---| # | 0 | 0 | 0000 |$~~~~~~$| 16 | 10 | 10000|$~~~~~~$| 32 | 20 |100000|$~~~~~~$|...| # | 1 | 1 | 0001 |$~~~~~~$| 17 | 11 | 10001|$~~~~~~$| 33 | 21 |100001|$~~~~~~$|...| # | 2 | 2 | 0010 |$~~~~~~$| 18 | 12 | 10010|$~~~~~~$| 34 | 22 |100010|$~~~~~~$|...| # | 3 | 3 | 0011 |$~~~~~~$| 19 | 13 | 10011|$~~~~~~$| 35 | 23 |100011|$~~~~~~$|...| # | 4 | 4 | 0100 |$~~~~~~$| 20 | 14 | 10100|$~~~~~~$| 36 | 24 |100100|$~~~~~~$|...| # | 5 | 5 | 0101 |$~~~~~~$| 21 | 15 | 10101|$~~~~~~$| 37 | 25 |100101|$~~~~~~$|...| # | 6 | 6 | 0110 |$~~~~~~$| 22 | 16 | 10110|$~~~~~~$| 38 | 26 |100110|$~~~~~~$|...| # | 7 | 7 | 0111 |$~~~~~~$| 23 | 17 | 10111|$~~~~~~$| 39 | 27 |100111|$~~~~~~$|...| # | 8 | 8 | 1000 |$~~~~~~$| 24 | 18 | 11000|$~~~~~~$| 40 | 28 |101000|$~~~~~~$|...| # | 9 | 9 | 1001 |$~~~~~~$| 25 | 19 | 11001|$~~~~~~$| 41 | 29 |101001|$~~~~~~$|...| # | 10 | a | 1010 |$~~~~~~$| 26 | 1a | 11010|$~~~~~~$| 42 | 2a |101010|$~~~~~~$|...| # | 11 | b | 1011 |$~~~~~~$| 27 | 1b | 11011|$~~~~~~$| 43 | 2b |101011|$~~~~~~$|...| # | 12 | c | 1100 |$~~~~~~$| 28 | 1c | 11100|$~~~~~~$| 44 | 2c |101100|$~~~~~~$|...| # | 13 | d | 1101 |$~~~~~~$| 29 | 1d | 11101|$~~~~~~$| 45 | 2d |101101|$~~~~~~$|...| # | 14 | e | 1110 |$~~~~~~$| 30 | 1e | 11110|$~~~~~~$| 46 | 2e |101110|$~~~~~~$|...| # | 15 | f | 1111 |$~~~~~~$| 31 | 1f | 11111|$~~~~~~$| 47 | 2f |101111|$~~~~~~$|...| # + [markdown] slideshow={"slide_type": "skip"} # To show more examples of the above subscript convention, we pick three random entries from the table: # # $11_{10} = \text{b}_{16} = 1011_2$ # # $25_{10} = 19_{16} = 11001_2$ # # $46_{10} = 2\text{e}_{16} = 101110_2$ # # The built-in [hex()](https://docs.python.org/3/library/functions.html#hex) function creates a `str` object starting with `"0x"` representing an `int` object's hexadecimal representation. The length depends on how many groups of four bits are implied by the corresponding binary representation. # # For `0` and `1`, the hexadecimal representation is similar to the binary one. # + slideshow={"slide_type": "slide"} hex(0) # + slideshow={"slide_type": "fragment"} hex(1) # + [markdown] slideshow={"slide_type": "skip"} # Whereas `bin(3)` already requires two digits, one is enough for `hex(3)`. # + slideshow={"slide_type": "skip"} hex(3) # bin(3) => "0b11"; two digits needed # + [markdown] slideshow={"slide_type": "skip"} # For `10` and `15`, we see the letter digits for the first time. # + slideshow={"slide_type": "fragment"} hex(10) # + slideshow={"slide_type": "fragment"} hex(15) # + [markdown] slideshow={"slide_type": "skip"} # The binary representation of `123`, `0b_111_1011`, can be viewed as *two* groups of four bits, $0111$ and $1011$, that are encoded as $7$ and $\text{b}$ in hexadecimal (cf., table above). # + slideshow={"slide_type": "slide"} bin(123) # + slideshow={"slide_type": "fragment"} hex(123) # + [markdown] slideshow={"slide_type": "skip"} # To obtain a *new* `int` object with the value `123`, we call the [int()](https://docs.python.org/3/library/functions.html#int) built-in with a properly formatted `str` object and `base=16` as arguments. # + slideshow={"slide_type": "fragment"} int("0x7b", base=16) # + [markdown] slideshow={"slide_type": "skip"} # Alternatively, we could use a literal notation instead. # + slideshow={"slide_type": "fragment"} 0x_7b # + [markdown] slideshow={"slide_type": "skip"} # Hexadecimals between $00_{16}$ and $\text{ff}_{16}$ (i.e., $0_{10}$ and $255_{10}$) are commonly used to describe colors, for example, in web development but also graphics editors. See this [online tool](https://www.w3schools.com/colors/colors_hexadecimal.asp) for some more background. # + slideshow={"slide_type": "skip"} hex(0) # + slideshow={"slide_type": "skip"} hex(255) # + [markdown] slideshow={"slide_type": "skip"} # Just like binary representations, the hexadecimals extend to the left for larger numbers like `789`. # + slideshow={"slide_type": "skip"} hex(789) # + [markdown] slideshow={"slide_type": "skip"} # For completeness sake, we mention that there is also the [oct()](https://docs.python.org/3/library/functions.html#oct) built-in to obtain an integer's **octal representation**. The logic is the same as for the hexadecimal representation, and we use *eight* instead of *sixteen* digits. That is the equivalent of viewing the binary representations in groups of three bits. As of today, octal representations have become less important, and the data science practitioner may probably live without them quite well. # + [markdown] slideshow={"slide_type": "skip"} # ### Negative Values # + [markdown] slideshow={"slide_type": "skip"} # While there are conventions that model negative integers with $0$s and $1$s in memory (cf., [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement)), Python manages that for us, and we do not look into the theory here for brevity. We have learned all that a practitioner needs to know about how integers are modeled in a computer. The "*Further Resources*" section at the end of this chapter provides a video tutorial on how the [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement) idea works. # # The binary and hexadecimal representations of negative integers are identical to their positive counterparts except that they start with a minus sign `-`. However, as the video tutorial at the end of the chapter reveals, that is *not* how the bits are organized in memory. # + slideshow={"slide_type": "skip"} bin(-3) # + slideshow={"slide_type": "skip"} hex(-3) # + slideshow={"slide_type": "skip"} bin(-255) # + slideshow={"slide_type": "skip"} hex(-255) # + [markdown] slideshow={"slide_type": "slide"} # ### The `bool` Type # + [markdown] slideshow={"slide_type": "skip"} # Whereas the boolean literals `True` and `False` are commonly *not* regarded as numeric types, they behave like `1` and `0` in an arithmetic context. # + slideshow={"slide_type": "slide"} True + False # + slideshow={"slide_type": "fragment"} 41 + True # + slideshow={"slide_type": "fragment"} 42.87 * False # + [markdown] slideshow={"slide_type": "skip"} # We may explicitly cast `bool` objects as integers ourselves with the [int()](https://docs.python.org/3/library/functions.html#int) built-in. # + slideshow={"slide_type": "slide"} int(True) # + slideshow={"slide_type": "fragment"} int(False) # + [markdown] slideshow={"slide_type": "skip"} # Of course, their binary representations only need *one* bit of information. # + slideshow={"slide_type": "slide"} bin(True) # + slideshow={"slide_type": "fragment"} bin(False) # + [markdown] slideshow={"slide_type": "skip"} # Their hexadecimal representations occupy *four* bits in memory while only *one* bit is needed. This is because "1" and "0" are just two of the sixteen possible digits. # + slideshow={"slide_type": "skip"} hex(True) # + slideshow={"slide_type": "skip"} hex(False) # + [markdown] slideshow={"slide_type": "skip"} # As a reminder, the `None` object is a type on its own, namely the `NoneType`, and different from `False`. It *cannot* be cast as an integer as the `TypeError` indicates. # + slideshow={"slide_type": "slide"} int(None) # + [markdown] slideshow={"slide_type": "slide"} # ### Bitwise Operators # + [markdown] slideshow={"slide_type": "skip"} # Now that we know how integers are represented with $0$s and $1$s, we look at ways of working with the individual bits, in particular with the so-called **[bitwise operators](https://wiki.python.org/moin/BitwiseOperators)**: As the name suggests, the operators perform some operation on a bit by bit basis. They only work with and always return `int` objects. # # We keep this overview rather short as such "low-level" operations are not needed by the data science practitioner regularly. Yet, it is worthwhile to have heard about them as they form the basis of all of arithmetic in computers. # # The first operator is the **bitwise AND** operator `&`: It looks at the bits of its two operands, `11` and `13` in the example, in a pairwise fashion and if *both* operands have a $1$ in the *same* position, the resulting integer will have a $1$ in this position as well. Otherwise, the resulting integer will have a $0$ in this position. The binary representations of `11` and `13` both have $1$s in their respective first and fourth bits, which is why `bin(11 & 13)` evaluates to `Ob_1001` or `9`. # + slideshow={"slide_type": "slide"} 11 & 13 # + slideshow={"slide_type": "fragment"} bin(11) + " & " + bin(13) # to show the operands' bits # + slideshow={"slide_type": "fragment"} bin(11 & 13) # + [markdown] slideshow={"slide_type": "skip"} # `0b_1001` is the binary representation of `9`. # + slideshow={"slide_type": "fragment"} 0b_1001 # + [markdown] slideshow={"slide_type": "skip"} # The **bitwise OR** operator `|` evaluates to an `int` object whose bits are set to $1$ if the corresponding bits of either *one* or *both* operands are $1$. So in the example `9 | 13` only the second bit is $0$ for both operands, which is why the expression evaluates to `0b_1101` or `13`. # + slideshow={"slide_type": "slide"} 9 | 13 # + slideshow={"slide_type": "fragment"} bin(9) + " | " + bin(13) # to show the operands' bits # + slideshow={"slide_type": "fragment"} bin(9 | 13) # + [markdown] slideshow={"slide_type": "skip"} # `0b_1101` evaluates to an `int` object with the value `13`. # + slideshow={"slide_type": "fragment"} 0b_1101 # + [markdown] slideshow={"slide_type": "skip"} # The **bitwise XOR** operator `^` is a special case of the `|` operator in that it evaluates to an `int` object whose bits are set to $1$ if the corresponding bit of *exactly one* of the two operands is $1$. Colloquially, the "X" stands for "exclusive." The `^` operator must *not* be confused with the exponentiation operator `**`! In the example, `9 ^ 13`, only the third bit differs between the two operands, which is why it evaluates to `0b_100` omitting the leading $0$. # + slideshow={"slide_type": "slide"} 9 ^ 13 # + slideshow={"slide_type": "fragment"} bin(9) + " ^ " + bin(13) # to show the operands' bits # + slideshow={"slide_type": "fragment"} bin(9 ^ 13) # + [markdown] slideshow={"slide_type": "skip"} # `0b_100` evaluates to an `int` object with the value `4`. # + slideshow={"slide_type": "fragment"} 0b_100 # + [markdown] slideshow={"slide_type": "skip"} # The **bitwise NOT** operator `~`, sometimes also called **inversion** operator, is said to "flip" the $0$s into $1$s and the $1$s into $0$s. However, it is based on the aforementioned [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement) convention and `~x = -(x + 1)` by definition (cf., the [reference](https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations)). The full logic behind this, while actually quite simple, is considered out of scope in this book. # # We can at least verify the definition by comparing the binary representations of `7` and `-8`: They are indeed the same. # + slideshow={"slide_type": "slide"} ~7 # + slideshow={"slide_type": "fragment"} ~7 == -(7 + 1) # = Two's Complement # + slideshow={"slide_type": "fragment"} bin(~7) # + slideshow={"slide_type": "fragment"} bin(-(7 + 1)) # + [markdown] slideshow={"slide_type": "skip"} # `~x = -(x + 1)` can be reformulated as `~x + x = -1`, which is slightly easier to check. # + slideshow={"slide_type": "skip"} ~7 + 7 # + [markdown] slideshow={"slide_type": "skip"} # Lastly, the **bitwise left and right shift** operators, `<<` and `>>`, shift all the bits either to the left or to the right. This corresponds to multiplying or dividing an integer by powers of `2`. # # When shifting left, $0$s are filled in. # + slideshow={"slide_type": "slide"} 7 << 2 # + slideshow={"slide_type": "fragment"} bin(7) # + slideshow={"slide_type": "fragment"} bin(7 << 2) # + slideshow={"slide_type": "fragment"} 0b_1_1100 # + [markdown] slideshow={"slide_type": "skip"} # When shifting right, some bits are always lost. # + slideshow={"slide_type": "slide"} 7 >> 1 # + slideshow={"slide_type": "fragment"} bin(7) # + slideshow={"slide_type": "fragment"} bin(7 >> 1) # + slideshow={"slide_type": "fragment"} 0b_11 # + [markdown] slideshow={"slide_type": "slide"} # ## The `float` Type # + [markdown] slideshow={"slide_type": "skip"} # As we have seen above, some assumptions need to be made as to how the $0$s and $1$s in a computer's memory are to be translated into numbers. This process becomes a lot more involved when we go beyond integers and model [real numbers](https://en.wikipedia.org/wiki/Real_number) (i.e., the set $\mathbb{R}$) with possibly infinitely many digits to the right of the period like $1.23$. # # The **[Institute of Electrical and Electronics Engineers](https://en.wikipedia.org/wiki/Institute_of_Electrical_and_Electronics_Engineers)** (IEEE, pronounced "eye-triple-E") is one of the important professional associations when it comes to standardizing all kinds of aspects regarding the implementation of soft- and hardware. # # The **[IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)** standard defines the so-called **floating-point arithmetic** that is commonly used today by all major programming languages. The standard not only defines how the $0$s and $1$s are organized in memory but also, for example, how values are to be rounded, what happens in exceptional cases like divisions by zero, or what is a zero value in the first place. # # In Python, the simplest way to create a `float` object is to use a literal notation with a dot `.` in it. # + slideshow={"slide_type": "slide"} b = 42.0 # + slideshow={"slide_type": "fragment"} id(b) # + slideshow={"slide_type": "fragment"} type(b) # + slideshow={"slide_type": "fragment"} b # + [markdown] slideshow={"slide_type": "skip"} # As with integer literals above, we may use underscores `_` to make longer `float` objects easier to read. # + slideshow={"slide_type": "skip"} 0.123_456_789 # + [markdown] slideshow={"slide_type": "skip"} # In cases where the dot `.` is unnecessary from a mathematical point of view, we either need to end the number with it nevertheless or use the [float()](https://docs.python.org/3/library/functions.html#float) built-in to cast the number explicitly. [float()](https://docs.python.org/3/library/functions.html#float) can process any numeric object or a properly formatted `str` object. # + slideshow={"slide_type": "slide"} 42. # + slideshow={"slide_type": "fragment"} float(42) # + slideshow={"slide_type": "fragment"} float("42") # + [markdown] slideshow={"slide_type": "skip"} # Leading and trailing whitespace is ignored ... # + slideshow={"slide_type": "skip"} float(" 42.87 ") # + [markdown] slideshow={"slide_type": "skip"} # ... but not whitespace in between. # + slideshow={"slide_type": "skip"} float("42. 87") # + [markdown] slideshow={"slide_type": "skip"} # `float` objects are implicitly created as the result of dividing an `int` object by another with the division operator `/`. # + slideshow={"slide_type": "slide"} 1 / 3 # + [markdown] slideshow={"slide_type": "skip"} # In general, if we combine `float` and `int` objects in arithmetic operations, we always end up with a `float` type: Python uses the "broader" representation. # + slideshow={"slide_type": "fragment"} 40.0 + 2 # + slideshow={"slide_type": "fragment"} 21 * 2.0 # + [markdown] slideshow={"slide_type": "slide"} # ### Scientific Notation # + [markdown] slideshow={"slide_type": "skip"} # `float` objects may also be created with the **scientific literal notation**: We use the symbol `e` to indicate powers of $10$, so $1.23 * 10^0$ translates into `1.23e0`. # + slideshow={"slide_type": "slide"} 1.23e0 # + [markdown] slideshow={"slide_type": "skip"} # Syntactically, `e` needs a `float` or `int` object in its literal notation on its left and an `int` object on its right, both without a space. Otherwise, we get a `SyntaxError`. # + slideshow={"slide_type": "skip"} 1.23 e0 # + slideshow={"slide_type": "skip"} 1.23e 0 # + slideshow={"slide_type": "skip"} 1.23e0.0 # + [markdown] slideshow={"slide_type": "skip"} # If we leave out the number to the left, Python raises a `NameError` as it unsuccessfully tries to look up a variable named `e0`. # + slideshow={"slide_type": "skip"} e0 # + [markdown] slideshow={"slide_type": "skip"} # So, to write $10^0$ in Python, we need to think of it as $1*10^0$ and write `1e0`. # + slideshow={"slide_type": "fragment"} 1e0 # + [markdown] slideshow={"slide_type": "skip"} # To express thousands of something (i.e., $10^3$), we write `1e3`. # + slideshow={"slide_type": "fragment"} 1e3 # = thousands # + [markdown] slideshow={"slide_type": "skip"} # Similarly, to express, for example, milliseconds (i.e., $10^{-3} s$), we write `1e-3`. # + slideshow={"slide_type": "fragment"} 1e-3 # = milli # + [markdown] slideshow={"slide_type": "slide"} # ### Special Values # + [markdown] slideshow={"slide_type": "skip"} # There are also three special values representing "**not a number,**" called `nan`, and positive or negative **infinity**, called `inf` or `-inf`, that are created by passing in the corresponding abbreviation as a `str` object to the [float()](https://docs.python.org/3/library/functions.html#float) built-in. These values could be used, for example, as the result of a mathematically undefined operation like division by zero or to model the value of a mathematical function as it goes to infinity. # + slideshow={"slide_type": "slide"} float("nan") # also float("NaN") # + slideshow={"slide_type": "skip"} float("+inf") # also float("+infinity") or float("infinity") # + slideshow={"slide_type": "fragment"} float("inf") # same as float("+inf") # + slideshow={"slide_type": "fragment"} float("-inf") # + [markdown] slideshow={"slide_type": "skip"} # `nan` objects *never* compare equal to *anything*, not even to themselves. This happens in accordance with the [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) standard. # + slideshow={"slide_type": "slide"} float("nan") == float("nan") # + [markdown] slideshow={"slide_type": "skip"} # Another caveat is that any arithmetic involving a `nan` object results in `nan`. In other words, the addition below **fails silently** as no error is raised. As this also happens in accordance with the [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) standard, we *need* to be aware of that and check any data we work with for any `nan` occurrences *before* doing any calculations. # + slideshow={"slide_type": "fragment"} 42 + float("nan") # + [markdown] slideshow={"slide_type": "skip"} # On the contrary, as two values go to infinity, there is no such concept as difference and *everything* compares equal. # + slideshow={"slide_type": "slide"} float("inf") == float("inf") # + [markdown] slideshow={"slide_type": "skip"} # Adding `42` to `inf` makes no difference. # + slideshow={"slide_type": "skip"} float("inf") + 42 # + slideshow={"slide_type": "fragment"} float("inf") + 42 == float("inf") # + [markdown] slideshow={"slide_type": "skip"} # We observe the same for multiplication ... # + slideshow={"slide_type": "skip"} 42 * float("inf") # + slideshow={"slide_type": "skip"} 42 * float("inf") == float("inf") # + [markdown] slideshow={"slide_type": "skip"} # ... and even exponentiation! # + slideshow={"slide_type": "skip"} float("inf") ** 42 # + slideshow={"slide_type": "skip"} float("inf") ** 42 == float("inf") # + [markdown] slideshow={"slide_type": "skip"} # Although absolute differences become unmeaningful as we approach infinity, signs are still respected. # + slideshow={"slide_type": "skip"} -42 * float("-inf") # + slideshow={"slide_type": "fragment"} -42 * float("-inf") == float("inf") # + [markdown] slideshow={"slide_type": "skip"} # As a caveat, adding infinities of different signs is an *undefined operation* in math and results in a `nan` object. So, if we (accidentally or unknowingly) do this on a real dataset, we do *not* see any error messages, and our program may continue to run with non-meaningful results! This is another example of a piece of code **failing silently**. # + slideshow={"slide_type": "slide"} float("inf") + float("-inf") # + slideshow={"slide_type": "fragment"} float("inf") - float("inf") # + [markdown] slideshow={"slide_type": "slide"} # ### Imprecision # + [markdown] slideshow={"slide_type": "skip"} # `float` objects are *inherently* imprecise, and there is *nothing* we can do about it! In particular, arithmetic operations with two `float` objects may result in "weird" rounding "errors" that are strictly deterministic and occur in accordance with the [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) standard. # # For example, let's add `1` to `1e15` and `1e16`, respectively. In the latter case, the `1` somehow gets "lost." # + slideshow={"slide_type": "slide"} 1e15 + 1 # + slideshow={"slide_type": "fragment"} 1e16 + 1 # + [markdown] slideshow={"slide_type": "skip"} # Interactions between sufficiently large and small `float` objects are not the only source of imprecision. # + slideshow={"slide_type": "slide"} from math import sqrt # + slideshow={"slide_type": "fragment"} sqrt(2) ** 2 # + slideshow={"slide_type": "fragment"} 0.1 + 0.2 # + [markdown] slideshow={"slide_type": "skip"} # This may become a problem if we rely on equality checks in our programs. # + slideshow={"slide_type": "fragment"} sqrt(2) ** 2 == 2 # + slideshow={"slide_type": "fragment"} 0.1 + 0.2 == 0.3 # + [markdown] slideshow={"slide_type": "skip"} # A popular workaround is to benchmark the difference between the two numbers to be checked for equality against a pre-defined `threshold` *sufficiently* close to `0`, for example, `1e-15`. # + slideshow={"slide_type": "slide"} threshold = 1e-15 # + slideshow={"slide_type": "fragment"} (sqrt(2) ** 2) - 2 < threshold # + slideshow={"slide_type": "fragment"} (0.1 + 0.2) - 0.3 < threshold # + [markdown] slideshow={"slide_type": "skip"} # The built-in [format()](https://docs.python.org/3/library/functions.html#format) function allows us to show the **significant digits** of a `float` number as they exist in memory to arbitrary precision. To exemplify it, let's view a couple of `float` objects with `50` digits. This analysis reveals that almost no `float` number is precise! After 14 or 15 digits "weird" things happen. As we see further below, the "random" digits ending the `float` numbers do *not* "physically" exist in memory! Rather, they are "calculated" by the [format()](https://docs.python.org/3/library/functions.html#format) function that is forced to show `50` digits. # # The [format()](https://docs.python.org/3/library/functions.html#format) function is different from the [format()](https://docs.python.org/3/library/stdtypes.html#str.format) method on `str` objects introduced in the next chapter (cf., [Chapter 6](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/06_text_00_lecture.ipynb#format%28%29-Method)): Yet, both work with the so-called [format specification mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language): `".50f"` is the instruction to show `50` digits of a `float` number. # + slideshow={"slide_type": "slide"} format(0.1, ".50f") # + slideshow={"slide_type": "fragment"} format(0.2, ".50f") # + slideshow={"slide_type": "fragment"} format(0.3, ".50f") # + slideshow={"slide_type": "slide"} format(1 / 3, ".50f") # + [markdown] slideshow={"slide_type": "skip"} # The [format()](https://docs.python.org/3/library/functions.html#format) function does *not* round a `float` object in the mathematical sense! It just allows us to show an arbitrary number of the digits as stored in memory, and it also does *not* change these. # # On the contrary, the built-in [round()](https://docs.python.org/3/library/functions.html#round) function creates a *new* numeric object that is a rounded version of the one passed in as the argument. It adheres to the common rules of math. # # For example, let's round `1 / 3` to five decimals. The obtained value for `roughly_a_third` is also *imprecise* but different from the "exact" representation of `1 / 3` above. # + slideshow={"slide_type": "fragment"} roughly_a_third = round(1 / 3, 5) # + slideshow={"slide_type": "fragment"} roughly_a_third # + slideshow={"slide_type": "fragment"} format(roughly_a_third, ".50f") # + [markdown] slideshow={"slide_type": "skip"} # Surprisingly, `0.125` and `0.25` appear to be *precise*, and equality comparison works without the `threshold` workaround: Both are powers of $2$ in disguise. # + slideshow={"slide_type": "slide"} format(0.125, ".50f") # + slideshow={"slide_type": "fragment"} format(0.25, ".50f") # + slideshow={"slide_type": "fragment"} 0.125 + 0.125 == 0.25 # + [markdown] slideshow={"slide_type": "slide"} # ### Binary Representations # + [markdown] slideshow={"slide_type": "skip"} # To understand these subtleties, we need to look at the **[binary representation of floats](https://en.wikipedia.org/wiki/Double-precision_floating-point_format)** and review the basics of the **[IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)** standard. On modern machines, floats are modeled in so-called double precision with $64$ bits that are grouped as in the figure below. The first bit determines the sign ($0$ for plus, $1$ for minus), the next $11$ bits represent an $exponent$ term, and the last $52$ bits resemble the actual significant digits, the so-called $fraction$ part. The three groups are put together like so: # + [markdown] slideshow={"slide_type": "slide"} # $$float = (-1)^{sign} * 1.fraction * 2^{exponent-1023}$$ # + [markdown] slideshow={"slide_type": "skip"} # A $1.$ is implicitly prepended as the first digit, and both, $fraction$ and $exponent$, are stored in base $2$ representation (i.e., they both are interpreted like integers above). As $exponent$ is consequently non-negative, between $0_{10}$ and $2047_{10}$ to be precise, the $-1023$, called the exponent bias, centers the entire $2^{exponent-1023}$ term around $1$ and allows the period within the $1.fraction$ part be shifted into either direction by the same amount. Floating-point numbers received their name as the period, formally called the **[radix point](https://en.wikipedia.org/wiki/Radix_point)**, "floats" along the significant digits. As an aside, an $exponent$ of all $0$s or all $1$s is used to model the special values `nan` or `inf`. # # As the standard defines the exponent part to come as a power of $2$, we now see why `0.125` is a *precise* float: It can be represented as a power of $2$, i.e., $0.125 = (-1)^0 * 1.0 * 2^{1020-1023} = 2^{-3} = \frac{1}{8}$. In other words, the floating-point representation of $0.125_{10}$ is $0_2$, $1111111100_2 = 1020_{10}$, and $0_2$ for the three groups, respectively. # + [markdown] slideshow={"slide_type": "-"} # <img src="static/floating_point.png" width="85%" align="center"> # + [markdown] slideshow={"slide_type": "skip"} # The crucial fact for the data science practitioner to understand is that mapping the *infinite* set of the real numbers $\mathbb{R}$ to a *finite* set of bits leads to the imprecisions shown above! # # So, floats are usually good approximations of real numbers only with their first $14$ or $15$ digits. If more precision is required, we need to revert to other data types such as a `Decimal` or a `Fraction`, as shown in the next two sections. # # This [blog post](http://fabiensanglard.net/floating_point_visually_explained/) gives another neat and *visual* way as to how to think of floats. It also explains why floats become worse approximations of the reals as their absolute values increase. # # The Python [documentation](https://docs.python.org/3/tutorial/floatingpoint.html) provides another good discussion of floats and the goodness of their approximations. # # If we are interested in the exact bits behind a `float` object, we use the [hex()](https://docs.python.org/3/library/stdtypes.html#float.hex) method that returns a `str` object beginning with `"0x1."` followed by the $fraction$ in hexadecimal notation and the $exponent$ as an integer after subtraction of $1023$ and separated by a `"p"`. # + slideshow={"slide_type": "slide"} one_eighth = 1 / 8 # + slideshow={"slide_type": "fragment"} one_eighth.hex() # + [markdown] slideshow={"slide_type": "skip"} # Also, the [as_integer_ratio()](https://docs.python.org/3/library/stdtypes.html#float.as_integer_ratio) method returns the two smallest integers whose ratio best approximates a `float` object. # + slideshow={"slide_type": "fragment"} one_eighth.as_integer_ratio() # + slideshow={"slide_type": "slide"} roughly_a_third.hex() # + slideshow={"slide_type": "fragment"} roughly_a_third.as_integer_ratio() # + [markdown] slideshow={"slide_type": "skip"} # `0.0` is also a power of $2$ and thus a *precise* `float` number. # + slideshow={"slide_type": "skip"} zero = 0.0 # + slideshow={"slide_type": "skip"} zero.hex() # + slideshow={"slide_type": "skip"} zero.as_integer_ratio() # + [markdown] slideshow={"slide_type": "skip"} # As seen in [Chapter 1](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/01_elements_00_lecture.ipynb#%28Data%29-Type-%2F-%22Behavior%22), the [is_integer()](https://docs.python.org/3/library/stdtypes.html#float.is_integer) method tells us if a `float` can be casted as an `int` object without any loss in precision. # + slideshow={"slide_type": "skip"} roughly_a_third.is_integer() # + slideshow={"slide_type": "skip"} one = roughly_a_third / roughly_a_third one.is_integer() # + [markdown] slideshow={"slide_type": "skip"} # As the exact implementation of floats may vary and be dependent on a particular Python installation, we look up the [float_info](https://docs.python.org/3/library/sys.html#sys.float_info) attribute in the [sys](https://docs.python.org/3/library/sys.html) module in the [standard library](https://docs.python.org/3/library/index.html) to check the details. Usually, this is not necessary. # + slideshow={"slide_type": "skip"} import sys # + slideshow={"slide_type": "skip"} sys.float_info # + [markdown] slideshow={"slide_type": "slide"} # ## The `Decimal` Type # + [markdown] slideshow={"slide_type": "skip"} # The [decimal](https://docs.python.org/3/library/decimal.html) module in the [standard library](https://docs.python.org/3/library/index.html) provides a [Decimal](https://docs.python.org/3/library/decimal.html#decimal.Decimal) type that may be used to represent any real number to a user-defined level of precision: "User-defined" does *not* mean an infinite or exact precision! The `Decimal` type merely allows us to work with a number of bits *different* from the $64$ as specified for the `float` type and also to customize the rounding rules and some other settings. # # We import the `Decimal` type and also the [getcontext()](https://docs.python.org/3/library/decimal.html#decimal.getcontext) function from the [decimal](https://docs.python.org/3/library/decimal.html) module. # + slideshow={"slide_type": "slide"} from decimal import Decimal, getcontext # + [markdown] slideshow={"slide_type": "skip"} # [getcontext()](https://docs.python.org/3/library/decimal.html#decimal.getcontext) shows us how the [decimal](https://docs.python.org/3/library/decimal.html) module is set up. By default, the precision is set to `28` significant digits, which is roughly twice as many as with `float` objects. # + slideshow={"slide_type": "fragment"} getcontext() # + [markdown] slideshow={"slide_type": "skip"} # The two simplest ways to create a `Decimal` object is to either **instantiate** it with an `int` or a `str` object consisting of all the significant digits. In the latter case, the scientific notation is also possible. # + slideshow={"slide_type": "slide"} Decimal(42) # + slideshow={"slide_type": "fragment"} Decimal("0.1") # + slideshow={"slide_type": "fragment"} Decimal("1e-3") # + [markdown] slideshow={"slide_type": "skip"} # It is *not* a good idea to create a `Decimal` from a `float` object. If we did so, we would create a `Decimal` object that internally used extra bits to store the "random" digits that are not stored in the `float` object in the first place. # + slideshow={"slide_type": "fragment"} Decimal(0.1) # do not do this # + [markdown] slideshow={"slide_type": "skip"} # With the `Decimal` type, the imprecisions in the arithmetic and equality comparisons from above go away. # + slideshow={"slide_type": "slide"} Decimal("0.1") + Decimal("0.2") # + slideshow={"slide_type": "fragment"} Decimal("0.1") + Decimal("0.2") == Decimal("0.3") # + [markdown] slideshow={"slide_type": "skip"} # `Decimal` numbers *preserve* the **significant digits**, even in cases where this is not needed. # + slideshow={"slide_type": "fragment"} Decimal("0.10000") + Decimal("0.20000") # + slideshow={"slide_type": "skip"} Decimal("0.10000") + Decimal("0.20000") == Decimal("0.3") # + [markdown] slideshow={"slide_type": "skip"} # Arithmetic operations between `Decimal` and `int` objects work as the latter are inherently precise: The results are *new* `Decimal` objects. # + slideshow={"slide_type": "slide"} 21 + Decimal(21) # + slideshow={"slide_type": "fragment"} 10 * Decimal("4.2") # + slideshow={"slide_type": "slide"} Decimal(1) / 10 # + [markdown] slideshow={"slide_type": "skip"} # To verify the precision, we apply the built-in [format()](https://docs.python.org/3/library/functions.html#format) function to the previous code cell and compare it with the same division resulting in a `float` object. # + slideshow={"slide_type": "fragment"} format(Decimal(1) / 10, ".50f") # + slideshow={"slide_type": "fragment"} format(1 / 10, ".50f") # + [markdown] slideshow={"slide_type": "skip"} # However, mixing `Decimal` and `float` objects raises a `TypeError`: So, Python prevents us from potentially introducing imprecisions via innocent-looking arithmetic by **failing loudly**. # + slideshow={"slide_type": "slide"} 1.0 * Decimal(42) # + [markdown] slideshow={"slide_type": "skip"} # To preserve the precision for more advanced mathematical functions, `Decimal` objects come with many **methods bound** on them. For example, [ln()](https://docs.python.org/3/library/decimal.html#decimal.Decimal.ln) and [log10()](https://docs.python.org/3/library/decimal.html#decimal.Decimal.log10) take the logarithm while [sqrt()](https://docs.python.org/3/library/decimal.html#decimal.Decimal.sqrt) calculates the square root. The methods always return a *new* `Decimal` object. We must never use the functions in the [math](https://docs.python.org/3/library/math.html) module in the [standard library](https://docs.python.org/3/library/index.html) with `Decimal` objects as they do *not* preserve precision. # + slideshow={"slide_type": "skip"} Decimal(100).log10() # + slideshow={"slide_type": "slide"} Decimal(2).sqrt() # + [markdown] slideshow={"slide_type": "skip"} # The object returned by the [sqrt()](https://docs.python.org/3/library/decimal.html#decimal.Decimal.sqrt) method is still limited in precision: This must be so as, for example, $\sqrt{2}$ is an **[irrational number](https://en.wikipedia.org/wiki/Irrational_number)** that *cannot* be expressed with absolute precision using *any* number of bits, even in theory. # # We see this as raising $\sqrt{2}$ to the power of $2$ results in an imprecise value as before! # + slideshow={"slide_type": "fragment"} two = Decimal(2).sqrt() ** 2 two # + [markdown] slideshow={"slide_type": "skip"} # However, the [quantize()](https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize) method allows us to [quantize](https://www.dictionary.com/browse/quantize) (i.e., "round") a `Decimal` number at any precision that is *smaller* than the set precision. It takes the number of decimals to the right of the period of the `Decimal` argument we pass in and rounds accordingly. # # For example, as the overall imprecise value of `two` still has an internal precision of `28` digits, we can correctly round it to *four* decimals (i.e., `Decimal("0.0000")` has four decimals). # + slideshow={"slide_type": "slide"} two.quantize(Decimal("0.0000")) # + [markdown] slideshow={"slide_type": "skip"} # We can never round a `Decimal` number and obtain a greater precision than before: The `InvalidOperation` exception tells us that *loudly*. # + slideshow={"slide_type": "fragment"} two.quantize(Decimal("1e-28")) # + [markdown] slideshow={"slide_type": "skip"} # Consequently, with this little workaround $\sqrt{2}^2 = 2$ works, even in Python. # + slideshow={"slide_type": "skip"} two.quantize(Decimal("0.0000")) == 2 # + [markdown] slideshow={"slide_type": "skip"} # The downside is that the entire expression is not as pretty as `sqrt(2) ** 2 == 2` from above. # + slideshow={"slide_type": "skip"} (Decimal(2).sqrt() ** 2).quantize(Decimal("0.0000")) == 2 # + [markdown] slideshow={"slide_type": "skip"} # `nan` and positive and negative `inf` exist as well, and the same remarks from above apply. # + slideshow={"slide_type": "skip"} Decimal("nan") # + [markdown] slideshow={"slide_type": "skip"} # `Decimal("nan")`s never compare equal to anything, not even to themselves. # + slideshow={"slide_type": "skip"} Decimal("nan") == Decimal("nan") # + [markdown] slideshow={"slide_type": "skip"} # Infinity is larger than any concrete number. # + slideshow={"slide_type": "skip"} Decimal("inf") # + slideshow={"slide_type": "skip"} Decimal("-inf") # + slideshow={"slide_type": "skip"} Decimal("inf") + 42 # + slideshow={"slide_type": "skip"} Decimal("inf") + 42 == Decimal("inf") # + [markdown] slideshow={"slide_type": "skip"} # As with `float` objects, we cannot add infinities of different signs: Now, get a module-specific `InvalidOperation` exception instead of a `nan` value. Here, **failing loudly** is a good thing as it prevents us from working with invalid results. # + slideshow={"slide_type": "skip"} Decimal("inf") + Decimal("-inf") # + slideshow={"slide_type": "skip"} Decimal("inf") - Decimal("inf") # + [markdown] slideshow={"slide_type": "skip"} # For more information on the `Decimal` type, see the tutorial at [PYMOTW](https://pymotw.com/3/decimal/index.html) or the official [documentation](https://docs.python.org/3/library/decimal.html). # + [markdown] slideshow={"slide_type": "slide"} # ## The `Fraction` Type # + [markdown] slideshow={"slide_type": "skip"} # If the numbers in an application can be expressed as [rational numbers](https://en.wikipedia.org/wiki/Rational_number) (i.e., the set $\mathbb{Q}$), we may model them as a [Fraction](https://docs.python.org/3/library/fractions.html#fractions.Fraction) type from the [fractions](https://docs.python.org/3/library/fractions.html) module in the [standard library](https://docs.python.org/3/library/index.html). As any fraction can always be formulated as the division of one integer by another, `Fraction` objects are inherently precise, just as `int` objects on their own. Further, we maintain the precision as long as we do not use them in a mathematical operation that could result in an irrational number (e.g., taking the square root). # # We import the `Fraction` type from the [fractions](https://docs.python.org/3/library/fractions.html) module. # + slideshow={"slide_type": "slide"} from fractions import Fraction # + [markdown] slideshow={"slide_type": "skip"} # Among others, there are two simple ways to create a `Fraction` object: We either instantiate one with two `int` objects representing the numerator and denominator or with a `str` object. In the latter case, we have two options again and use either the format "numerator/denominator" (i.e., *without* any spaces) or the same format as for `float` and `Decimal` objects above. # + slideshow={"slide_type": "fragment"} Fraction(1, 3) # 1/3 with "full" precision # + slideshow={"slide_type": "fragment"} Fraction("1/3") # 1/3 with "full" precision # + slideshow={"slide_type": "fragment"} Fraction("0.3333333333") # 1/3 with a precision of 10 significant digits # + slideshow={"slide_type": "skip"} Fraction("3333333333e-10") # scientific notation is also allowed # + [markdown] slideshow={"slide_type": "skip"} # Only the lowest common denominator version is maintained after creation: For example, $\frac{3}{2}$ and $\frac{6}{4}$ are the same, and both become `Fraction(3, 2)`. # + slideshow={"slide_type": "slide"} Fraction(3, 2) # + slideshow={"slide_type": "fragment"} Fraction(6, 4) # + [markdown] slideshow={"slide_type": "skip"} # We could also cast a `Decimal` object as a `Fraction` object: This only makes sense as `Decimal` objects come with a pre-defined precision. # + slideshow={"slide_type": "slide"} Fraction(Decimal("0.1")) # + [markdown] slideshow={"slide_type": "skip"} # `float` objects may *syntactically* be cast as `Fraction` objects as well. However, then we create a `Fraction` object that precisely remembers the `float` object's imprecision: A *bad* idea! # + slideshow={"slide_type": "fragment"} Fraction(0.1) # + [markdown] slideshow={"slide_type": "skip"} # `Fraction` objects follow the arithmetic rules from middle school and may be mixed with `int` objects *without* any loss of precision. The result is always a *new* `Fraction` object. # + slideshow={"slide_type": "slide"} Fraction(3, 2) + Fraction(1, 4) # + slideshow={"slide_type": "fragment"} Fraction(5, 2) - 2 # + slideshow={"slide_type": "fragment"} 3 * Fraction(1, 3) # + slideshow={"slide_type": "fragment"} Fraction(3, 2) * Fraction(2, 3) # + [markdown] slideshow={"slide_type": "skip"} # `Fraction` and `float` objects may also be mixed *syntactically*. However, then the results may exhibit imprecision again, even if we do not see them at first sight! This is another example of code **failing silently**. # + slideshow={"slide_type": "slide"} 10.0 * Fraction(1, 100) # do not do this # + slideshow={"slide_type": "fragment"} format(10.0 * Fraction(1, 100), ".50f") # + [markdown] slideshow={"slide_type": "skip"} # For more examples and discussions, see the tutorial at [PYMOTW](https://pymotw.com/3/fractions/index.html) or the official [documentation](https://docs.python.org/3/library/fractions.html). # + [markdown] slideshow={"slide_type": "slide"} # ## The `complex` Type # + [markdown] slideshow={"slide_type": "slide"} # **What is the solution to $x^2 = -1$ ?** # + [markdown] slideshow={"slide_type": "skip"} # Some mathematical equations cannot be solved if the solution has to be in the set of the real numbers $\mathbb{R}$. For example, $x^2 = -1$ can be rearranged into $x = \sqrt{-1}$, but the square root is not defined for negative numbers. To mitigate this, mathematicians introduced the concept of an [imaginary number](https://en.wikipedia.org/wiki/Imaginary_number) $\textbf{i}$ that is *defined* as $\textbf{i} = \sqrt{-1}$ or often as the solution to the equation $\textbf{i}^2 = -1$. So, the solution to $x = \sqrt{-1}$ then becomes $x = \textbf{i}$. # # If we generalize the example equation into $(mx-n)^2 = -1 \implies x = \frac{1}{m}(\sqrt{-1} + n)$ where $m$ and $n$ are constants chosen from the reals $\mathbb{R}$, then the solution to the equation comes in the form $x = a + b\textbf{i}$, the sum of a real number and an imaginary number, with $a=\frac{n}{m}$ and $b = \frac{1}{m}$. # # Such "compound" numbers are called **[complex numbers](https://en.wikipedia.org/wiki/Complex_number)**, and the set of all such numbers is commonly denoted by $\mathbb{C}$. The reals $\mathbb{R}$ are a strict subset of $\mathbb{C}$ with $b=0$. Further, $a$ is referred to as the **real part** and $b$ as the **imaginary part** of the complex number. # # Complex numbers are often visualized in a plane like below, where the real part is depicted on the x-axis and the imaginary part on the y-axis. # + [markdown] slideshow={"slide_type": "-"} # <img src="static/complex_numbers.png" width="25%" align="center"> # + [markdown] slideshow={"slide_type": "skip"} # `complex` numbers are part of core Python. The simplest way to create one is to write an arithmetic expression with the literal `j` notation for $\textbf{i}$. The `j` is commonly used in many engineering disciplines instead of the symbol $\textbf{i}$ from math as $I$ in engineering more often than not means [electric current](https://en.wikipedia.org/wiki/Electric_current). # # For example, the answer to $x^2 = -1$ can be written in Python as `1j` like below. This creates a `complex` object with value `1j`. The same syntactic rules apply as with the above `e` notation: No spaces are allowed between the number and the `j`. The number may be any `int` or `float` literal; however, it is stored as a `float` internally. So, `complex` numbers suffer from the same imprecision as `float` numbers. # + slideshow={"slide_type": "slide"} x = 1j # + slideshow={"slide_type": "fragment"} id(x) # + slideshow={"slide_type": "fragment"} type(x) # + slideshow={"slide_type": "fragment"} x # + [markdown] slideshow={"slide_type": "skip"} # To verify that it solves the equation, let's raise it to the power of $2$. # + slideshow={"slide_type": "slide"} x ** 2 == -1 # + [markdown] slideshow={"slide_type": "skip"} # Often, we write an expression of the form $a + b\textbf{i}$. # + slideshow={"slide_type": "slide"} 2 + 0.5j # + [markdown] slideshow={"slide_type": "skip"} # Alternatively, we may use the [complex()](https://docs.python.org/3/library/functions.html#complex) built-in: This takes two parameters where the second is optional and defaults to `0`. We may either call it with one or two arguments of any numeric type or a `str` object in the format of the previous code cell without any spaces. # + slideshow={"slide_type": "fragment"} complex(2, 0.5) # + [markdown] slideshow={"slide_type": "skip"} # By omitting the second argument, we set the imaginary part to $0$. # + slideshow={"slide_type": "skip"} complex(2) # + [markdown] slideshow={"slide_type": "skip"} # The arguments to [complex()](https://docs.python.org/3/library/functions.html#complex) may be any numeric type. # + slideshow={"slide_type": "skip"} complex(Decimal("2.0"), Fraction(1, 2)) # + slideshow={"slide_type": "skip"} complex("2+0.5j") # + [markdown] slideshow={"slide_type": "skip"} # Arithmetic expressions work with `complex` numbers. They may be mixed with the other numeric types, and the result is always a `complex` number. # + slideshow={"slide_type": "slide"} c1 = 1 + 2j c2 = 3 + 4j # + slideshow={"slide_type": "fragment"} c1 + c2 # + slideshow={"slide_type": "fragment"} c1 - c2 # + slideshow={"slide_type": "skip"} c1 + 1 # + slideshow={"slide_type": "skip"} 3.5 - c2 # + slideshow={"slide_type": "skip"} 5 * c1 # + slideshow={"slide_type": "skip"} c2 / 6 # + slideshow={"slide_type": "fragment"} c1 * c2 # + slideshow={"slide_type": "fragment"} c1 / c2 # + [markdown] slideshow={"slide_type": "skip"} # The absolute value of a `complex` number $x$ is defined with the Pythagorean Theorem where $\lVert x \rVert = \sqrt{a^2 + b^2}$ and $a$ and $b$ are the real and imaginary parts. The [abs()](https://docs.python.org/3/library/functions.html#abs) built-in function implements that in Python. # + slideshow={"slide_type": "slide"} abs(3 + 4j) # + [markdown] slideshow={"slide_type": "skip"} # A `complex` number comes with two **attributes** `real` and `imag` that return the two parts as `float` objects on their own. # + slideshow={"slide_type": "fragment"} c1.real # + slideshow={"slide_type": "fragment"} c1.imag # + [markdown] slideshow={"slide_type": "skip"} # Also, a `conjugate()` method is bound to every `complex` object. The [complex conjugate](https://en.wikipedia.org/wiki/Complex_conjugate) is defined to be the complex number with identical real part but an imaginary part reversed in sign. # + slideshow={"slide_type": "fragment"} c1.conjugate() # + [markdown] slideshow={"slide_type": "skip"} # The [cmath](https://docs.python.org/3/library/cmath.html) module in the [standard library](https://docs.python.org/3/library/index.html) implements many of the functions from the [math](https://docs.python.org/3/library/math.html) module such that they work with complex numbers. # + [markdown] slideshow={"slide_type": "slide"} # ## The Numerical Tower # + [markdown] slideshow={"slide_type": "skip"} # Analogous to the discussion of *containers* and *iterables* in [Chapter 4](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/04_iteration_00_lecture.ipynb#Containers-vs.-Iterables), we contrast the *concrete* numeric data types in this chapter with the *abstract* ideas behind [numbers in mathematics](https://en.wikipedia.org/wiki/Number). # # The figure below summarizes five *major* sets of [numbers in mathematics](https://en.wikipedia.org/wiki/Number) as we know them from high school: # # - $\mathbb{N}$: [Natural numbers](https://en.wikipedia.org/wiki/Natural_number) are all non-negative count numbers, e.g., $0, 1, 2, ...$ # - $\mathbb{Z}$: [Integers](https://en.wikipedia.org/wiki/Integer) are all numbers *without* a fractional component, e.g., $-1, 0, 1, ...$ # - $\mathbb{Q}$: [Rational numbers](https://en.wikipedia.org/wiki/Rational_number) are all numbers that can be expressed as a quotient of two integers, e.g., $-\frac{1}{2}, 0, \frac{1}{2}, ...$ # - $\mathbb{R}$: [Real numbers](https://en.wikipedia.org/wiki/Real_number) are all numbers that can be represented as a distance along a line, and negative means "reversed," e.g., $\sqrt{2}, \pi, \text{e}, ...$ # - $\mathbb{C}$: [Complex numbers](https://en.wikipedia.org/wiki/Complex_number) are all numbers of the form $a + b\textbf{i}$ where $a$ and $b$ are real numbers and $\textbf{i}$ is the [imaginary number](https://en.wikipedia.org/wiki/Imaginary_number), e.g., $0, \textbf{i}, 1 + \textbf{i}, ...$ # # In the listed order, the five sets are perfect subsets of the respective following sets, and $\mathbb{C}$ is the largest set (cf., the figure below illustrates that observation as well). To be precise, all sets are infinite, but they still have a different number of elements. # + [markdown] slideshow={"slide_type": "slide"} # <img src="static/numbers.png" width="75%" align="center"> # + [markdown] slideshow={"slide_type": "skip"} # The data types introduced in this chapter are all *imperfect* models of *abstract* mathematical ideas. # # The `int` and `Fraction` types are the models "closest" to the idea they implement: Whereas $\mathbb{Z}$ and $\mathbb{Q}$ are, by definition, infinite, every computer runs out of bits when representing sufficiently large integers or fractions with a sufficiently large number of decimals. However, within a system-dependent range, we can model an integer or fraction without any loss in precision. # # For the other types, in particular, the `float` type, the implications of their imprecision are discussed in detail above. # # The abstract concepts behind the four outer-most mathematical sets are formalized in Python since [PEP 3141](https://www.python.org/dev/peps/pep-3141/) in 2007. The [numbers](https://docs.python.org/3/library/numbers.html) module in the [standard library](https://docs.python.org/3/library/index.html) defines what programmers call the **[numerical tower](https://en.wikipedia.org/wiki/Numerical_tower)**, a collection of five **[abstract data types](https://en.wikipedia.org/wiki/Abstract_data_type)**, or **abstract base classes** (ABCs) as they are called in Python jargon: # # - `Number`: "any number" (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Number)) # - `Complex`: "all complex numbers" (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Complex)) # - `Real`: "all real numbers" (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Real)) # - `Rational`: "all rational numbers" (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Rational)) # - `Integral`: "all integers" (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Integral)) # + slideshow={"slide_type": "slide"} import numbers # + slideshow={"slide_type": "slide"} dir(numbers) # + [markdown] slideshow={"slide_type": "skip"} # As a reminder, the built-in [help()](https://docs.python.org/3/library/functions.html#help) function is always our friend. # # The ABCs' docstrings are unsurprisingly similar to the corresponding data types' docstrings. For now, let's not worry about the dunder-style names in the docstrings. # # For example, both `numbers.Complex` and `complex` list the `imag` and `real` attributes shown above. # + slideshow={"slide_type": "skip"} help(numbers.Complex) # + slideshow={"slide_type": "skip"} help(complex) # + [markdown] slideshow={"slide_type": "slide"} # ### Duck Typing # + [markdown] slideshow={"slide_type": "skip"} # The primary purpose of ABCs is to classify the *concrete* data types and standardize how they behave. This guides us as the programmers in what kind of behavior we should expect from objects of a given data type. In this context, ABCs are not reflected in code but only in our heads. # # For, example, as all numeric data types are `Complex` numbers in the abstract sense, they all work with the built-in [abs()](https://docs.python.org/3/library/functions.html#abs) function (cf., [documentation](https://docs.python.org/3/library/numbers.html#numbers.Complex)). While it is intuitively clear what the [absolute value](https://en.wikipedia.org/wiki/Absolute_value) (i.e., "distance" to $0$) of an integer, a fraction, or any real number is, [abs()](https://docs.python.org/3/library/functions.html#abs) calculates the equivalent of that for complex numbers. That concept is called the [magnitude](https://en.wikipedia.org/wiki/Magnitude_%28mathematics%29) of a number, and is really a *generalization* of the absolute value. # # Relating back to the concept of **duck typing** mentioned in [Chapter 4](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/master/04_iteration_00_lecture.ipynb#Type-Checking-&-Input-Validation), `int`, `float`, and `complex` objects "walk" and "quack" alike in context of the [abs()](https://docs.python.org/3/library/functions.html#abs) function. # + slideshow={"slide_type": "slide"} abs(-1) # + slideshow={"slide_type": "fragment"} abs(-42.87) # + slideshow={"slide_type": "fragment"} abs(4 - 3j) # + [markdown] slideshow={"slide_type": "skip"} # On the contrary, only `Real` numbers in the abstract sense may be rounded with the built-in [round()](https://docs.python.org/3/library/functions.html#round) function. # + slideshow={"slide_type": "slide"} round(123, -2) # + slideshow={"slide_type": "fragment"} round(42.1) # + [markdown] slideshow={"slide_type": "skip"} # `Complex` numbers are two-dimensional. So, rounding makes no sense here and leads to a `TypeError`. So, in the context of the [round()](https://docs.python.org/3/library/functions.html#round) function, `int` and `float` objects "walk" and "quack" alike whereas `complex` objects do not. # + slideshow={"slide_type": "fragment"} round(1 + 2j) # + [markdown] slideshow={"slide_type": "slide"} # ### Goose Typing # + [markdown] slideshow={"slide_type": "skip"} # Another way to use ABCs is in place of a *concrete* data type. # # For example, we may pass them as arguments to the built-in [isinstance()](https://docs.python.org/3/library/functions.html#isinstance) function and check in which of the five mathematical sets the object `1 / 10` is. # + slideshow={"slide_type": "slide"} isinstance(1 / 10, float) # + [markdown] slideshow={"slide_type": "skip"} # A `float` object is a generic `Number` in the abstract sense but may also be seen as a `Complex` or `Real` number. # + slideshow={"slide_type": "fragment"} isinstance(1 / 10, numbers.Number) # + slideshow={"slide_type": "fragment"} isinstance(1 / 10, numbers.Complex) # + slideshow={"slide_type": "fragment"} isinstance(1 / 10, numbers.Real) # + [markdown] slideshow={"slide_type": "skip"} # Due to the `float` type's inherent imprecision, `1 / 10` is *not* a `Rational` number. # + slideshow={"slide_type": "fragment"} isinstance(1 / 10, numbers.Rational) # + [markdown] slideshow={"slide_type": "skip"} # However, if we model `1 / 10` as a `Fraction`, it is recognized as a `Rational` number. # + slideshow={"slide_type": "skip"} isinstance(Fraction("1/10"), numbers.Rational) # + [markdown] slideshow={"slide_type": "skip"} # Replacing *concrete* data types with ABCs is particularly valuable in the context of input validation: The revised version of the `factorial()` function below allows its user to take advantage of *duck typing*: If a real but non-integer argument `n` is passed in, `factorial()` tries to cast `n` as an `int` object with the [int()](https://docs.python.org/3/library/functions.html#int) built-in. # # Two popular and distinguished Pythonistas, [<NAME>](https://github.com/ramalho) and [<NAME>](https://en.wikipedia.org/wiki/Alex_Martelli), coin the term **goose typing** to specifically mean using the built-in [isinstance()](https://docs.python.org/3/library/functions.html#isinstance) function with an ABC (cf., Chapter 11 in this [book](https://www.amazon.com/Fluent-Python-Concise-Effective-Programming/dp/1491946008) or this [summary](https://dgkim5360.github.io/blog/python/2017/07/duck-typing-vs-goose-typing-pythonic-interfaces/) thereof). # + [markdown] slideshow={"slide_type": "skip"} # #### Example: [Factorial](https://en.wikipedia.org/wiki/Factorial) (revisited) # + slideshow={"slide_type": "slide"} def factorial(n, *, strict=True): """Calculate the factorial of a number. Args: n (int): number to calculate the factorial for; must be positive strict (bool): if n must not contain decimals; defaults to True; if set to False, the decimals in n are ignored Returns: factorial (int) Raises: TypeError: if n is not an integer or cannot be cast as such ValueError: if n is negative """ if not isinstance(n, numbers.Integral): if isinstance(n, numbers.Real): if n != int(n) and strict: raise TypeError("n is not integer-like; it has decimals") n = int(n) else: raise TypeError("Factorial is only defined for integers") if n < 0: raise ValueError("Factorial is not defined for negative integers") elif n == 0: return 1 return n * factorial(n - 1) # + [markdown] slideshow={"slide_type": "skip"} # `factorial()` works as before, but now also accepts, for example, `float` numbers. # + slideshow={"slide_type": "slide"} factorial(0) # + slideshow={"slide_type": "fragment"} factorial(3) # + slideshow={"slide_type": "fragment"} factorial(3.0) # + [markdown] slideshow={"slide_type": "skip"} # With the keyword-only argument `strict`, we can control whether or not a passed in `float` object may come with decimals that are then truncated. By default, this is not allowed and results in a `TypeError`. # + slideshow={"slide_type": "slide"} factorial(3.1) # + [markdown] slideshow={"slide_type": "skip"} # In non-strict mode, the passed in `3.1` is truncated into `3` resulting in a factorial of `6`. # + slideshow={"slide_type": "fragment"} factorial(3.1, strict=False) # + [markdown] slideshow={"slide_type": "skip"} # For `complex` numbers, `factorial()` still raises a `TypeError` because they are neither an `Integral` nor a `Real` number. # + slideshow={"slide_type": "slide"} factorial(1 + 2j) # + [markdown] slideshow={"slide_type": "skip"} # ## TL;DR # + [markdown] slideshow={"slide_type": "skip"} # There exist three numeric types in core Python: # - `int`: a near-perfect model for whole numbers (i.e., $\mathbb{Z}$); inherently precise # - `float`: the "gold" standard to approximate real numbers (i.e., $\mathbb{R}$); inherently imprecise # - `complex`: layer on top of the `float` type to approximate complex numbers (i.e., $\mathbb{C}$); inherently imprecise # # Furthermore, the [standard library](https://docs.python.org/3/library/index.html) provides two more types that can be used as substitutes for the `float` type: # - `Decimal`: similar to `float` but allows customizing the precision; still inherently imprecise # - `Fraction`: a near-perfect model for rational numbers (i.e., $\mathbb{Q}$); built on top of the `int` type and therefore inherently precise # # The *important* takeaways for the data science practitioner are: # # 1. **Do not mix** precise and imprecise data types, and # 2. actively expect `nan` results when working with `float` numbers as there are no **loud failures**. # # The **numerical tower** is Python's way of implementing various **abstract** ideas of what numbers are in mathematics. # + [markdown] slideshow={"slide_type": "skip"} # ## Further Resources # + [markdown] slideshow={"slide_type": "skip"} # The two videos below show how addition and multiplication works with numbers in their binary representations. Subtraction is a bit more involved as we need to understand how negative numbers are represented in binary with the concept of [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement) first. A video on that is shown further below. Division in binary is actually also quite simple. # + slideshow={"slide_type": "skip"} from IPython.display import YouTubeVideo YouTubeVideo("RgklPQ8rbkg", width="60%") # + slideshow={"slide_type": "skip"} YouTubeVideo("xHWKYFhhtJQ", width="60%") # + [markdown] slideshow={"slide_type": "skip"} # The video below explains the idea behind [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement). This is how most modern programming languages implement negative integers. The video also shows how subtraction in binary works. # + slideshow={"slide_type": "skip"} YouTubeVideo("4qH4unVtJkE", width="60%") # + [markdown] slideshow={"slide_type": "skip"} # This video by the YouTube channel [Computerphile](https://www.youtube.com/channel/UC9-y-6csu5WGm29I7JiwpnA) explains floating point numbers in an intuitive way with some numeric examples. # + slideshow={"slide_type": "skip"} YouTubeVideo("PZRI1IfStY0", width="60%") # + [markdown] slideshow={"slide_type": "skip"} # Below is a short introduction to [complex numbers](https://en.wikipedia.org/wiki/Complex_number) by [MIT](https://www.mit.edu) professor [<NAME>](https://en.wikipedia.org/wiki/Gilbert_Strang) aimed at high school students. # + slideshow={"slide_type": "skip"} YouTubeVideo("Jkv-55ndVYY", width="60%")
05_numbers_00_lecture.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/IEwaspbusters/KopuruVespaCompetitionIE/blob/main/Competition_subs/2021-04-28_submit/batch_LARVAE/HEX.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # - # # XGBoost Years: Prediction with Cluster Variables and selected Weather Variables (according to Feature importance) # ## Import the Data & Modules # + colab={"base_uri": "https://localhost:8080/"} id="rt-Jj2BjesTz" outputId="171cecde-0242-4aaf-82b8-0e3458dff994" # Base packages ----------------------------------- import pandas as pd import numpy as np # Data Viz ----------------------------------- import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (15, 10) # to set figure size when ploting feature_importance # XGBoost ------------------------------- import xgboost as xgb from xgboost import XGBRegressor from xgboost import plot_importance # built-in function to plot features ordered by their importance # SKLearn ----------------------------------------- from sklearn import preprocessing # scaling data # + code_folding=[] # Function that checks if final Output is ready for submission or needs revision def check_data(HEX): def template_checker(HEX): submission_df = (HEX["CODIGO MUNICIPIO"].astype("string")+HEX["NOMBRE MUNICIPIO"]).sort_values().reset_index(drop=True) template_df = (template["CODIGO MUNICIPIO"].astype("string")+template["NOMBRE MUNICIPIO"]).sort_values().reset_index(drop=True) check_df = pd.DataFrame({"submission_df":submission_df,"template_df":template_df}) check_df["check"] = check_df.submission_df == check_df.template_df if (check_df.check == False).any(): pd.options.display.max_rows = 112 return check_df.loc[check_df.check == False,:] else: return "All Municipality Names and Codes to be submitted match the Template" print("Submission form Shape is", HEX.shape) print("Number of Municipalities is", HEX["CODIGO MUNICIPIO"].nunique()) print("The Total 2020 Nests' Prediction is", int(HEX["NIDOS 2020"].sum())) assert HEX.shape == (112, 3), "Error: Shape is incorrect." assert HEX["CODIGO MUNICIPIO"].nunique() == 112, "Error: Number of unique municipalities is correct." return template_checker(HEX) # + id="9MLidG_FwhYB" # Importing datasets from GitHub as Pandas Dataframes queen_train = pd.read_csv("../Feeder_years/WBds03_QUEENtrainYears.csv", encoding="utf-8") #2018+2019 test df queen_predict = pd.read_csv("../Feeder_years/WBds03_QUEENpredictYears.csv", encoding="utf-8") #2020 prediction df queen_clusters = pd.read_csv("../Feeder_years/WBds_CLUSTERSnests.csv",sep=",") template = pd.read_csv("../../../Input_open_data/ds01_PLANTILLA-RETO-AVISPAS-KOPURU.csv",sep=";", encoding="utf-8") # - # ## Further Clean the Data # + # Adding cluster labels queen_train = pd.merge(queen_train, queen_clusters, how = 'left', left_on = 'municip_code', right_on = 'municip_code') queen_predict = pd.merge(queen_predict, queen_clusters, how = 'left', left_on = 'municip_code', right_on = 'municip_code') # + # Remove the Municipalities to which we did not assign a Cluster, since there was not reliable data for us to predict queen_train = queen_train.loc[~queen_train.municip_code.isin([48071, 48074, 48022, 48088, 48051, 48020]),:].copy() queen_predict = queen_predict.loc[~queen_predict.municip_code.isin([48071, 48074, 48022, 48088, 48051, 48020]),:].copy() # - # ## Get the Prediction for: Cluster 1 # ### Arrange data into a features matrix and target vector # + # selecting the train X & y variables # Y will be the response variable (filter for the number of wasp nests - waspbust_id) y = queen_train.NESTS # X will be the explanatory variables. Remove response variable and non desired categorical columns such as (municip code, year, etc...) X = queen_train.iloc[:,6:-10].drop(["station_code"],axis=1).copy() X["cluster"] = queen_train.Cluster.copy() # We want to predict our response variable (number of nests in 2020). Remove response variable and non desired categorical columns such as (municip code, year, etc...) queen_predict2020 = queen_predict.iloc[:,6:-10].drop("station_code",axis=1).copy() queen_predict2020["cluster"] = queen_predict.Cluster.copy() # - # Check if the shape of the features and their labels match or if there are errors raised # + # Perform checks of features labels & their shapes assert queen_predict2020.shape[1] == X.shape[1], "Error: Number of columns do not match!" assert (queen_predict2020.columns == X.columns).any(), "Error: Columns labels do not match" assert y.shape == (212,), "Error: y shape is incorrect!" # - # ### Scale the Data in order to filter the relevant variables using Feature Importance # #### Arrange data into a features matrix and target vector # + # Scale the datasets using MinMaxScaler X_scaled = preprocessing.minmax_scale(X) # this creates a numpy array X_scaled = pd.DataFrame(X_scaled,index=X.index,columns=X.columns) # create a Pandas Dataframe == X # - # #### Choose a class of model by importing the appropriate estimator class # selecting the XGBoost model and fitting with the train data model = XGBRegressor() # #### Fit the model to your data by calling the `.fit()` method of the model instance # + # selecting the XGBoost model and fitting with the train data for each cluster model.fit(X_scaled, y) # - # #### Selecting the Relevant Variables and filtering according to the results # + tags=[] # Plot the Relevant Variables in order to filter the relevant ones per Cluster plot_importance(model,height=0.5,xlabel="F-Score",ylabel="Feature Importance",grid=False) plt.show() # + # selecting the XGBoost model and fitting with the train data without the irrelevant variables X = queen_train.loc[:,["population","food_txakoli","food_apple","weath_days_frost","weath_humidity","weath_maxLevel","food_kiwi","Cluster"]].copy() queen_predict2020 = queen_predict.loc[:,["population","food_txakoli","food_apple","weath_days_frost","weath_humidity","weath_maxLevel","food_kiwi","Cluster"]].copy() # - # ### Choose a class of model by importing the appropriate estimator class # + # selecting the XGBoost model and fitting with the train data model = XGBRegressor() # - # ### Fit the model to your data by calling the `.fit()` method of the model instance # + # refitting the model model.fit(X, y) # - # ### Apply the model to new data: # # - For supervised learning, predict labels for unknown data using the `.predict()` method # + # make a prediction prediction_2020 = model.predict(queen_predict2020) # - # ## Add Each Cluster Predictions to the original DataFrame and Save it as a `.csv file` # Create a new Column with the 2020 prediction queen_predict["nests_2020"] = prediction_2020 # + # Create a new DataFrame with the Municipalities to insert manualy HEX_aux = pd.DataFrame({"CODIGO MUNICIPIO":[48022, 48071, 48088, 48074, 48051, 48020],\ "NOMBRE MUNICIPIO":["Karrantza Harana/Valle de Carranza","Muskiz","Ubide","Urduña/Orduña","Lanestosa","Bilbao"],\ "NIDOS 2020":[0,0,0,0,0,0]}) # + id="Z3PcQ4UnACCA" HEX = queen_predict.loc[:,["municip_code","municip_name_x","nests_2020"]].round() # create a new Dataframe for Kopuru submission HEX.columns = ["CODIGO MUNICIPIO","NOMBRE MUNICIPIO","NIDOS 2020"] # change column names to Spanish (Decidata template) HEX = HEX.append(HEX_aux, ignore_index=True) # Add rows of municipalities to add manually # + # Final check check_data(HEX) # + # reset max_rows to default values (used in function to see which rows did not match template) pd.reset_option("max_rows") # + id="uiPq7zXi0STt" # Save the new dataFrame as a .csv in the current working directory on Windows HEX.to_csv("WaspBusters_20210519_XGyears_cluster_var.csv", index=False, encoding="latin-1")
B_Submissions_Kopuru_competition/2021-05-26_submit/Batch_XGboost/workerbee05_HEX_XGyears_cluster_var.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Analysis of Unicode Character Names # ## Character data from Python `unicodedata` module import sys import unicodedata sys.maxunicode unicodedata.unidata_version def python_named_chars(): for code in range(sys.maxunicode): char = chr(code) try: yield char, unicodedata.name(char) except ValueError: # no such name continue l_py = list(python_named_chars()) len(l_py) l_py[0] l_py[:5], l_py[-5:] set_py = {name for _, name in l_py} # + import collections words = collections.Counter() for _, name in l_py: parts = name.replace('-', ' ').split() words.update(parts) len(words) # - for word, count in words.most_common(10): print(f'{count:6d} {word}') mc = [(w, c) for w, c in words.most_common() if c > 1] len(mc) mc[len(mc)//100] # ## Character data from `UnicodeData.txt` len(list(open('UnicodeData.txt'))) import ucd # local module l_ucd = list(ucd.parser()) len(l_ucd) l_ucd[:5], l_ucd[-5:] set_ucd = {rec.name for rec in l_ucd} # ## Difference between names from `unicodedata` module and `UnicodeData.txt` # # > Note: `UnicodeData.txt` does not contain algorthmically derived names such as `'CJK UNIFIED IDEOGRAPH-20004'` set_py > set_ucd set_ucd > set_py ucd_only = sorted(set_ucd - set_py) len(ucd_only) ucd_only[:7], ucd_only[-7:] py_only = sorted(set_py - set_ucd) len(py_only) py_only[:7], py_only[-7:] # + import collections words = collections.Counter() for name in py_only: if 'CJK UNIFIED IDEOGRAPH' in name: continue parts = name.replace('-', ' ').split() words.update(parts) len(words) # - for word, count in words.most_common(10): print(f'{count:6d} {word}') # + words = collections.Counter() for name in sorted(set_ucd): parts = name.replace('-', ' ').split() words.update(parts) len(words) # - for word, count in words.most_common(100): print(f'{count:6d} {word}') max(words, key=len) singles = sorted((count, word) for word, count in words.items() if len(word)==1) len(singles) for count, word in reversed(singles): print(f'{count:6d} {word}') unique = sorted(word for word, count in words.items() if count==1) len(unique) unique[:50], unique[-50:]
unicode/servers/name-analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/learnlatex.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="M_IYHSO3fN5l" # # メモ # colab で latex を勉強するためのノートブックです。 # # colab で開いてください。 # # https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/learnlatex.ipynb # # colab でテキストセル内で &dollar; マークを使うと数式を latex で処理して美しく表示できる。 # $$ \int f(x)dx $$ # # これを latex でどう書いているかは、セルをダブルクリックするかセルを選択して Ctrl+Enter を押して、編集モードにすることで見ることができる。 # # + [markdown] id="5FDxKNL9mZED" # もっと明示的にコードセルで `%%latex` マジックを使って書くことができる。 # # この場合はコードセルをセルの左側の丸に右向き三角の実行ボタンを押すか、Ctrl+Enter で実行して出力としてレンダリングされた表示を見ることになる。 # # colab の latex は完全な latex ではない。 mathjax ベースのサブセットである。 数式を書くのに便利。 # # このノートブックではテキストセルで表示して同じことを、コードセルで実行できるようにすることで、いちいち編集モードに入らずに読み進められるようにしたい。 # # + colab={"base_uri": "https://localhost:8080/", "height": 38} id="StwWQ1xuncNF" outputId="58850e49-124a-4371-e223-62ddb925d47f" # 例 # %%latex \int f(x)dx # + [markdown] id="X4JZJvQLY_rw" # # 参考サイト # # TeX入門 ( http://www.comp.tmu.ac.jp/tsakai/lectures/intro_tex.html ) # TeX入門Wiki ( https://texwiki.texjp.org/) # Learn LaTeX in 30 minutes ( https://www.overleaf.com/learn/latex/ # Learn_LaTeX_in_30_minutes ) # MathJax ( https://docs.mathjax.org/en/v2.5-latest/tex.html ) # MathJaxの使い方( # http://www.eng.niigata-u.ac.jp/~nomoto/download/mathjax.pdf) # + [markdown] id="i_Cod0PRbZRu" # # 数式記号一覧 # # The Comprehensive LaTeX Symbol List - The CTAN archive ( http://tug.ctan.org/info/symbols/comprehensive/symbols-a4.pdf ) # # Short Math Guide for LaTeX ( https://ftp.yz.yamagata-u.ac.jp/pub/CTAN/info/short-math-guide/short-math-guide.pdf ) # # ギリシャ文字, ドイツ文字, 花文字, 筆記体の TeX 表記をまとめておいた ( https://phasetr.com/blog/2013/04/14/ギリシャ文字-ドイツ文字-筆記体の-tex-表記を/ ) # + [markdown] id="dlP5VSVvbsxB" # # はじめに ~ 実験学習 # # + [markdown] id="4iJm4gvVNuCc" # マークダウンでテキストの中に latex を入れることができる。 # インラインで入れることもできるし $x = 3$ とか。 # # $$ # x = 3 # $$ # # とか。 # # + [markdown] id="ENrYHoYLWZmG" # テキストセルでは数式を &dollar; マークで囲むとインライン、&dollar;&dollar; で囲むと段落を変えて表示する。 # # 表示された数式の latex での表記はセルを編集モードにすると見ることができる。 # # 編集モードにするにはセルを選択してダブルクリックするか Enter キーを押す。 # # # + colab={"base_uri": "https://localhost:8080/", "height": 38} id="wOsNxaXaXPUy" outputId="45ca7d34-e2e0-4bb0-c467-5b8f38d73e29" # コードセルで %%latex で表示する # 編集モードにしなくても latex 表記ができるので latex の学習には便利 # コードセルを実行しないと数式表記にならない。 # コードセルの実行はセルの左の実行ボタン(右向き三角)を押すか、Ctrl+Enter を押す。 # x = 3 の数字を変えて実行してみよう # %%latex x = 3 # + colab={"base_uri": "https://localhost:8080/", "height": 72} id="ztMpC1OwjeeE" outputId="4ae94a0d-08ef-4b6d-d13f-e593e5008281" # 実験 python プログラムで表示することもできる。このノートブックでは学習対象としない。 from sympy import * from IPython.display import Markdown display(Markdown("実験学習 $x = 3$ と書く")) x = symbols('x') display(Eq(x,3)) # + [markdown] id="RLjJ7URGdV1Z" # # マークダウンと %%latex の違い (参考) # 1. コードセルに %%latex と書くとその行以降 mathjax のルールが適用される。 # 1. %%latex以降にバックスラッシュ \ でエスケープされていない \$ マークがあると latex で解釈せずに入力のまま出力する。 # 1. % 記号はコメント記号なので文法上は許されるが、% 記号以降が出力されないのでバックスラッシュ \ でエスケープする必要がある。 # 1. バックスラッシュ \ 自体は \backslash と書く。 波記号 チルダ tilde ~ は \tilde{}、キャレット、ハット記号、サーカムフレックス、circumflex ^ は \hat{} になる。 # 1. 地の文、テキストも数式として解釈されるので、英文字はフォントが変わる。普通の文字にしたい場合は \text{} で括る。 # 1. 改行はマークダウンではスペース 2 個だが、%%latex では バックスラッシュ \ を2個 \\\\ になる。 # 1. その他マークダウン上の便利な機能。箇条書きの自動ナンバリングなどは使えない。 # # + colab={"base_uri": "https://localhost:8080/", "height": 183} id="Osz4ublTk27V" outputId="13ee6b85-0b16-4336-95ed-ac19aeac6050" # 実験 # %%latex this is a pen. \\ \text{this is a pen} \\ \backslash \\ \tilde{x}\\ \tilde{} \quad x\\ \hat{x} \\ \hat{} \quad x \\ x^3 \\ # + [markdown] id="ug4l1dHmOnvE" # 同じことをマークダウンでやってみる。 # # $this is a pen.$ # $\text{this is a pen}$ # $\backslash$ # $\tilde{x}$ # $\tilde{} \quad x$ # $\hat{x} $ # $\hat{} \quad x $ # $x^3 $ # + id="YswKX7ujjxzA" colab={"base_uri": "https://localhost:8080/", "height": 60} outputId="1a5919fe-929f-4f21-f013-f5e6cff97fb5" # これはコメント # %%latex y = 5 \\ % これはコメント x = 3 # + [markdown] id="gS-20EZ4B0lL" # # 簡単な数式 # + id="NXhBtJwreRGG" colab={"base_uri": "https://localhost:8080/", "height": 38} outputId="55b28ffd-22e1-4656-b3e8-c3b5f790891d" language="latex" # E = mc^2 # + [markdown] id="VQ5cdQKxB0lO" # マークダウンでドルサインで囲むと latex(mathjax) になる。 2 個のドルサインで囲むと行替えされ、センタリングされた数式になる。 # # $$ E=mc^2$$ # # ここで $c$ は光速を表し、値は次の通り。 # # $$ c = 299{,}792{,}458 \, \mathrm{m/s} $$ # # いわゆる光速は 30 万キロ/秒というやつね!!!! # # 地球 7 周り半。 # # + id="XaZ9k2NuebYv" colab={"base_uri": "https://localhost:8080/", "height": 74} outputId="638d2ff0-b2ae-4e1a-99d2-c2f469159d56" language="latex" # E =mc^2 \\[0.8em] # c = 299{,}792{,}458 \, \mathrm{m/s} # + [markdown] id="7JZQs8Ize_jf" # 数字のカンマは `{,}` として入れる。 波括弧 brace で囲む。 # # + [markdown] id="JJRGMDwVF90w" # # ドル`$`マーク ドルサインをエスケープするには # # この本は\$35.40。これはマークダウン。 # # この本は $\$35.40$ 。これは latex。 # # ドルサインは latex (mathjax) 対応のマークダウンでは mathjax の begin, end の記号なので、エスケープする必要がある。 # # colab 環境ではバックスラッシュ `\` でエスケープできる。 # # ドルサイン自体を HTML文字参照で書く、という方法もある。 # # `&#36; ` # `&#x24;` # `&dollar;` # # HTML文字参照は latex の中では使えない。 # # + [markdown] id="5Bj1HdA_dkGx" # 同一セル内でペアになっていないと表示される。 # # $ # # $$ # + [markdown] id="ji3YyhsGKjpV" # # 水平方向の空白 # + id="s98H-qzjKkTo" colab={"base_uri": "https://localhost:8080/", "height": 146} outputId="d4be56d3-2acf-4b1a-a5c2-8f0369ee2ccc" # 水平方向の空白の実験 # \+セミコロン、スペース、チルダが標準的な 1 文字スペースのようである # とりあえずセミコロンがわかりやすいので \; とする # %%latex a\;b\;c\;d\;e\;f\;g\; セミコロン\\ a\ b\ c\ d\ e\ f\ g\ スペース\\ a~b~c~d~e~f~g~ tilde\\ a\,b\,c\,d\,e\,f\,g\, カンマ\\ a~~b~~c~~d~~e~~f~~g~~ tilde2\\ a\quad b\quad c\quad d\quad e\quad f\quad g\quad quad\\ # + [markdown] id="L872XDCqfsyM" # # 改行と空行 # # + [markdown] id="D07ckSl95vvl" # マークダウン中の latex の中での改行は無視される。 # # # 結合されて、1 つの文になる。 # # 改行は `\` を行末に2個入れる。 # # 行間をあける (空白行を入れる) のはけっこうむずかしい。 # # \{\}+\\\\ # `{}\\` # # とか。 # # # + [markdown] id="A3Z0alVOPf75" # #インテグラル 積分 # $$ # \frac{\pi}{2} = # \left( \int_{0}^{\infty} \frac{\sin x}{\sqrt{x}} dx \right)^2 = # \sum_{k=0}^{\infty} \frac{(2k)!}{2^{2k}(k!)^2} \frac{1}{2k+1} = # \prod_{k=1}^{\infty} \frac{4k^2}{4k^2 - 1} # $$ # + id="z_hJqC1ggHRw" colab={"base_uri": "https://localhost:8080/", "height": 67} outputId="c809418a-f158-4738-d931-1cc7aa950f82" # インテグラル 積分記号 # latex では \int , sympy では Integral # %%latex \displaystyle \frac{\pi}{2} = \left( \int_{0}^{\infty} \frac{\sin x}{\sqrt{x}} dx \right)^2 = \sum_{k=0}^{\infty} \frac{(2k)!}{2^{2k}(k!)^2} \frac{1}{2k+1} = \prod_{k=1}^{\infty} \frac{4k^2}{4k^2 - 1} # + [markdown] id="ufdfBaWyw9Te" # `\displaystyle`としないと、インラインスタイルでフォントが小さくなってしまう。 # # # + [markdown] id="NgmgaN0pnnAY" # # フォントの実験 # + [markdown] id="ohnAEa3ppMIq" # マークダウンで英文字は # abcdefABC # となるが、ドルサインで囲って latex にすると、数学用のフォントになる。 # $abcdefABC$ # この latex のなかで text とすると数学フォントではなくなる。 # $\text{This is a text}$ # # * latex -> $abcdefABC$ $\quad$ 通常の数式書体 # * \mathrm -> $\mathrm{abcdefABC}$ $\quad$ sin, cos など数式 # *\boldsymbol -> $\boldsymbol{abcdefABC}$ $\quad$ ベクトルに使う # * \mathbf -> $\mathbf{abcdefABC}$ $\quad$ $\mathbf{NZRC}$ # * \mathbb -> $\mathbb{abcdefABC}$ $\quad$ $\mathbb{NZRC}$ # * \mathcal -> $\mathcal{abcdefABC}$ $\quad$ # * \mathfrak -> $\mathfrak{abcdefABC}$ $\quad$ # # 数学のテキストでのアルファベットの使い分けは通常はイタリックで、座標とかはセリフ付きのローマン体の大文字が使われている。 ベクトルを小文字で表すときに上矢印をつけずにボールド体を使うことがある。 # # 手書きで部分白抜きを真似た mathbb というのもあって、これで書かれたテキストもある。 # # &nbsp; # + [markdown] id="izyrEmSv6mIS" # # 行列 matrix # + [markdown] id="3-QF3ROg3LXj" # $ # A =\begin{pmatrix} # a_{11} & \ldots & a_{1n} \\ # \vdots & \ddots & \vdots \\ # a_{m1} & \ldots & a_{mn} # \end{pmatrix}$ # + id="FbVx5XVeB0lT" colab={"base_uri": "https://localhost:8080/", "height": 90} outputId="2ef4ece8-73c6-4791-c613-1103031a8ad3" language="latex" # \displaystyle # A =\begin{pmatrix} # a_{11} & \ldots & a_{1n} \\ # \vdots & \ddots & \vdots \\ # a_{m1} & \ldots & a_{mn} # \end{pmatrix} \quad # A =\begin{bmatrix} # a_{11} & \ldots & a_{1n} \\ # \vdots & \ddots & \vdots \\ # a_{m1} & \ldots & a_{mn} # \end{bmatrix} # + [markdown] id="l0WOCX6ZbsFA" # 直交行列 # 実対称行列 $A$ は直交行列 $P$ によって # $D = P^{-1} A P$ # と対角行列 $D$ に対角化される。 # # + id="hGPGMKjC5tUm" colab={"base_uri": "https://localhost:8080/", "height": 38} outputId="51797684-bb8a-4f5d-97a8-40944676c941" # 直交行列 # %%latex D = P^{-1} A P # + [markdown] id="dY6bVGzBps3v" # 数列の合計シグマ、無限、階乗 # $$ # \sin x = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} # $$ # + id="qXRmBXE2PuHC" colab={"base_uri": "https://localhost:8080/", "height": 66} outputId="3d936ad4-9139-4511-d3f3-5b4b9fc1d71e" language="latex" # \displaystyle # \sin x = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} # + [markdown] id="bLZ6VPGFqARq" # # 積分記号、イプシロン、極限 # $$ # \int_{0}^{1} \log x \,dx # = \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x \,dx # = \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} # = -1 # $$ # + id="BwuoDXTSQKR7" colab={"base_uri": "https://localhost:8080/", "height": 59} outputId="c8d5d23b-8c85-41c8-8199-8830315ceec5" # \int, Integral, \lim, # %%latex \displaystyle \int_{0}^{1} \log x \,dx = \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x \,dx = \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} = -1 # + [markdown] id="jZ4nUZbeqf2I" # # array, eqnarray, align, cases # それぞれ違いがあるが、汎用的なのは array だろう。 # $$ # \begin{array}{lcl} # \displaystyle \int_{0}^{1} \log x dx # & = \quad & \displaystyle \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x dx \\ # & = & \displaystyle \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} \\ # & = & -1 # \end{array} # $$ # # &nbsp; # $$ # \begin{eqnarray} # \int_{0}^{1} \log x dx # & = & \displaystyle \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x dx \\ # & = & \displaystyle \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} \\ # & = & -1 # \end{eqnarray} # $$ # # &nbsp; # # $$ # \begin{align} # \int_{0}^{1} \log x dx # & = & \displaystyle \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x dx \\ # & = & \displaystyle \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} \\ # & = & -1 # \end{align} # $$ # # &nbsp; # # # $$ # \begin{align} # \int_1^x \{ye^{-t^2}\}'dt &=&\int_1^x e^{-t^2}tdt \\ # \left[ye^{-t^2}\right]_1^x &=& \left[-{1\over 2}e^{-t^2}\right]_1^x \\ # ye^{-x^2}-2e^{-1} &=& -{1\over 2}e^{-x^2}+{1\over 2}e^{-1} \\ # ye^{-x^2} &=& -{1\over 2}e^{-x^2}+{5\over 2}e^{-1} # \end{align} # $$ # + id="SqHt58ANQ-Nb" colab={"base_uri": "https://localhost:8080/", "height": 107} outputId="60015dd3-738c-4c1f-d359-a00ba37be4df" language="latex" # \begin{array}{lcl} # \displaystyle # \int_{0}^{1} \log x dx # & = & \displaystyle \lim_{\epsilon \to +0} \int_{\epsilon}^{1} \log x dx \\ # & = & \displaystyle \lim_{\epsilon \to +0} [x \log x - x]_{\epsilon}^{1} \\ # & = & -1 # \end{array} # + id="koHc7A_oKAVw" colab={"base_uri": "https://localhost:8080/", "height": 58} outputId="d1907b6d-d97c-411d-a54e-7a85d09254cf" # \begin{array} の使い方。 # %%latex \displaystyle \begin{array} lkj;lkj & = & jk \\ & = & kj;ljk;jk;j \end{array} # + [markdown] id="FaFeoc9X-be2" # # array で行間が狭いとき # array で行間が狭いときには \\ のあとに [0.3em] とか入れる # # $$ # \displaystyle # \begin{array}{lcl} # \sin(\alpha \pm \beta) & = & \sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ # \cos(\alpha \pm \beta) & = & \cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\[0.5em] # \tan(\alpha \pm \beta) & = & \displaystyle \frac{\tan \alpha \pm \tan \beta}{1 \mp \tan \alpha \tan \beta} # \end{array} # $$ # + id="Jb03yr1JSOma" colab={"base_uri": "https://localhost:8080/", "height": 101} outputId="3584ae50-e229-4c41-edf6-0dcd8584404e" # 行間がきついときには \\ のあとに [0.3em] とか入れる # %%latex \displaystyle \begin{array}{lcl} \sin(\alpha \pm \beta) & = & \sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ \cos(\alpha \pm \beta) & = & \cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\[0.3em] \tan(\alpha \pm \beta) & = & \displaystyle \frac{\tan \alpha \pm \tan \beta}{1 \mp \tan \alpha \tan \beta} \end{array} # + id="GV3TDo_bTfD9" colab={"base_uri": "https://localhost:8080/", "height": 125} outputId="7a44b67c-bfca-4ca1-d39b-68d5a0323396" # 括弧のいろいろ 丸括弧 波括弧 角括弧 絶対値 # %%latex [ (x) ] \\ \{ x \}\\ \| x \| \\ | x | \\ \langle x \rangle # + id="xKyM3qnxWuEC" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="cf2a362f-a3b1-4e36-ee70-1df90ff45eb5" language="latex" # \displaystyle # \Bigg( \bigg[ \Big\{ \big\| \langle x \rangle \big\| \Big\} \bigg] \Bigg) # + [markdown] id="AsGPAw9E_ReN" # 左右の括弧に`\left`、`\right`をつけると自動で可変になる。 大きくなる。 # \left`、`\right`はかならずペアで、片方だけ使うときはピリオド `.` をつける。 # $$ # \displaystyle # \left( \frac{a}{b} \right) # \left( \int_a^\infty x \, dx \right) # $$ # + [markdown] id="iDYN1YVkwUwS" # 左寄せ、センタリング、右寄せ # # $$ # \begin{array}{lcr} # 111 & 222 & 333 \\ # 44 & 55 & 66 \\ # 7 & 8 & 9 # \end{array} # $$ # + id="yBKZWWP0hlDW" colab={"base_uri": "https://localhost:8080/", "height": 78} outputId="347808cf-5924-4b23-ea37-ca198644981f" language="latex" # # \begin{array}{lcr} # 111 & 222 & 333 \\ # 44 & 55 & 66 \\ # 7 & 8 & 9 # \end{array} # + [markdown] id="cZWWCTqp-3uT" # # 括弧のいろいろ 丸括弧 波括弧 角括弧 絶対値 大括弧 可変括弧 片括弧 山括弧 # $$ # [ (x) ] \\ # \{ x \}\\ # \| x \| \\ # | x | \\ # \langle x \rangle # $$ # + [markdown] id="OO4PbbU01aAD" # 左右の括弧に`\left`、`\right`をつけると自動で可変になる。 大きくなる。 # `\left`、`\right`はかならずペアで、片方だけ使うときはピリオド `.` をつける。 # # $$ # \left( \frac{a}{b} \right) # \left( \int_a^\infty x \, dx \right) # $$ # + id="Ka0qoGgeXAey" colab={"base_uri": "https://localhost:8080/", "height": 58} outputId="5e422c84-5516-42ea-9d29-7d4751adca3b" # 左右の括弧に`\left`、`\right`をつけると自動で可変になる。 大きくなる。 # `\left`、`\right`はかならずペアで、片方だけ使うときはピリオド `.` をつける。 # %%latex \displaystyle \left( \frac{a}{b} \right) \left( \int_a^\infty x \, dx \right) # + [markdown] id="baZf-hqz1k7I" # # 片括弧 # $$ # \displaystyle # \left\{ \frac{a}{b} \right. # $$ # # $$ # \left\{ # \begin{array}{lcl} # \sin(\alpha \pm \beta) & = & \sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ # \cos(\alpha \pm \beta) & = & \cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\[0.3em] # \tan(\alpha \pm \beta) & = & \displaystyle \frac{\tan \alpha \pm \tan \beta}{1 \mp \tan \alpha \tan \beta} # \end{array} # \right. # $$ # + id="UgkUWCtbabhj" colab={"base_uri": "https://localhost:8080/", "height": 49} outputId="f1e10ec6-e0db-49c8-d117-cc2d8ac2c296" # 括弧を片方だけつかってみる # %%latex \displaystyle \left\{ \frac{a}{b} \right. # + colab={"base_uri": "https://localhost:8080/", "height": 101} id="1ba_unNA85vz" outputId="1f42e49a-e3b7-4653-e429-e78afee8431a" # 括弧を片方だけつかってみる # %%latex \displaystyle \left\{ \begin{array}{lcl} \sin(\alpha \pm \beta) & = & \sin \alpha \cos \beta \pm \cos \alpha \sin \beta \\ \cos(\alpha \pm \beta) & = & \cos \alpha \cos \beta \mp \sin \alpha \sin \beta \\[0.3em] \tan(\alpha \pm \beta) & = & \displaystyle \frac{\tan \alpha \pm \tan \beta}{1 \mp \tan \alpha \tan \beta} \end{array} \right. # + [markdown] id="Sv4ZXkhuyXDm" # 行列を括弧で囲むには array ではなく pmatrix を使う。 # \left(,\right) を使うこともできる # $$ # # # %%latex # \begin{pmatrix} # 111 & 222 & 333 \\ # 44 & 55 & 66 \\ # 7 & 8 & 9 # \end{pmatrix} # $$ # $$ # \left( # \begin{array}{rrr} # 111 & 222 & 333 \\ # 44 & 55 & 66 \\ # 7 & 8 & 9 # \end{array} # \right) # $$ # + id="drq4hK7fmryu" colab={"base_uri": "https://localhost:8080/", "height": 139} outputId="b2968aee-424e-45a0-ed33-ae9ad2e36599" # 行列を括弧で囲むには array ではなく pmatrix を使う。 # \left(,\right) を使うこともできる # %%latex \begin{pmatrix} 111 & 222 & 333 \\ 44 & 55 & 66 \\ 7 & 8 & 9 \end{pmatrix} {}\\ \left( \begin{array}{rrr} 111 & 222 & 333 \\ 44 & 55 & 66 \\ 7 & 8 & 9 \end{array} \right) # + [markdown] id="PvCuS9Tcyr5F" # pmatrix は array のように item の位置指定ができない。 # # $$ # \begin{pmatrix} # a & longitem \\ # 128 & 3.1419 # \end{pmatrix} # $$ # + id="AzzGRXcJRLVn" colab={"base_uri": "https://localhost:8080/", "height": 58} outputId="9da9435b-8b86-4414-cfbf-a1407199b3f8" # pmatrix は array のように item の位置を指定することはできないみたい # %%latex \displaystyle \begin{pmatrix} a & longitem \\ 128 & 3.1419 \end{pmatrix} # + [markdown] id="0O1SWSw4SMjp" # # 複素関数 # # + [markdown] id="l21ix0zmy6JM" # **複素関数** # $$ # f(z) = f(x + i y ) = u (x, y) + iv(x, y) \\ # $$ # が点 \\ # $$ # z_0 = x_0 + iy_0 # $$ # # において正則であるための必要十分条件は、 # $ z_0 $ # のある # $ \varepsilon $ # 近傍 # $\Delta (z_0, \varepsilon) $ # においてコーシー・リーマン方程式 # # $$ # \begin {array}{ccc} # \displaystyle \frac{\partial u}{\partial x} &=& \displaystyle \frac{\partial v}{\partial y} \\ # \displaystyle \frac{\partial u}{\partial y} &=& \displaystyle - \frac{\partial v}{\partial x} # \end {array} # $$ # # を満たすことである。 # + id="jEwDgPrKU07h" colab={"base_uri": "https://localhost:8080/", "height": 280} outputId="20ebb8ce-9a6e-4656-a8c9-077e54d58d03" language="latex" # 複素関数 \\ # f(z) = f(x + i y ) = u (x, y) + iv(x, y) \\ # が点 \\ # z_0 = x_0 + iy_0 \\ # において正則であるための必要十分条件は、 \\ # z_0 # のある # \varepsilon # 近傍 \\ # \Delta (z_0, \varepsilon) \\ # においてコーシー・リーマン方程式 \\ # # \begin {array}{ccc} # \displaystyle \frac{\partial u}{\partial x} &=& \displaystyle \frac{\partial v}{\partial y} \\ # \displaystyle \frac{\partial u}{\partial y} &=& \displaystyle - \frac{\partial v}{\partial x} # \end {array} # \\ # を満たすことである。 # + [markdown] id="JCnkFEK7n0GD" # # 空間曲線 # # + [markdown] id="Ezf230dDz1mK" # **空間曲線** # $$ # c(t) = (x (t), y(t), z(t)) $$ # # によって与えられる空間曲線 c の $ # c(0)$ を始点として $c(t)$ までの弧長を $s(t)$ とすると # # $$ # s(t) = \displaystyle \int_0^t \sqrt { (\frac {dx}{dt})^2 # + (\frac {dy}{dt})^2 + (\frac {dz}{dt})^2} # $$ # と表される。 # + id="zBzYoUr9o6CI" colab={"base_uri": "https://localhost:8080/", "height": 146} outputId="39bf8026-c585-40f8-8002-ff2f0e2447e9" language="latex" # c(t) = (x (t), y(t), z(t)) \\ # によって与えられる空間曲線 c の \\ # c(0) を始点として c(t) までの弧長を s(t) とすると \\ # # s(t) = \displaystyle \int_0^t \sqrt { (\frac {dx}{dt})^2 # + (\frac {dy}{dt})^2 + (\frac {dz}{dt})^2} # \\ # と表される。 # + [markdown] id="v9f0D-eFpCl3" # # 微分可能 # # + [markdown] id="MYL3utjT0SYf" # **微分可能** # # 関数 $f$ が開区間 $I$ 上で $n$ 回微分可能であるとする。 # このとき、$a, b \in I$ に対し、 # # $$ # f(b) = \displaystyle f(a)+ \frac{f'(a)}{1!} (b - a) # + \frac{f''(a)}{2!} (b - a)^2 + \cdots # + \frac{f^{(n - 1)}(a)}{(n - 1)!} (b - a)^{(n - 1)} + R_n(c) # $$ # # を満たす $c$ が $a$ と $b$ の間に存在する。 # + id="hoLm8yHerEru" colab={"base_uri": "https://localhost:8080/", "height": 124} outputId="b7696a49-0b56-4c4c-df4f-10d76fbb930b" # 微分可能 # %%latex 関数 f が開区間 I 上で n 回微分可能であるとする。 \\ このとき、a, b \in I に対し、\\ f(b) = \displaystyle f(a)+ \frac{f'(a)}{1!} (b - a) + \frac{f''(a)}{2!} (b - a)^2 + \cdots + \frac{f^{(n - 1)}(a)}{(n - 1)!} (b - a)^{(n - 1)} + R_n(c) \\ を満たす c が a と b の間に存在する。 # + [markdown] id="R-e13l9GrQ43" # # $n$ 次正方行列 # # + [markdown] id="sMjuMGuvTEVk" # **$n$ 次正方行列** # $$ # J (\alpha, m) = \begin {bmatrix} # \alpha & 1 & 0 & \ldots & 0 \\ # 0 & \alpha & 1 & \ddots & \vdots \\ # \vdots & \ddots & \ddots & \ddots & 0 \\ # \vdots & & \ddots & \ddots & 1 \\ # 0 & \ldots & \ldots & 0 & \alpha # \end {bmatrix} # $$ # # を Jordan 細胞と呼ぶ。 正方行列 $A$ が正則行列 $P$ によって # # $$ # \begin {array} {lcl} # P^{-1} A P &=& J(\alpha_1, m_1) \oplus J(\alpha_2, m_2) \oplus \cdots \oplus J(\alpha_k, m_k) \\ # &=& \begin {bmatrix} # J(\alpha_1, m_1) & & & \\ # & J(\alpha_2, m_2) & & \\ # & & \ddots & \\ # & & & j(\alpha_k, m_k) # \end {bmatrix} # \end {array} \\ # $$ # # と Jordan 細胞の直和になるとき、これを $A$ の Jordan 標準形と呼ぶ。 # # + id="PtaIIJSRwUfX" colab={"base_uri": "https://localhost:8080/", "height": 298} outputId="631abe5f-9c8b-4a1f-d609-f46be5c79bad" # n次正方行列 # %%latex J (\alpha, m) = \begin {bmatrix} \alpha & 1 & 0 & \ldots & 0 \\ 0 & \alpha & 1 & \ddots & \vdots \\ \vdots & \ddots & \ddots & \ddots & 0 \\ \vdots & & \ddots & \ddots & 1 \\ 0 & \ldots & \ldots & 0 & \alpha \end {bmatrix} \\ を Jordan 細胞と呼ぶ。 正方行列 A が正則行列 P によって \\ \begin {array} {lcl} P^{-1} A P &=& J(\alpha_1, m_1) \oplus J(\alpha_2, m_2) \oplus \cdots \oplus J(\alpha_k, m_k) \\ &=& \begin {bmatrix} J(\alpha_1, m_1) & & & \\ & J(\alpha_2, m_2) & & \\ & & \ddots & \\ & & & j(\alpha_k, m_k) \end {bmatrix} \end {array} \\ と Jordan 細胞の直和になるとき、これを A の Jordan 標準形と呼ぶ。 # + [markdown] id="wdOsVm25xi6O" # # 二項関係 # # + [markdown] id="kyKAHNQ0qTLo" # # # **定義 1** 集合 $X$ 上の二項関係 $\rho$ について、次の性質を考える。 # # 1. すべての $x \in X$ について、$x \;\rho\; x$ が成り立つ。(反射律) # # 1. $x, y \in X$ について、$x \;\rho\; y$ ならば $y \;\rho\; x$ が成り立つ。(対称律) # # 1. $x, y, z \in X$ について、$x \;\rho\; y$ かつ $y \;\rho\; z$ ならば $x \;\rho\; z$ が成り立つ。(推移律) # # 1. $x, y \in X$ について、$x \;\rho\; y$ かつ $y \;\rho\; x$ ならば $x = y$ が成り立つ。(反対称律) # # 性質 $\it{1, 2, 3}$ を満たす二項関係を**同値関係**と呼び、性質 $\it{1, 3, 4}$ を満たす二項関係を**順序関係**と呼ぶ。 # # * reflexive law 反射律 # * transitive law 推移律 # * symmetric law 対称律 # * antisymmetric law 反対称律 # + colab={"base_uri": "https://localhost:8080/", "height": 146} id="vPJ7sqxYSIxz" outputId="b865a903-e038-41fb-c5c1-a81064553138" language="latex" # 定義 1 集合 X 上の二項関係 \;\rho\; について、次の性質を考える。\\ # # 1. すべての x \in X について、x \;\rho\; x が成り立つ。(反射律) \\ # 2. x, y \in X について、x \;\rho\; y ならば y \;\rho\; x が成り立つ。(対称律) \\ # 3. x, y, z \in X について、x \;\rho\; y かつ y \;\rho\; z ならば x \;\rho\; z が成り立つ。(推移律) \\ # 4. x, y \in X について、x \;\rho\; y かつ y \;\rho\; x ならば x = y が成り立つ。(反対称律) \\ # 性質 \it{1, 2, 3} を満たす二項関係を同値関係と呼び、性質 \it{1, 3, 4} を満たす二項関係を順序関係と呼ぶ。 \\ # + [markdown] id="AhnMk_wTnkZU" # # 集合の内包表記 set comprehension # + [markdown] id="xfp5HeQy57fH" # 参考 集合で習う集合の内包表記は数式で次の様に書く。 # # $ # S= \{2x \mid x \in \mathbb{N}, \ x \leq 10 \} # $ # # プログラミングでは list comprehension と言うと思うが。 # # + id="FPRji7FKkpWg" colab={"base_uri": "https://localhost:8080/", "height": 38} outputId="ab706d6d-8b04-4c67-a653-e47d36ccc43a" # 参考 集合で習う集合の内包表記は数式で次の様に書く。 # %%latex S= \{2x \mid x \in \mathbb{N}, \ x \leq 10 \} # + [markdown] id="4shZRzUt7YUh" # # 練習問題 # + [markdown] id="OjewVaDU7a0u" # --- # 2 次方程式 # $$ ax^{2}+bx+c=0 $$ # の解は # $$ x = \frac{-b\pm\sqrt{b^{2}-4ac}}{2a} \tag{1}$$ # である。 # + [markdown] id="x9LkU-cj76aw" # --- # 総和記号 シグマ はこんな感じ。 # # $$\sum_{k=1}^{n} a_{k} = a_{1} + a_{2} + \dots + a_{n}$$ # + [markdown] id="iyzcwrXD8SUc" # --- # ガウス積分 # # $$ # \int_{-\infty}^{\infty} e^{-x^{2}} \, dx = \sqrt{\pi} # $$ # + [markdown] id="Naejv7f18izy" # --- # 関数 $f(x)$ の導関数は # $$ # f’(x) = \lim_{\varDelta x \to 0} \frac{ f(x+\varDelta x) - f(x) }{\varDelta x}$$ # である。 # + [markdown] id="zxOq4jQm80yi" # --- # 三角関数の積分 # # $$\int \tan\theta \, d\theta = \int \frac{\sin\theta}{\cos\theta} \, d\theta= -\log |\cos\theta| + C$$ # + [markdown] id="CZnsrL8d9JfQ" # --- # 式の変形 # $$ # \begin{align}\cos 2\theta &= \cos^{2} \theta - \sin^{2} \theta \\&= 2\cos^{2} \theta - 1 \\&= 1 - 2\sin^{2} \theta\end{align} # $$ # + [markdown] id="rQtOs73i9bor" # --- # 片括弧、大括弧、大波括弧、cases # # $$ # |x| = # \begin{cases} # fx & x \ge 0のとき\\ # -x & x \lt 0のとき # \end{cases}\ # $$ # + [markdown] id="wxpJ6Uc5-F_0" # --- # 行列 $n \times n$ 行列 # # $$A =\begin{pmatrix} # a_{11} & a_{12} & \ldots & a_{1n} \\ # a_{21} & a_{22} & \ldots & a_{2n} \\ # \vdots & \vdots & \ddots & \vdots \\ # a_{n1} & a_{n2} & \ldots & a_{nn} # \end{pmatrix} $$ # # が逆行列 $A^{-1}$ をもつための必要十分条件は、$ \det A \neq 0 $ である。 # + [markdown] id="S93wTZ1M-xs5" # --- # 行列を囲む括弧のいろいろ # # 丸括弧、角括弧、波括弧、縦棒、 二重の縦棒括弧なし # # $$ # \begin{pmatrix} # a & b \\ # c & d # \end{pmatrix},\; # \begin{bmatrix} # a & b \\ # c & d # \end{bmatrix},\; # \begin{Bmatrix} # a & b \\ # c & d # \end{Bmatrix},\; # \begin{vmatrix} # a & b \\ # c & d # \end{vmatrix},\; # \begin{Vmatrix} # a & b \\ # c & d # \end{Vmatrix},\; # \begin{matrix} # a & b \\ # c & d # \end{matrix} # $$ # # # # # + [markdown] id="-tyh02f43Ae7" # --- # $$ # + [markdown] id="8v77Lobj24tk" # # マクロの定義 # $$ # \def\RR{{\mathbb R}} # \def\bol#1{{\bf #1}} # \RR \\ # \bol {crazy\;rich\;tycoon}\\ # \def \x {\times} # 3 \x 3 = 9\\ # \def\dd#1#2{\frac{\partial #1}{\partial #2}} # \dd{x}{y} # $$ # + colab={"base_uri": "https://localhost:8080/", "height": 101} id="O08Otvp-4xTe" outputId="a39f4f92-0bd5-4f33-e955-b57f02ebf1c0" language="latex" # \def\RR{{\mathbb R}} # \def\bol#1{{\bf #1}} # \RR \\ # \bol {crazy\;rich\;tycoon}\\ # \def \x {\times} # 3 \x 3 = 9\\ # \def\dd#1#2{\frac{\partial #1}{\partial #2}} # \dd{x}{y} # + [markdown] id="i1JHh7jU9DWs" # --- # ベクトル場 $\boldsymbol B (x,y,z)$ が # # $$ # \def \x {\times} # \boldsymbol B = \nabla \x\boldsymbol A \tag{1.1} # $$ # # という形に書ける時、その発散 # # $$ # \def\dd#1#2{\frac{\partial #1}{\partial #2}} # \nabla \cdot\boldsymbol{B} = \dd{B_{x}}{x} + \dd{B_{y}}{y} + \dd{B_{z}}{z} \tag{1.2} # $$ # # は $0$ になる。 式 (1.1) に現れる $\boldsymbol{A,B}$ をベクトルポテンシャルと言う。 # + [markdown] id="eTuJPZyhBovE" # # 演習問題 # + [markdown] id="_qZAgjXWBsIQ" # --- # オイラーの公式 # # $$ # e^{i\theta}=\cos \theta + i \sin \theta # $$ # + [markdown] id="LGnsooTrD4ce" # --- # テイラー展開 # # $$ # f(x) = \sum^\infty_{n=0}\frac{f^{(n)}(a)}{n !} (x-a)^n # $$ # + [markdown] id="A213i1e-ETtW" # --- # 正規分布 # # $$ # f(x)=\frac 1 {\sqrt{2\pi \sigma^2}}\exp\left (-\frac{(x-\mu)^2}{2\sigma^2}\right) # $$ # + [markdown] id="P8X97epME1KG" # --- # ニュートンの運動方程式 # # $$ # m \frac{d^2 \overrightarrow r}{d t^2}=\overrightarrow F # $$ # + [markdown] id="nRGuh4uhFk26" # --- # ラグランジュの運動方程式 # # $$ # \frac d {dt}\left(\frac{\partial \mathcal L}{\partial \dot q} \right) - \frac{\partial \mathcal L}{\partial q} = 0 # $$ # + [markdown] id="ZqHc-lbcG6TN" # --- # フーリエ変換 # # $$ # \hat f (\xi) = \int_{\mathbb R ^n} f(x) e ^{-2 \pi i x \cdot \xi} dx # $$ # # + [markdown] id="eWP7JAJTN3NS" # --- # コーシーの積分方程式 # # $$ # f(\alpha)=\frac 1 {2\pi i} \oint_C \frac{f(z)}{z - \alpha} d z # $$ # # + [markdown] id="JmCqkH7bPyoP" # --- # ガウスの定理 # # $$ # \iiint_V \nabla \cdot\boldsymbol A \; dV = \iint_{\partial V}\boldsymbol A \cdot\boldsymbol n \; dS # $$ # + [markdown] id="ZcC6f0L8QCdI" # --- # シュレーディンガー方程式 # # $$ # i \hbar \frac \partial {\partial t} \psi (r,t) = \left (-\frac{\hbar}{2m}\nabla^2+V(r,t) \right)\psi(r,t) # $$ # # # + [markdown] id="OnAjq5rtSoeJ" # --- # メモ $\quad$ 上記では `\left (, \right )` を使ったが、 # * \bigl,\Bigl,\biggl,\Biggl # * \bigr,\Bigr,\biggr,\Biggr # * \bigm,\Bigm,\biggm,\Biggm \\ # という体系もある。 # # + [markdown] id="jwDYJZcxSuNg" # --- # 熱化学方程式 # # $$ # \mathrm{H_2(g) + {1 \over 2} O_2(g) \rightarrow H_2O(l)} \quad \varDelta H^\circ = -286\mathrm{kJ} # $$ # # + [markdown] id="zpfjUgFEUg3W" # 集合記号・内包表記 list comprehension # # $$ # A \cap B = \{x \;|\; x \in A \land x \in B\} # $$ # # # + [markdown] id="vsFTu0dCXMIw" # --- # メモ # * \\{ , \\}: $\{$, $\}$ 波括弧だけでは表示されない # * \cap, \cup, \wedge, \land, \lor, \vee:$\cap, \cup, \wedge, \land, \lor, \vee$ # * \in, \ni, \notin, \subset, \supset:$\in, \ni, \notin, \subset, \supset$ # * \emptyset, \forall, \exists, \neg:$\emptyset, \forall, \exists, \neg$ # + [markdown] id="ziufWRbrXPXM" # --- # 二項係数 # # $$ # {}_n C_r = \binom n r = \frac{n!}{r! (n-r)!} # $$ # + [markdown] id="0976DB5hXkPU" # --- # マクスウェル方程式 # # $$ # \begin{array}{ll} # \displaystyle # \nabla \cdot E = \frac \rho {\varepsilon_0}, # &\qquad # \displaystyle # \nabla \cdot E = - \frac {\partial B}{\partial t}\\ # \nabla \cdot B = 0, # &\qquad # \nabla \cdot B = \mu_0 i + \displaystyle \frac 1 {c^2} \frac {\partial E}{\partial t} # \end{array} # $$
learnlatex.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <img src="../images/aeropython_logo.png" alt="AeroPython" style="width: 300px;"/> # # Introducción a SymPy # ![](http://sympy.org/static/images/logo.png) # # __SymPy es una biblioteca de Python para matemática simbólica__. Apunta a convertirse en un sistema de algebra computacional (__CAS__) con todas sus prestaciones manteniendo el código tan simple como sea posible para manterlo comprensible y fácilmente extensible. SymPy está __escrito totalmente en Python y no requiere bibliotecas adicionales__. _Este proyecto comenzó en 2005, fue lanzado al público en 2007 y a él han contribuido durante estos años cientos de personas._ # # _ Otros CAS conocidos son Mathematica y Maple, sin embargo ambos son software privativo y de pago. [Aquí](https://github.com/sympy/sympy/wiki/SymPy-vs.-Maple) puedes encontrar una comparativa de SymPy con Maple. _ # # Hoy veremos cómo: # # * Crear símbolos y expresiones. # * Manipular expresiones (simplificación, expansión...) # * Calcular derivadas e integrales. # * Límites y desarrollos en serie. # * Resolución de ecuaciones. # * Resolción de EDOs. # * Matrices # # Sin embargo, SymPy no acaba aquí ni mucho menos... # ## Documentación & SymPy Live Shell from IPython.display import HTML HTML('<iframe src="http://docs.sympy.org/latest/index.html" width="700" height="400"></iframe>') # ## SymPy Gamma HTML('<iframe src="http://www.sympygamma.com/input/?i=integrate%281+%2F+%281+%2B+x^2%29%29" width="700" height="400"></iframe>') # ## Creación de símbolos # Lo primero, como siempre, es importar aquello que vayamos a necesitar. La manera usual de hacerlo con SymPy es importar la función `init_session`: # ``` # from sympy import init_session # init_session(use_latex=True)``` # # Esta función ya se encarga de importar todas las funciones básicas y preparar las salidas gráficas. Sin embargo, en este momento, esta función se encuentra en mantenimiento para su uso dentro de los notebooks por lo que activaremos la salida gráfica e importaremos las funciones de la manera usual. Puedes consultar el estado de la corrección en: https://github.com/sympy/sympy/pull/13300 y https://github.com/sympy/sympy/issues/13319 . # El comando `init_session` llevaría a cabo algunas acciones por nostros: # # * Gracias a `use_latex=True` obtenemos la salida en $\LaTeX$. # * __Crea una serie de variables__ para que podamos ponernos a trabajar en el momento. # # Estas capacidades volverán a estar disponibles cuando el problema se corrija. from sympy import init_printing init_printing() # aeropython: preserve from sympy import (symbols, pi, I, E, cos, sin, exp, tan, simplify, expand, factor, collect, apart, cancel, expand_trig, diff, Derivative, Function, integrate, limit, series, Eq, solve, dsolve, Matrix, N) # <div class="alert warning-info"><strong>Nota:</strong> # En Python, no se declaran las variables, sin embargo, no puedes usar una hasta que no le hayas asignado un valor. Si ahora intentamos crear una variable `a` que sea `a = 2 * b`, veamos qué ocurre: # </div> # Intentamos usar un símbolo que no hemos creado a = 2 * b # Como en `b` no había sido creada, Python no sabe qué es `b`. # # Esto mismo nos ocurre con los símbolos de SymPy. __Antes de usar una variable, debo decir que es un símbolo y asignárselo:__ # Creamos el símbolo a a = symbols('a') a # Número pi (a + pi) ** 2 # Unidad imaginaria a + 2 * I # Número e E # Vemos qué tipo de variable es a type(a) # Ahora ya podría crear `b = 2 * a`: b = 2 * a b type(b) # ¿Qué está ocurriendo? Python detecta que a es una variable de tipo `Symbol` y al multiplicarla por `2` devuelve una variable de Sympy. # # Como Python permite que el tipo de una variable cambie, __si ahora le asigno a `a` un valor float deja de ser un símbolo.__ a = 2.26492 a type(a) # --- # __Las conclusiones son:__ # # * __Si quiero usar una variable como símbolo debo crearla previamente.__ # * Las operaciones con símbolos devuelven símbolos. # * Si una varibale que almacenaba un símbolo recibe otra asignación, cambia de tipo. # # --- # __Las variables de tipo `Symbol` actúan como contenedores en los que no sabemos qué hay (un real, un complejo, una lista...)__. Hay que tener en cuenta que: __una cosa es el nombre de la variable y otra el símbolo con el que se representa__. #creación de símbolos coef_traccion = symbols('c_T') coef_traccion # Incluso puedo hacer cosas raras como: # Diferencia entre variable y símbolo a = symbols('b') a # Además, se pueden crear varos símbolos a la vez: x, y, z, t = symbols('x y z t') # y símbolos griegos: w = symbols('omega') W = symbols('Omega') w, W # ![](../images/simplification_sympy.png) # _Fuente: Documentación oficial de SymPy_ # __Por defecto, SymPy entiende que los símbolos son números complejos__. Esto puede producir resultados inesperados ante determinadas operaciones como, por ejemplo, lo logaritmos. __Podemos indicar que la variable es real, entera... en el momento de la creación__: # Creamos símbolos reales x, y, z, t = symbols('x y z t', real=True) # Podemos ver las asunciones de un símbolo x.assumptions0 # ## Expresiones # Comencemos por crear una expresión como: $\cos(x)^2+\sin(x)^2$ expr = cos(x)**2 + sin(x)**2 expr # ### `simplify()` # Podemos pedirle que simplifique la expresión anterior: simplify(expr) # En este caso parece estar claro lo que quiere decir más simple, pero como en cualquier _CAS_ el comando `simplify` puede no devolvernos la expresión que nosotros queremos. Cuando esto ocurra necesitaremos usar otras instrucciones. # ### `.subs()` # En algunas ocasiones necesitaremos sustituir una variable por otra, por otra expresión o por un valor. expr # Sustituimos x por y ** 2 expr.subs(x, y**2) # ¡Pero la expresión no cambia! expr # Para que cambie expr = expr.subs(x, y**2) expr # Cambia el `sin(x)` por `exp(x)` expr.subs(sin(x), exp(x)) # Particulariza la expresión $sin(x) + 3 x $ en $x = \pi$ (sin(x) + 3 * x).subs(x, pi) # __Aunque si lo que queremos es obtener el valor numérico lo mejor es `.evalf()`__ (sin(x) + 3 * x).subs(x, pi).evalf(25) #ver pi con 25 decimales pi.evalf(25) #el mismo resultado se obtiene ocn la función N() N(pi,25) # # Simplificación # SymPy ofrece numerosas funciones para __simplificar y manipular expresiones__. Entre otras, destacan: # # * `expand()` # * `factor()` # * `collect()` # * `apart()` # * `cancel()` # # Puedes consultar en la documentación de SymPy lo que hace cada una y algunos ejemplos. __Existen también funciones específicas de simplificación para funciones trigonométricas, potencias y logaritmos.__ Abre [esta documentación](http://docs.sympy.org/latest/tutorial/simplification.html) si lo necesitas. # ##### ¡Te toca! # Pasaremos rápidamente por esta parte, para hacer cosas "más interesantes". Te proponemos algunos ejemplos para que te familiarices con el manejor de expresiones: # __Crea las expresiones de la izquierda y averigua qué función te hace obtener la de la derecha:__ # # expresión 1| expresión 2 # :------:|:------: # $\left(x^{3} + 3 y + 2\right)^{2}$ | $x^{6} + 6 x^{3} y + 4 x^{3} + 9 y^{2} + 12 y + 4$ # $\frac{\left(3 x^{2} - 2 x + 1\right)}{\left(x - 1\right)^{2}} $ | $3 + \frac{4}{x - 1} + \frac{2}{\left(x - 1\right)^{2}}$ # $x^{3} + 9 x^{2} + 27 x + 27$ | $\left(x + 3\right)^{3}$ # $\sin(x+2y)$ | $\left(2 \cos^{2}{\left (y \right )} - 1\right) \sin{\left (x \right )} + 2 \sin{\left (y \right )} \cos{\left (x \right )} \cos{\left (y \right )}$ # #1 expr1 = (x ** 3 + 3 * y + 2) ** 2 expr1 expr1_exp = expr1.expand() expr1_exp #2 expr2 = (3 * x ** 2 - 2 * x + 1) / (x - 1) ** 2 expr2 expr2.apart() #3 expr3 = x ** 3 + 9 * x ** 2 + 27 * x + 27 expr3 expr3.factor() #4 expr4 = sin(x + 2 * y) expr4 expand(expr4) expand_trig(expr4) expand(expr4, trig=True) # # Derivadas e integrales # Puedes derivar una expresion usando el método `.diff()` y la función `dif()` # + #creamos una expresión expr = cos(x) #obtenemos la derivada primera con funcion diff(expr, x) # - #utilizando método expr.diff(x) # __¿derivada tercera?__ expr.diff(x, x, x) expr.diff(x, 3) # __¿varias variables?__ expr_xy = y ** 3 * sin(x) ** 2 + x ** 2 * cos(y) expr_xy diff(expr_xy, x, 2, y, 2) # __Queremos que la deje indicada__, usamos `Derivative()` Derivative(expr_xy, x, 2, y) # __¿Será capaz SymPy de aplicar la regla de la cadena?__ # Creamos una función F F = Function('F') F(x) # Creamos una función G G = Function('G') G(x) # $$\frac{d}{d x} F{\left (G(x) \right )} $$ # Derivamos la función compuesta F(G(x)) F(G(x)).diff(x) # En un caso en el que conocemos las funciones: # definimos una f f = 2 * y * exp(x) f # definimos una g(f) g = f **2 * cos(x) + f g #la derivamos diff(g,x) # ##### Te toca integrar # __Si te digo que se integra usando el método `.integrate()` o la función `integrate()`__. ¿Te atreves a integrar estas casi inmediatas...?: # # $$\int{\cos(x)^2}dx$$ # $$\int{\frac{dx}{\sin(x)}}$$ # $$\int{\frac{dx}{(x^2+a^2)^2}}$$ # # int1 = cos(x) ** 2 integrate(int1) int2 = 1 / sin(x) integrate(int2) # + x, a = symbols('x a', real=True) int3 = 1 / (x**2 + a**2)**2 integrate(int3, x) # - # # Límites # Calculemos este límite sacado del libro _Cálculo: definiciones, teoremas y resultados_, de <NAME>: # # $$\lim_{x \to 0} \left(\frac{x}{\tan{\left (x \right )}}\right)^{\frac{1}{x^{2}}}$$ # # Primero creamos la expresión: x = symbols('x', real=True) expr = (x / tan(x)) ** (1 / x**2) expr # Obtenemos el límite con la función `limit()` y si queremos dejarlo indicado, podemos usar `Limit()`: limit(expr, x, 0) # # Series # Los desarrollos en serie se pueden llevar a cabo con el método `.series()` o la función `series()` #creamos la expresión expr = exp(x) expr #la desarrollamos en serie series(expr) # Se puede especificar el número de términos pasándole un argumento `n=...`. El número que le pasemos será el primer término que desprecie. # Indicando el número de términos series(expr, n=10) # Si nos molesta el $\mathcal{O}(x^{10})$ lo podemos quitar con `removeO()`: series(expr, n=10).removeO() series(sin(x), n=8, x0=pi/3).removeO().subs(x, x-pi/3) # --- # ## Resolución de ecuaciones # Como se ha mencionado anteriormente las ecuaciones no se pueden crear con el `=` #creamos la ecuación ecuacion = Eq(x ** 2 - x, 3) ecuacion # También la podemos crear como Eq(x ** 2 - x -3) #la resolvemos solve(ecuacion) # Pero la gracia es resolver con símbolos, ¿no? # $$a e^{\frac{x}{t}} = C$$ # Creamos los símbolos y la ecuación a, x, t, C = symbols('a, x, t, C', real=True) ecuacion = Eq(a * exp(x/t), C) ecuacion # La resolvemos solve(ecuacion ,x) # Si consultamos la ayuda, vemos que las posibilidades y el número de parámetros son muchos, no vamos a entrar ahora en ellos, pero ¿se ve la potencia? # ## Ecuaciones diferenciales # Tratemos de resolver, por ejemplo: # # $$y{\left (x \right )} + \frac{d}{d x} y{\left (x \right )} + \frac{d^{2}}{d x^{2}} y{\left (x \right )} = \cos{\left (x \right )}$$ x = symbols('x') f = Function('y') ecuacion_dif = Eq(y(x).diff(x,2) + y(x).diff(x) + y(x), cos(x)) ecuacion_dif #resolvemos dsolve(ecuacion_dif, f(x)) # # Matrices #creamos una matriz llena de símbolos a, b, c, d = symbols('a b c d') A = Matrix([ [a, b], [c, d] ]) A #sacamos autovalores A.eigenvals() #inversa A.inv() #elevamos al cuadrado la matriz A ** 2 # --- # # _ Esto ha sido un rápido recorrido por algunas de las posibilidades que ofrece SymPy . El cálculo simbólico es un terreno díficil y este joven paquete avanza a pasos agigantados gracias a un grupo de desarrolladores siempre dispuestos a mejorar y escuchar sugerencias. Sus posibilidades no acaban aquí. En la siguiente clase presentaremos el paquete `mechanics`, pero además cuenta con herramientas para geometría, mecánica cuántica, teoría de números, combinatoria... Puedes echar un ojo [aquí](http://docs.sympy.org/latest/modules/index.html). _ # Si te ha gustado esta clase: # # <a href="https://twitter.com/share" class="twitter-share-button" data-url="https://github.com/AeroPython/Curso_AeroPython" data-text="Aprendiendo Python con" data-via="pybonacci" data-size="large" data-hashtags="AeroPython">Tweet</a> # <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> # # --- # #### <h4 align="right">¡Síguenos en Twitter! # ###### <a href="https://twitter.com/Pybonacci" class="twitter-follow-button" data-show-count="false">Follow @Pybonacci</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <a href="https://twitter.com/Alex__S12" class="twitter-follow-button" data-show-count="false" align="right";>Follow @Alex__S12</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <a href="https://twitter.com/newlawrence" class="twitter-follow-button" data-show-count="false" align="right";>Follow @newlawrence</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> # ##### <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es"><img alt="Licencia Creative Commons" style="border-width:0" src="http://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Curso AeroPython</span> por <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName"><NAME> y <NAME></span> se distribuye bajo una <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es">Licencia Creative Commons Atribución 4.0 Internacional</a>. # ##### <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/MemberProfile" data-id="http://es.linkedin.com/in/juanluiscanor" data-format="inline" data-related="false"></script> <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/MemberProfile" data-id="http://es.linkedin.com/in/alejandrosaezm" data-format="inline" data-related="false"></script> # --- # _Las siguientes celdas contienen configuración del Notebook_ # # _Para visualizar y utlizar los enlaces a Twitter el notebook debe ejecutarse como [seguro](http://ipython.org/ipython-doc/dev/notebook/security.html)_ # # File > Trusted Notebook # + language="html" # <a href="https://twitter.com/Pybonacci" class="twitter-follow-button" data-show-count="false">Follow @Pybonacci</a> # <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> # - # Esta celda da el estilo al notebook from IPython.core.display import HTML css_file = '../styles/aeropython.css' HTML(open(css_file, "r").read())
notebooks_completos/040-SymPy-Intro.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + from src.drugexr.models.generator import Generator from src.drugexr.config.constants import PROC_DATA_PATH from src.drugexr.data_structs.vocabulary import Vocabulary from torch.utils.data import DataLoader, Dataset import torch import pathlib import pandas as pd import pytorch_lightning as pl # - import torch.multiprocessing as mp mp.set_start_method('spawn') voc = Vocabulary(vocabulary_path=pathlib.Path(PROC_DATA_PATH / "chembl_voc.txt")) BATCH_SIZE = 32 chembl = pd.read_table(PROC_DATA_PATH / "chembl_corpus_DEV_1000.txt").Token chembl = torch.LongTensor(voc.encode([seq.split(" ") for seq in chembl])).to('cuda') chembl = DataLoader(chembl, batch_size=BATCH_SIZE, shuffle=True, drop_last=True, num_workers=16) # + import os os.environ["CUDA_LAUNCH_BLOCKING"] = "1" # init model g = Generator(vocabulary=voc, embed_size=32, hidden_size=64) # Initialize a trainer trainer = pl.Trainer(gpus=1, max_epochs=1, progress_bar_refresh_rate=20, log_every_n_steps=1) # Train the model ⚡ trainer.fit(g, chembl) # -
analysis/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os import numpy as np import pandas as pd current_dir = os.getcwd() print(current_dir) csv_dir = os.path.join(current_dir,'titanic.csv') print(csv_dir) df = pd.read_csv(csv_dir) print(df.head()) dataset = df.copy() print('Summary Description\n',dataset.describe()) print(dataset.dtypes) target_ = dataset['Survived'] print(target_.head()) dataset = dataset.drop(['Survived'] , axis=1) print('\n\n\nDataset without target\n',dataset.head()) features = dataset.copy() #converting sex column to label encoder label_encoder = {'male':0 , 'female':1} dataset['Sex'].map(label_encoder) print(dataset) #remove name column dataset = dataset.drop(['Name'] , axis=1) print(dataset.head()) dataset.columns columns_renamed = {'Pclass' : 'passengerClass' , 'Sex' : 'Gender' , 'Siblings/Spouses Aboard':'Siblings', 'Parents/Children Aboard':'Parents', 'Fare' : 'Price'} dataset.rename(columns=columns_renamed , inplace=True) print(dataset.head()) #we will take some samples out of titanic data print(len(dataset)) size = int(len(dataset)*0.40 ) taget_samples = target_[:size] features = dataset[:size] print(features) print(taget_samples) def train(c,t): for i, val in enumerate(t): if val == 1: specific_hypothesis = c[i].copy() break for i, val in enumerate(c): if t[i] == 1: for x in range(len(specific_hypothesis)): if val[x] != specific_hypothesis[x]: specific_hypothesis[x] = '?' else: pass return specific_hypothesis features_copy = features.copy() features_arr = np.array(features_copy) print(features_arr ,end="\n\n\n\n\n") target_arr = np.array(taget_samples) print(target_arr) train(features_arr,target_arr) len(features_arr) low_range =2 high_range = 6 train(features_arr[low_range:high_range] , target_arr[low_range:high_range]) # #### size = [1,2,3,4,5,6,7,8,9,10] # for i in size : # print(i,train(features_arr[:i],target_arr[:i]))
0. Tom Mitchell Exercise Solutions/find_s.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + deletable=true editable=true # %matplotlib notebook # %matplotlib inline import math import matplotlib.pyplot as plt import numpy as np # + [markdown] deletable=true editable=true # # Modern Physics # # - State the special theory of relativity # - Differentiate inertial and non-inertial reference frames # - Compare classical and relativistic physics approaches # - Calculate relativistic masses # - Calculate time dilation # - Calculate length contraction # - Describe the photoelectric effect # - Calculate Compton scattering angles and kinetic energies # - Calculate de Broglie wavelengths # - Relate energy and wavelength for photons # - Understand wave-particle duality # - Relate wave-particle duality and particle energy/wavelength # # + [markdown] deletable=true editable=true # ## Special Theory of Relativity # # Classical physics relies on Newton's laws to descibe motion. Newton's second law says: # # # \begin{align} # F &=\frac{d\vec{p}}{dt} \\ # &= \frac{dm\vec{v}}{dt} # \end{align} # where # \begin{align} # \vec{F} &= \mbox{the force applied to the object}\\ # \vec{p} &= \mbox{the momentum of the object}\\ # \vec{v} &= \mbox{velocity of the object}\\ # m &= \mbox{mass of the object}\\ # \end{align} # # In newtonian physics, the mass of the object ($m$) is constant. # # # ### Relativistic Mass # # In 1905 Einstein showed that mass varies with an object's speed. # \begin{align} # m = \frac{m_o}{\sqrt{1-\frac{v^2}{c^2}}} # \end{align} # where # \begin{align} # m_o &= \mbox{rest mass of the object}\\ # c &= \mbox{speed of light}\\ # &= 3\times10^{8}\frac{m}{s} # \end{align} # # #### Exercise: Think, Pair, Share # # If one plotted mass as a function of velocity, what could one expect the plot to look like? # + [markdown] deletable=true editable=true # ## Principle of Relativity # # Lots of things are relative. # When we talk in physics about relativity, we intend to refer to the _relative_ features of coordinate systems. # # Imagine two inertial coordinate systems. $S$ is stationary, while $S'$ is moving away along the x axis with velocity $\vec{v} = v\hat{x}$. The coordinate transformation is, then. # # \begin{align} # x' & = x - vt\\ # y' &= y\\ # z' &= z\\ # t' &= t # \end{align} # + [markdown] deletable=true editable=true # Substituting these transformations into Newton's laws does not impact their validity. If we consider a force $F_x$ acting on mass $m$, then the 2nd law in the moving system is: # # # # \begin{align} # F_x & = m\frac{d^2x'}{dt'^2}\\ # \end{align} # # If we transform it to the stationary system, with constant $v$: # # # \begin{align} # F_x &= m\frac{d^2x'}{dt'^2}\\ # &= m\frac{d^2(x-vt)}{d(t)^2}\\ # &= m\frac{d^2x}{dt^2}\\ # \end{align} # # # However, Maxwell's equations don't survive the transformation above. Lorentz observed (1904) that a different transformation could preserve Maxwell's equations. We call this the Lorentz transformation: # # \begin{align} # x' &= \frac{x - vt}{\sqrt{1-\frac{v^2}{c^2}}}\\ # y' &= y\\ # z' &= z\\ # t' &= \frac{t-\frac{vx}{c^2}}{\sqrt{1-\frac{v^2}{c^2}}}\\ # \end{align} # # # In the Lorentz transformation above, **space and time depend on one another.** # + deletable=true editable=true def x_ltz(x, v, t): c = 3.0e8 num = x - v*t denom = math.sqrt(1-(v/c)**2) return num/denom def t_ltz(x, v, t): c = 3.0e8 num = t - v*x/c**2 denom = math.sqrt(1-(v/c)**2) return num/denom x = 1 vel = 3.0e2 time = np.arange(0, 300, 10) to_plot = np.arange(0.,30.) for i in range(0, 30): to_plot[i] = x_ltz(x, vel, time[i]) plt.plot(time, to_plot, label="x_ltz") plt.ylabel("Lorentz transformed x ($m$)") plt.xlabel("time $(s)$") plt.legend(loc=2) # + [markdown] deletable=true editable=true # ### Results of the Special Theory of Relativity # # What Einstein showed in 1905 was that **all physics in inertial coordinate systems remains unchanged under the Lorentz transformation.** To acheive this, however, one must correct Newton's laws of motion to allow them, too, to remain invariant under this transformation. # # Einstein based this on two _postulates_: # # - The laws of motion should have the same form in all coordinate systems moving at constant velocities to one another. # - The speed of light in free space, $c$, is the same for all observers and is independent of the relative velocity between the source and observer. # # #### Exercise: Think-pair-share # # If the first postulate, velocity is kept constant between coordinate systems. What is the name for such coordinate systems? # # If the coordinate systems were accelerating with respect to each other, what quality is lost? # + [markdown] deletable=true editable=true # ### Result: Relativistic Mass # # The laws of motion are correct, as stated by Newton, if the mass of the object is a function of the object's speed. # # In 1905 Einstein showed that mass varies with an object's speed. # # \begin{align} # m = \frac{m_o}{\sqrt{1-\frac{v^2}{c^2}}} # \end{align} # where # \begin{align} # m_o &= \mbox{rest mass of the object}\\ # c &= \mbox{speed of light}\\ # &= 3\times10^{8}\frac{m}{s} # \end{align} # # #### Exercise: Think, Pair, Share # # If one plotted mass as a function of velocity, what could one expect the plot to look like? # + deletable=true editable=true def m_rel(m_o, v): """Returns the relativistic mass of an object Parameters ---------- m_o : double rest mass of the object v : double velocity of the object """ c = 3.0e8 m = m_o/math.sqrt((1 - pow(v,2)/pow(c,2))) return m # + deletable=true editable=true # Plot it vel = np.arange(0, 3.0e8, 1.0e7) to_plot = np.arange(0.,30.) for i in range(0, 30): to_plot[i] = m_rel(1, vel[i]) plt.plot(vel, to_plot, label="relativistic mass") plt.ylabel("relativistic mass (normalized by $m_o$)") plt.xlabel("velocity $(m/s)$") plt.legend(loc=2) # + [markdown] deletable=true editable=true # ### Result: Length Contraction # # The length of a moving object, in the direction of its motion, appears smaller to an observer at rest: # # \begin{align} # L&=L_o \sqrt{1-\frac{v^2}{c^2}} # \end{align} # # where # # # \begin{align} # L_o &= \mbox{proper length of the object at rest} # \end{align} # + deletable=true editable=true def l_rel(l_o, v): """Returns the relativistic length of an object Parameters ---------- l_o : double rest length of the object v : double velocity of the object """ c = 3.0e8 length = l_o*math.sqrt((1 - pow(v,2)/pow(c,2))) return length # Plot it vel = np.arange(0, 3.0e8, 1.0e7) to_plot = np.arange(0.,30.) for i in range(0, 30): to_plot[i] = l_rel(1, vel[i]) plt.plot(vel, to_plot, label="relativistic length") plt.ylabel("relativistic length (normalized by $L_o$)") plt.xlabel("velocity $(m/s)$") plt.legend(loc=2) # + [markdown] deletable=true editable=true # #### Exercise: Think-Pair-Share # # When we talk about length in this way, in what direction are we measuring it? # + [markdown] deletable=true editable=true # ### Result: Time Dilation # # The passage of time appears slow in a system moving with respect to a stationary observer. # # # \begin{align} # t &= \frac{t_o}{\sqrt{1-\frac{v^2}{c^2}}} # \end{align} # # where # # # \begin{align} # t &= \mbox{time required for some physical phenomenon in the moving system}\\ # t_o &= \mbox{time required for some physical phenomenon in the stationary system} # \end{align} # + deletable=true editable=true def t_rel(t_o, v): """Returns the time required for some physical phenomenon in the moving system Parameters ---------- t_o : double time required for some physical phenomenon in the stationary system v : double velocity of the moving reference frame """ c = 3.0e8 time = t_o/math.sqrt((1 - pow(v,2)/pow(c,2))) return time # Plot it vel = np.arange(0, 3.0e8, 1.0e7) to_plot = np.arange(0.,30.) for i in range(0, 30): to_plot[i] = t_rel(1, vel[i]) plt.plot(vel, to_plot, label="relativistic time") plt.ylabel("relativistic time (normalized by $t_o$)") plt.xlabel("velocity $(m/s)$") plt.legend(loc=2) # + [markdown] deletable=true editable=true # ### Exercise: Consider twins # # Now, imagine two identical twins, one of whom makes a journey into space in a high-speed rocket and returns home. # # Which is older, at the end of the event? # # ![a-k-huff.jpg](a-k-huff.jpg) # + [markdown] deletable=true editable=true # ### Result: Equivalence of mass and energy # # The most famous result is that there is an equivalence between mass and energy: # # \begin{align} # E_{rest} = m c^2 # \end{align} # # For particles with mass (such as electrons, protons, neutrons, alpha particles, etc.), the rest mass energy is # # \begin{align} # E_{rest} = m_o c^2 # \end{align} # # where m_o is the mass that is given in reference tables. # # # # ### Total Energy # # The total energy ($E_{total}$) is the sum of the rest and kinetic energies. Therefore, for relativistic particles, the total energy is: # # \begin{align} # E_{total} &= E_{rest} + E_{kinetic}\\ # &= mc^2\\ # &=\frac{m_oc^2}{\sqrt{1-\frac{v^2}{c^2}}}\\ # \end{align} # # # The above can be used for any particle, though for velocities much slower than the speed of light ($<0.1c$), one can use the simpler classical mechanics expression: # # \begin{align} # E_{total} &= E_{rest} + E_{kinetic}\\ # &=m_o c^2 + \frac{1}{2}m_ov^2\\ # \end{align} # # ### Exercise: Think-pair-share # Why do photons, such as gamma and X rays, have no rest mass energy ? # # + [markdown] deletable=true editable=true # ## Photon Energy # # The total energy of a photon, moving at the speed of light $(c=\lambda\nu)$ is: # # \begin{align} # E_{total} &= h\nu\\ # &= \frac{hc}{\lambda} # \end{align} # # where # # \begin{align} # h &=\mbox{Planck's constant}\\ # \nu &= \mbox{frequency of the particle}\\ # \lambda &= \mbox{wavelength} # \end{align} # # # + [markdown] deletable=true editable=true # ## Kinetic Energy and Momentum # # The equation for a particle's momentum is identical both classically and relativistically, # # \begin{align} # p=mv. # \end{align} # # Classically, we can describe the kinetic energy, $T$, using the momentum. # # \begin{align} # T &= \frac{mv^2}{2}\\ # &= \frac{p^2}{2m}\\ # \implies p = \sqrt{2mT} # \end{align} # # Relativistically, the relationship between momentum and kinetic energy is, instead: # # \begin{align} # p = \frac{1}{c}\sqrt{T^2 + 2Tm_oc^2}. # \end{align} # + deletable=true editable=true def mom_class(T, m): p = pow(2*m*T, 0.5) return p def mom_rel(T, m_o): c = 3.0e8 p = (1/c)*pow((T**2 + 2*T*m_o*c**2), 0.5) return p # Plot it kinetic = np.arange(0, 3.0e8, 1.0e7) to_plot_rel = np.arange(0.,30.) to_plot_class = np.arange(0, 30.) m = 1 for i in range(0, 30): to_plot_rel[i] = mom_rel(kinetic[i], m) to_plot_class[i] = mom_class(kinetic[i], m) plt.plot(kinetic, to_plot_class, label="classical momentum") plt.plot(kinetic, to_plot_rel, label="relativistic momentum") plt.xlabel("kinetic energy") plt.legend(loc=2) # + deletable=true editable=true to_plot_diff = to_plot_rel - to_plot_class plt.plot(kinetic, to_plot_diff, label="mom_rel - mom_class") plt.ylabel("relativistic momentum correction ($\Delta p $)") plt.xlabel("kinetic energy") plt.legend(loc=2) # + [markdown] deletable=true editable=true # ## The photoelectric effect # # # # - **1887** Hertz showed that when metal surfaces were irradiated with light "electricity" was emitted # - **1898** <NAME> showed these were electrons ("photoelectrons") # # The classical theory explaining this was insufficient to describe the experimental results. Specifically, it failed to explain the following phenomena: # # - For each metal there is a minimum light frequency $\nu$ below which no photoelectrons are emitted # - There is no time lag between the irradiation and emission # - The intensity of the light only impacts the _rate_ of photoelectron emission # - The photoelectron kinetic energy only depends on frequency of light (not intensity) # # - **1905** Einstein, in his big year, suggested a new model. # # <a title="By Wolfmankurd (en:Inkscape) [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Photoelectric_effect.svg"><img width="128" alt="Photoelectric effect" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Photoelectric_effect.svg/128px-Photoelectric_effect.svg.png"></a> # # # He postulated that light is made of _photons_ that have energy: # # \begin{align} # E&=h\nu\\ # &=\mbox{energy of a photon}\\ # \mbox{where }&\\ # h&=\mbox{Plank's constant}\\ # &=6.62\times 10^{-34} [J\cdot s]\\ # \nu&=\mbox{photon frequency} # \end{align} # # Additionally, he suggested that photons act as a whole -- never partially absorbed or emitted by an atom. Thus, the maximum kinetic energy of an electron would be: # # \begin{align} # E&=h\nu-A\\ # &=\mbox{maximum kinetic energy of a photoelectron}\\ # \mbox{where }&\\ # A &= \mbox{"work function"}\\ # &=\mbox{amount of energy required to free the electron from the metal} # \end{align} # + [markdown] deletable=true editable=true # ## Exercise: Photoelectric effect (from Shultis & Faw) # # What is the maximum wavelength of light required to liberate photoelectrons from a metallic surface with a awork function of 2.35ev (energy neeced to free a valence electron)? # # # The maximum wavelength has the minumum frequency. So, find the minimum frequency by assuming no energy is lost to the electron in the form of kinetic energy: # # \begin{align} # \nu_{min} &= \frac{A}{h}\\ # &=\frac{2.35ev}{4.136\times10^{-15}eV}\\ # &= 5.68\times 10^{14} \frac{1}{s}\\ # \implies \lambda_{max} &= \frac{c}{\nu_{min}}\\ # &=\frac{2.998\times10^{8}\frac{m}{s}}{5.68\times 10^{14}\frac{1}{s}}\\ # &=\boxed{5.28\times10^{-7}m} # \end{align} # + [markdown] deletable=true editable=true # ## Compton Scattering # # - **1922** Compton noticed that x-rays scattered from electrons had a change in wavelength $\Delta\lambda = \lambda' - \lambda$ proportional to $(1-\cos{\theta_s})$ # # <a title="JabberWok [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Compton-scattering.svg"><img width="128" alt="Compton-scattering" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Compton-scattering.svg/128px-Compton-scattering.svg.png"></a> # # # # + [markdown] deletable=true editable=true # To explain this, we must treat x-rays as particles with a linear momentum $p=\frac{h}{\lambda}$ and energy $E=h\nu=pc$. # # In an x-ray scattering interaction, both momentum and energy must be conserved. To conserve momentum # # \begin{align} # \vec{p_\lambda} = \vec{p_{\lambda'}}+\vec{p_e} # \end{align} # # ## Exercise: Conservation of Momentum # # Draw a triangle representing the relationship between $\vec{p_\lambda}$,$\vec{p_{\lambda'}}$, and $\vec{p_e}$. Use $\phi_e$ and $\theta_s$ to represent the electron-photon incident angle and the scattering angle. # # + deletable=true editable=true # + [markdown] deletable=true editable=true # From the law of cosines: # # \begin{align} # p_e^2 &= p_\lambda^2 + p_{\lambda'}^2 - 2p_\lambda p_{\lambda'}\cos{\theta_s} # \end{align} # # # From conservation of energy: # \begin{align} # p_\lambda c+m_ec^2 &= p_{\lambda'}c + mc^2\\ # \mbox{where }&\\ # m_e&=\mbox{rest mass of the electron}\\ # m &= \mbox{relativistic electron mass after scattering} # \end{align} # # Combining these gives: # # \begin{align} # \lambda' - \lambda &= \frac{h}{m_ec}(1-\cos{\theta_s})\\ # \implies \frac{1}{E'} - \frac{1}{E} &= \frac{1}{m_ec^2}(1-\cos{\theta_s}) # \end{align} # + [markdown] deletable=true editable=true # ## Exercise: Recoil energy # # What is the recoil kinetic energy of the electron? # # First, we can find the energy of the scattered photon: # # \begin{align} # E' &= \left[\frac{1}{E} + \frac{1}{m_ec^2}(1-\cos{\theta_s})\right]^{-1}\\ # &= \left[\frac{1}{3MeV} + \frac{1}{0.511MeV}\left(1-\cos{\frac{\pi}{4}}\right)\right]^{-1} # &= 1.10MeV # \end{align} # # The energy lost by the scattered photon is balanced by kinetic energy of the electron, $ T_e = E-E' = 3- 1.10 = 1.90MeV.$ # + [markdown] deletable=true editable=true # ## Electromagnetic Radiation : Wave-Particle duality # # ### Photon properties # Photons must always be treated relativistically since they travel at the speed of light $c$. # # #### What's $\nu$? # # \begin{align} # c = \lambda \nu\\ # \implies \nu = \frac{c}{\lambda} # \end{align} # # The momentum of the photon is of course: # # \begin{align} # p&=\frac{E}{c}\\ # &= \frac{h\nu}{c}\\ # &= \frac{h}{\lambda}. # \end{align} # # And its relativistic mass comes from the equivalence of mass and energy: # # \begin{align} # mc^2 &= E = h\nu\\ # \implies m&=\frac{h\nu}{c^2} # \end{align} # # + [markdown] deletable=true editable=true # ## de Broglie wavelength # # - **1924** de Broglie's PhD thesis proposed that electrons have wave-like and particle-like properties, just like photons. # # The dominance of classical vs relativistic behavior is related to the object's energy and mass. The de Broglie wavelength can be used to differentiate that threshold. # # By rearranging the momentum equation stated for photons, a relationship between $\lambda$ and $p$ for the electron can be found: # # \begin{align} # \lambda &={\frac {h}{p}}\\ # &= \frac{h}{\sqrt{T^2 + 2Tm_oc^2}} # \end{align} # # The relationship is now known to hold for all types of matter: **all matter exhibits properties of both particles and waves.** # # # + deletable=true editable=true
modern_physics/00-modern-physics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/"} id="nOzdBDxUdCuw" outputId="5e371914-5199-48f5-87fd-6566e851c7e9" from google.colab import drive drive.mount('/content/drive', force_remount=True) # + [markdown] id="2ZpyR3xc2Ol3" # #Load Libraries: # + id="ki_Fq2_5edIl" import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras import backend as K from tensorflow.keras import activations from tensorflow.keras.layers import * from tensorflow.keras.models import Model, load_model from tensorflow.keras import models from tensorflow.keras import layers import cv2 import numpy as np from tqdm import tqdm import math import os import matplotlib.pyplot as plt # + id="Nc1Kih9dedY_" # + [markdown] id="KMMyHBOZ19x0" # #Load Model: # + id="-_8AF-yhdOZ3" work_dir = "drive/My Drive/Plant_Leaf_MalayaKew_MK_Dataset/Records/" # + id="EUOK04obeQVm" checkpointer_name = "best_weights.MalayaKew.Original.rgb.(256, 256).DataFlow.pad0.TransferLearning3D.DenseNet201.wInit.imagenet.TrainableAfter.allDefault.Dense.1024.1024.2048.actF.elu.opt.Adam.drop.0.5.batch16.Flatten.l2.0.001.run_1.hdf5" # + colab={"base_uri": "https://localhost:8080/"} id="ysU6atkXdOcd" outputId="5883404f-8893-4585-86af-e7f618533ce9" model_loaded = load_model(work_dir+checkpointer_name) print("Loaded "+work_dir+checkpointer_name+".") # + colab={"base_uri": "https://localhost:8080/"} id="tHNURUPWdOfJ" outputId="d34b9c3a-18e9-4a7c-9a1d-cd03a962024c" model_loaded.summary() # + id="ViXRmtqjdOhz" # + [markdown] id="8hbpPCCO4Jx1" # #Model Layers: # + colab={"base_uri": "https://localhost:8080/"} id="wcjgpg8o4JPU" outputId="8862a098-57fc-4123-a9db-6b411428be3f" layer_names = [] # conv4_block48_2_conv, conv3_block12_2_conv for layer in model_loaded.layers: layer_names.append(layer.name) print(layer_names) # + colab={"base_uri": "https://localhost:8080/"} id="3ATZmTBE4lI_" outputId="5ede6481-1529-400e-b72c-ab53666f1e2c" layer_no = -9 print(f"layer_names[{layer_no}] = {layer_names[layer_no]}") # + id="1FwONIc74ZLa" # + [markdown] id="95hQ7EFG1du9" # #By Loading Entire Test at Once: # + id="sZetvikYywKT" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="0c3eb5d2-a6a9-42e9-8031-492483168066" ''' input_path = "drive/My Drive/Plant_Leaf_MalayaKew_MK_Dataset/" filename = "D2_Plant_Leaf_MalayaKew_MK_impl_1_Original_RGB_test_X.pkl.npy" #''' # + id="lLXSPXtMzZcQ" #input_test = np.load(f"{input_path}{filename}", allow_pickle=True) # + colab={"base_uri": "https://localhost:8080/", "height": 36} id="_W5hkjTzzeWx" outputId="62189701-faea-4ed4-f531-411fd9e20ef2" ''' print(f"input_test.shape = {input_test.shape}") #''' # + id="klW0J1i7ytUg" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="6b5fa6eb-7858-4ae3-cfda-a48bfa610c8b" ''' layer_outputs = [layer.output for layer in model_loaded.layers] activation_model = models.Model(inputs=model_loaded.input, outputs=layer_outputs) activations = activation_model.predict(input_test) #''' # + id="PXhv6uNf4Kqy" # + [markdown] id="W648c3vC1pIL" # #By Loading Single at a Time: # + colab={"base_uri": "https://localhost:8080/"} id="3lXRE2oAz-FK" outputId="e646ad82-a351-41e8-8752-0435602eac02" root_path = "drive/My Drive/Plant_Leaf_MalayaKew_MK_Dataset/MK/D2/test_patch/" #num_classes = 44 #list_classes = [f"Class{i+1}" for i in range(num_classes)] list_classes = [f"Class{i}" for i in [1,11,22,33,44]] list_input_path = [] for class_name in list_classes: list_input_path.append(f"{root_path}{class_name}/") print(f"len(list_input_path) = {len(list_input_path)}") # + colab={"base_uri": "https://localhost:8080/", "height": 36} id="Ov1bmBMav-Wg" outputId="fa5cc549-de42-41e2-835b-63650011a4f6" os.listdir(list_input_path[0])[0] # + colab={"base_uri": "https://localhost:8080/"} id="lbhQGHoKvq2p" outputId="b5aed16a-4947-456e-c242-3fc15635ad1a" list_full_paths = [] choose_different_index = 0 for input_path in list_input_path: filename = os.listdir(input_path)[choose_different_index] choose_different_index += 15 list_full_paths.append(f"{input_path}{filename}") print(f"len(list_full_paths) = {len(list_full_paths)}") # + colab={"base_uri": "https://localhost:8080/"} id="Td7X_qteAyLq" outputId="4790c409-7c29-479f-f2e9-d163369da7d0" list_full_paths # + colab={"base_uri": "https://localhost:8080/", "height": 54} id="tmeR_0Lcz-H7" outputId="6a467cc2-c981-4a0e-d1b4-3e0dc5dc3e17" ''' filename = "Class44(8)R315_00277.jpg" test_image = cv2.imread(f"{input_path}{filename}") print(f"test_image.shape = {test_image.shape}") input_test = np.expand_dims(test_image, 0) print(f"input_test.shape = {input_test.shape}") #''' # + colab={"base_uri": "https://localhost:8080/"} id="lsi51g-Bz-K0" outputId="c27ffa72-4299-4a6c-eacf-3c35d624f02b" list_test_images = [] for file_full_path in list_full_paths: test_image = cv2.imread(file_full_path) print(f"file_full_path: {file_full_path}") list_test_images.append(test_image) np_test_images = np.array(list_test_images) print(f"np_test_images.shape = {np_test_images.shape}") # + [markdown] id="l6Rwo5t8xorx" # #Get Layer Activation Outputs: # + id="zvSYJVJW3Wk9" layer_outputs = [layer.output for layer in model_loaded.layers] activation_model = models.Model(inputs=model_loaded.input, outputs=layer_outputs) #activations = activation_model.predict(input_test) # + colab={"base_uri": "https://localhost:8080/"} id="wF_6m3ltfqFo" outputId="69fb1dd2-b97a-4346-c898-6ba30b6225d4" list_activations = [] for test_image in tqdm(np_test_images): activations = activation_model.predict(np.array([test_image])) list_activations.append(activations) print(f"\nlen(list_activations) = {len(list_activations)}") # + id="CDp35uWo2eTS" # + [markdown] id="6bjLJKIciHZE" # ##Visualize: # + colab={"base_uri": "https://localhost:8080/"} id="Yymbnrsj3flS" outputId="f98ecd3d-0157-41cf-e859-bde2565b4215" ''' input_1(256,256,3), conv1/relu(128,128,64), pool2_relu(64,64,256), pool3_relu(32,32,512), pool4_relu(16,16,1792), relu(8,8,1920) ''' #target_layer_name = "conv3_block12_concat" list_target_layer_names = ['input_1', 'conv1/relu', 'pool2_relu', 'pool3_relu', 'pool4_relu', 'relu'] list_layer_indices = [] for target_layer_name in list_target_layer_names: for target_layer_index in range(len(layer_names)): if layer_names[target_layer_index]==target_layer_name: #layer_no = target_layer_index list_layer_indices.append(target_layer_index) #print(f"layer_names[{layer_no}] = {layer_names[layer_no]}") print(f"list_layer_indices = {list_layer_indices}") # + colab={"base_uri": "https://localhost:8080/"} id="nXvvBns6aPX5" outputId="5cfcfdf1-ed73-4744-8d57-1795bae9d7eb" for activations in list_activations: print(len(activations)) # + colab={"base_uri": "https://localhost:8080/", "height": 54} id="pSpNzilQ46Mo" outputId="978130ad-fa41-48cc-bb7d-82e43d3ccda1" ''' current_layer = activations[layer_no] num_neurons = current_layer.shape[1:][-1] print(f"current_layer.shape = {current_layer.shape}") print(f"image_dimension = {current_layer.shape[1:][:-1]}") print(f"num_neurons = {num_neurons}") #''' # + colab={"base_uri": "https://localhost:8080/"} id="LzJO_Wgcke9Y" outputId="02b2a3a2-dd7a-4782-c919-799b0190fa4a" list_all_activations_layers = [] list_all_num_neurons = [] # list_all_activations_layers -> list_activations_layers -> current_layer -> activations[layer_no] for activations in list_activations: list_activations_layers = [] list_neurons = [] for layer_no in list_layer_indices: current_layer = activations[layer_no] #print(f"current_layer.shape = {current_layer.shape}") list_activations_layers.append(current_layer) #list_current_layers.append(current_layer) list_neurons.append(current_layer.shape[1:][-1]) list_all_activations_layers.append(list_activations_layers) list_all_num_neurons.append(list_neurons) print(f"len(list_all_activations_layers) = {len(list_all_activations_layers)}") print(f"len(list_all_activations_layers[0]) = {len(list_all_activations_layers[0])}") print(f"list_all_activations_layers[0][0] = {list_all_activations_layers[0][0].shape}") print(f"list_all_num_neurons = {list_all_num_neurons}") print(f"list_all_num_neurons[0] = {list_all_num_neurons[0]}") # + colab={"base_uri": "https://localhost:8080/"} id="_kTGmOSqrEOU" outputId="c94d3b29-dad3-4013-8d87-0a40b801d70f" print(f"list_all_activations_layers[0][0] = {list_all_activations_layers[0][0].shape}") print(f"list_all_activations_layers[0][1] = {list_all_activations_layers[0][1].shape}") print(f"list_all_activations_layers[0][2] = {list_all_activations_layers[0][2].shape}") print(f"list_all_activations_layers[0][3] = {list_all_activations_layers[0][3].shape}") print(f"list_all_activations_layers[0][4] = {list_all_activations_layers[0][4].shape}") #print(f"list_all_activations_layers[0][5] = {list_all_activations_layers[0][5].shape}") # + colab={"base_uri": "https://localhost:8080/", "height": 286} id="uPAhAkCgrdT-" outputId="58b83ecc-eaa7-4586-82d3-7797f52bb3f5" #''' current_layer = list_all_activations_layers[0][1] superimposed_activation_image = current_layer[0, :, :, 0] for activation_image_index in range(1, current_layer.shape[-1]): current_activation_image = current_layer[0, :, :, activation_image_index] superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition plt.imshow(superimposed_activation_image, cmap='viridis') #''' # + colab={"base_uri": "https://localhost:8080/", "height": 286} id="0sSMu2wzsGVg" outputId="6ede6d85-875e-4846-c8a6-01b1177b9568" #''' current_layer = list_all_activations_layers[-1][1] superimposed_activation_image = current_layer[0, :, :, 0] for activation_image_index in range(1, current_layer.shape[-1]): current_activation_image = current_layer[0, :, :, activation_image_index] superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition plt.imshow(superimposed_activation_image, cmap='viridis') #''' # + id="VNU8xoUL51LV" #plt.matshow(current_layer[0, :, :, -1], cmap ='PiYG') #plt.matshow(current_layer[0, :, :, -1], cmap ='viridis') # + id="YxIBc2E_SzGa" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="c7f17ae6-8b53-4a16-df9c-ee9e9b81c1f9" ''' superimposed_activation_image = current_layer[0, :, :, 0] for activation_image_index in range(1, num_neurons): current_activation_image = current_layer[0, :, :, activation_image_index] #superimposed_activation_image = np.multiply(superimposed_activation_image, current_activation_image) # elementwise multiplication superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition plt.imshow(superimposed_activation_image, cmap='viridis') #''' # + id="SeA7aw_HWoMN" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="74d5bd9d-cdb7-428e-b0ee-3931d849ca21" ''' superimposed_activation_image = current_layer[0, :, :, 0] for activation_image_index in range(1, len(num_neurons)): current_activation_image = current_layer[0, :, :, activation_image_index] superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition plt.imshow(superimposed_activation_image, cmap='viridis') #''' # + colab={"base_uri": "https://localhost:8080/"} id="uydb14reCfwW" outputId="438a459d-62b1-448f-ea9a-407dd2d1445c" #''' # list_all_activations_layers -> list_activations_layers -> current_layer -> activations[layer_no] #num_activation_per_test_image = len(list_target_layer_names) list_all_superimposed_activation_image = [] for list_activations_layers_index in range(len(list_all_activations_layers)): list_activations_layers = list_all_activations_layers[list_activations_layers_index] list_current_num_neurons = list_all_num_neurons[list_activations_layers_index] #print(f"list_activations_layers_index = {list_activations_layers_index}") #print(f"list_all_num_neurons = {list_all_num_neurons}") #print(f"list_current_num_neurons = {list_current_num_neurons}") list_superimposed_activation_image = [] for activations_layer_index in range(len(list_activations_layers)): activations_layers = list_activations_layers[activations_layer_index] #print(f"activations_layers.shape = {activations_layers.shape}") num_neurons = list_current_num_neurons[activations_layer_index] superimposed_activation_image = activations_layers[0, :, :, 0] for activation_image_index in range(1, num_neurons): current_activation_image = activations_layers[0, :, :, activation_image_index] superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition #print(f"superimposed_activation_image.shape = {superimposed_activation_image.shape}") list_superimposed_activation_image.append(superimposed_activation_image) #print(f"list_superimposed_activation_image[0].shape = {list_superimposed_activation_image[0].shape}") list_all_superimposed_activation_image.append(list_superimposed_activation_image) #print(f"list_all_superimposed_activation_image[0][0].shape = {list_all_superimposed_activation_image[0][0].shape}") #plt.imshow(superimposed_activation_image, cmap='viridis') print(f"len(list_all_superimposed_activation_image) = {len(list_all_superimposed_activation_image)}") print(f"len(list_all_superimposed_activation_image[0]) = {len(list_all_superimposed_activation_image[0])}") print(f"len(list_all_superimposed_activation_image[0][0]) = {len(list_all_superimposed_activation_image[0][0])}") print(f"list_all_superimposed_activation_image[0][0].shape = {list_all_superimposed_activation_image[0][0].shape}") #''' # + colab={"base_uri": "https://localhost:8080/", "height": 128} id="sATiS-4tXC2S" outputId="11ec0c50-2b5f-4731-e407-b561393d6dc1" ''' interpolation = cv2.INTER_LINEAR # INTER_LINEAR, INTER_CUBIC, INTER_NEAREST # list_all_activations_layers -> list_activations_layers -> current_layer -> activations[layer_no] #num_activation_per_test_image = len(list_target_layer_names) list_all_superimposed_activation_image = [] for list_activations_layers_index in range(len(list_all_activations_layers)): list_activations_layers = list_all_activations_layers[list_activations_layers_index] list_current_num_neurons = list_all_num_neurons[list_activations_layers_index] #print(f"list_activations_layers_index = {list_activations_layers_index}") #print(f"list_all_num_neurons = {list_all_num_neurons}") #print(f"list_current_num_neurons = {list_current_num_neurons}") list_superimposed_activation_image = [] for activations_layer_index in range(len(list_activations_layers)): activations_layers = list_activations_layers[activations_layer_index] #print(f"activations_layers.shape = {activations_layers.shape}") num_neurons = list_current_num_neurons[activations_layer_index] superimposed_activation_image = activations_layers[0, :, :, 0] superimposed_activation_image_resized = cv2.resize(superimposed_activation_image, (256,256), interpolation = interpolation) for activation_image_index in range(1, num_neurons): current_activation_image = activations_layers[0, :, :, activation_image_index] #superimposed_activation_image = np.add(superimposed_activation_image, current_activation_image) # elementwise addition current_activation_image_resized = cv2.resize(current_activation_image, (256,256), interpolation = interpolation) superimposed_activation_image_resized = np.add(superimposed_activation_image_resized, current_activation_image_resized) # elementwise addition #print(f"superimposed_activation_image.shape = {superimposed_activation_image.shape}") #list_superimposed_activation_image.append(superimposed_activation_image) list_superimposed_activation_image.append(superimposed_activation_image_resized) #print(f"list_superimposed_activation_image[0].shape = {list_superimposed_activation_image[0].shape}") list_all_superimposed_activation_image.append(list_superimposed_activation_image) #print(f"list_all_superimposed_activation_image[0][0].shape = {list_all_superimposed_activation_image[0][0].shape}") #plt.imshow(superimposed_activation_image, cmap='viridis') print(f"len(list_all_superimposed_activation_image) = {len(list_all_superimposed_activation_image)}") print(f"len(list_all_superimposed_activation_image[0]) = {len(list_all_superimposed_activation_image[0])}") print(f"len(list_all_superimposed_activation_image[0][0]) = {len(list_all_superimposed_activation_image[0][0])}") print(f"list_all_superimposed_activation_image[0][0].shape = {list_all_superimposed_activation_image[0][0].shape}") print(f"list_all_superimposed_activation_image[0][-1].shape = {list_all_superimposed_activation_image[0][-1].shape}") #''' # + id="ox4o4lMddoii" # + colab={"base_uri": "https://localhost:8080/", "height": 128} id="V4yXgCD1ObB1" outputId="7c801549-c208-4c62-ad3d-2559fce104fb" ''' supported cmap values are: 'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'oc... ''' # + colab={"base_uri": "https://localhost:8080/", "height": 644} id="F3zED9xEpjQM" outputId="d6d0341a-8455-4118-96dd-3ba2ff3bb9ed" sub_fig_num_rows = len(list_test_images) sub_fig_num_cols = len(list_target_layer_names) fig_heigth = 11 fig_width = 11 cmap = "Greens" # PuOr_r, Dark2, Dark2_r, RdBu, RdBu_r, coolwarm, viridis, PiYG, gray, binary, afmhot, PuBu, copper fig, axes = plt.subplots(sub_fig_num_rows,sub_fig_num_cols, figsize=(fig_width,fig_heigth)) #plt.suptitle(f"Layer {str(layer_no+1)}: {layer_names[layer_no]} {str(current_layer.shape[1:])}", fontsize=20, y=1.1) for i,ax in enumerate(axes.flat): row = i//sub_fig_num_cols col = i%sub_fig_num_cols #print(f"i={i}; row={row}, col={col}") #''' ax.imshow(list_all_superimposed_activation_image[row][col], cmap=cmap) #ax.imshow(list_all_superimposed_activation_image[row][col]) ax.set_xticks([]) ax.set_yticks([]) if col == 0: ax.set_ylabel(f"{list_classes[row]}") if row == 0: #ax.set_xlabel(f"Layer {str(list_layer_indices[col])}") # , rotation=0, ha='right' ax.set_xlabel(str(list_target_layer_names[col])) #ax.set_xlabel(f"Layer {str(list_layer_indices[col])}: {str(list_target_layer_names[col])}") # , rotation=0, ha='right' ax.xaxis.set_label_position('top') ax.set_aspect('auto') plt.subplots_adjust(wspace=0.02, hspace=0.05) #''' # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="ZKKjgDVNJ46o" outputId="897adc7c-295f-4adf-a501-90dfee73b609" # good cmap for this work: PuOr_r, Dark2_r, RdBu, RdBu_r, coolwarm, viridis, PiYG ''' for activation_image_index in range(num_neurons): plt.imshow(current_layer[0, :, :, activation_image_index], cmap='PiYG') #''' plt.imshow(superimposed_activation_image, cmap='gray') # + id="212AvSgY39Dk" # + [markdown] id="yTVHjDQyxrYP" # #Weight Visualization: # + id="kCX4ucXMdOku" layer_outputs = [layer.output for layer in model_loaded.layers] #activation_model = models.Model(inputs=model_loaded.input, outputs=layer_outputs) #activations = activation_model.predict(input_test) # + colab={"base_uri": "https://localhost:8080/"} id="dCOrNeGEdOsu" outputId="ee09137e-a54e-4194-9d6a-c7a7f07e538c" layer_configs = [] layer_weights = [] for layer in model_loaded.layers: layer_configs.append(layer.get_config()) layer_weights.append(layer.get_weights()) print(f"len(layer_configs) = {len(layer_configs)}") print(f"len(layer_weights) = {len(layer_weights)}") # + colab={"base_uri": "https://localhost:8080/"} id="fw6huxYTdOvo" outputId="cf2c1d02-d7e2-48f9-bf48-aad26ec751d5" layer_configs[-9] # + id="x1VI_tY6dOyc" layer_name = 'conv2_block1_1_conv' # conv5_block32_1_conv model_weight = model_loaded.get_layer(layer_name).get_weights()[0] #model_biases = model_loaded.get_layer(layer_name).get_weights()[1] # + colab={"base_uri": "https://localhost:8080/"} id="F1FeqY8bdO1E" outputId="19b648cf-c9f0-419f-ad54-62a5295184bd" print(f"type(model_weight) = {type(model_weight)}") print(f"model_weight.shape = {model_weight.shape}") # + colab={"base_uri": "https://localhost:8080/"} id="iZxPM8ocdO37" outputId="2852b4ae-bb13-4fcc-badf-128347f1827d" model_weight[0][0].shape # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="KICZImKDdO6T" outputId="3328f6b3-cce3-40fb-e449-89af948f4a6c" plt.matshow(model_weight[0, 0, :, :], cmap ='viridis') # + id="m85ei0WAdO9L"
Plant_Leaf_MalayaKew_MK_Dataset/Layer_Activation_Visualization_from_Saved_Model_Malaya_Kew.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Blog Post: Spectral Clustering # # In this blog post, you'll write a tutorial on a simple version of the *spectral clustering* algorithm for clustering data points. Each of the below parts will pose to you one or more specific tasks. You should plan to both: # # - Achieve these tasks using clean, efficient, and well-documented Python and # - Write, in your own words, about how to understand what's going on. # # > Remember, your aim is not just to write and understand the algorithm, but to explain to someone else how they could do the same. # # ***Note***: your blog post doesn't have to contain a lot of math. It's ok for you to give explanations like "this function is an approximation of this other function according to the math in the written assignment." # # ### Notation # # In all the math below: # # - Boldface capital letters like $\mathbf{A}$ refer to matrices (2d arrays of numbers). # - Boldface lowercase letters like $\mathbf{v}$ refer to vectors (1d arrays of numbers). # - $\mathbf{A}\mathbf{B}$ refers to a matrix-matrix product (`A@B`). $\mathbf{A}\mathbf{v}$ refers to a matrix-vector product (`A@v`). # # ### Comments and Docstrings # # You should plan to comment all of your code. Docstrings are not required except in Part G. # # ## Introduction # # In this problem, we'll study *spectral clustering*. Spectral clustering is an important tool for identifying meaningful parts of data sets with complex structure. To start, let's look at an example where we *don't* need spectral clustering. import numpy as np from sklearn import datasets from matplotlib import pyplot as plt n = 200 np.random.seed(1111) X, y = datasets.make_blobs(n_samples=n, shuffle=True, random_state=None, centers = 2, cluster_std = 2.0) plt.scatter(X[:,0], X[:,1]) # *Clustering* refers to the task of separating this data set into the two natural "blobs." K-means is a very common way to achieve this task, which has good performance on circular-ish blobs like these: # + from sklearn.cluster import KMeans km = KMeans(n_clusters = 2) km.fit(X) plt.scatter(X[:,0], X[:,1], c = km.predict(X)) # - # ### Harder Clustering # # That was all well and good, but what if our data is "shaped weird"? np.random.seed(1234) n = 200 X, y = datasets.make_moons(n_samples=n, shuffle=True, noise=0.05, random_state=None) plt.scatter(X[:,0], X[:,1]) # We can still make out two meaningful clusters in the data, but now they aren't blobs but crescents. As before, the Euclidean coordinates of the data points are contained in the matrix `X`, while the labels of each point are contained in `y`. Now k-means won't work so well, because k-means is, by design, looking for circular clusters. km = KMeans(n_clusters = 2) km.fit(X) plt.scatter(X[:,0], X[:,1], c = km.predict(X)) # Whoops! That's not right! # # As we'll see, spectral clustering is able to correctly cluster the two crescents. In the following problems, you will derive and implement spectral clustering. # ## Part A # # Construct the *similarity matrix* $\mathbf{A}$. $\mathbf{A}$ should be a matrix (2d `np.ndarray`) with shape `(n, n)` (recall that `n` is the number of data points). # # When constructing the similarity matrix, use a parameter `epsilon`. Entry `A[i,j]` should be equal to `1` if `X[i]` (the coordinates of data point `i`) is within distance `epsilon` of `X[j]` (the coordinates of data point `j`), and `0` otherwise. # # **The diagonal entries `A[i,i]` should all be equal to zero.** The function `np.fill_diagonal()` is a good way to set the values of the diagonal of a matrix. # # #### Note # # It is possible to do this manually in a `for`-loop, by testing whether `(X[i] - X[j])**2 < epsilon**2` for each choice of `i` and `j`. This is not recommended! Instead, see if you can find a solution built into `sklearn`. Can you find a function that will compute all the pairwise distances and collect them into an appropriate matrix for you? # # For this part, use `epsilon = 0.4`. import sklearn eps = 0.4 A = sklearn.metrics.pairwise_distances(X) < eps A = A - np.diag(np.ones(n)) # ## Part B # # The matrix `A` now contains information about which points are near (within distance `epsilon`) which other points. We now pose the task of clustering the data points in `X` as the task of partitioning the rows and columns of `A`. # # Let $d_i = \sum_{j = 1}^n a_{ij}$ be the $i$th row-sum of $\mathbf{A}$, which is also called the *degree* of $i$. Let $C_0$ and $C_1$ be two clusters of the data points. We assume that every data point is in either $C_0$ or $C_1$. The cluster membership as being specified by `y`. We think of `y[i]` as being the label of point `i`. So, if `y[i] = 1`, then point `i` (and therefore row $i$ of $\mathbf{A}$) is an element of cluster $C_1$. # # The *binary norm cut objective* of a matrix $\mathbf{A}$ is the function # # $$N_{\mathbf{A}}(C_0, C_1)\equiv \mathbf{cut}(C_0, C_1)\left(\frac{1}{\mathbf{vol}(C_0)} + \frac{1}{\mathbf{vol}(C_1)}\right)\;.$$ # # In this expression, # - $\mathbf{cut}(C_0, C_1) \equiv \sum_{i \in C_0, j \in C_1} a_{ij}$ is the *cut* of the clusters $C_0$ and $C_1$. # - $\mathbf{vol}(C_0) \equiv \sum_{i \in C_0}d_i$, where $d_i = \sum_{j = 1}^n a_{ij}$ is the *degree* of row $i$ (the total number of all other rows related to row $i$ through $A$). The *volume* of cluster $C_0$ is a measure of the size of the cluster. # # A pair of clusters $C_0$ and $C_1$ is considered to be a "good" partition of the data when $N_{\mathbf{A}}(C_0, C_1)$ is small. To see why, let's look at each of the two factors in this objective function separately. # # # #### B.1 The Cut Term # # First, the cut term $\mathbf{cut}(C_0, C_1)$ is the number of nonzero entries in $\mathbf{A}$ that relate points in cluster $C_0$ to points in cluster $C_1$. Saying that this term should be small is the same as saying that points in $C_0$ shouldn't usually be very close to points in $C_1$. # # Write a function called `cut(A,y)` to compute the cut term. You can compute it by summing up the entries `A[i,j]` for each pair of points `(i,j)` in different clusters. # # There is a solution for computing the cut term that uses only `numpy` tools and no loops. However, it's fine to use `for`-loops for this part only -- we're going to see a more efficient approach later. def cut(A,y): cut = 0 for i in np.arange(len(y)): for j in np.arange(len(y)): if y[i] != y[j]: cut += A[i, j] return cut # Compute the cut objective for the true clusters `y`. Then, generate a random vector of random labels of length `n`, with each label equal to either 0 or 1. Check the cut objective for the random labels. You should find that the cut objective for the true labels is *much* smaller than the cut objective for the random labels. # # This shows that this part of the cut objective indeed favors the true clusters over the random ones. true_cut = cut(A, y) true_cut rand_y = np.random.randint(0, 2, size=n) rand_cut = cut(A, rand_y) rand_cut # #### B.2 The Volume Term # # Now take a look at the second factor in the norm cut objective. This is the *volume term*. As mentioned above, the *volume* of cluster $C_0$ is a measure of how "big" cluster $C_0$ is. If we choose cluster $C_0$ to be small, then $\mathbf{vol}(C_0)$ will be small and $\frac{1}{\mathbf{vol}(C_0)}$ will be large, leading to an undesirable higher objective value. # # Synthesizing, the binary normcut objective asks us to find clusters $C_0$ and $C_1$ such that: # # 1. There are relatively few entries of $\mathbf{A}$ that join $C_0$ and $C_1$. # 2. Neither $C_0$ and $C_1$ are too small. # # Write a function called `vols(A,y)` which computes the volumes of $C_0$ and $C_1$, returning them as a tuple. For example, `v0, v1 = vols(A,y)` should result in `v0` holding the volume of cluster `0` and `v1` holding the volume of cluster `1`. Then, write a function called `normcut(A,y)` which uses `cut(A,y)` and `vols(A,y)` to compute the binary normalized cut objective of a matrix `A` with clustering vector `y`. # # ***Note***: No for-loops in this part. Each of these functions should be implemented in five lines or less. def vols(A, y): row_sums = A.sum(axis = 1) y0 = np.sum(row_sums[y == 0]) y1 = np.sum(row_sums[y == 1]) return (y0, y1) def normcut(A,y): v0, v1 = vols(A, y) return cut(A, y) * (1/v0 + 1/v1) # Now, compare the `normcut` objective using both the true labels `y` and the fake labels you generated above. What do you observe about the normcut for the true labels when compared to the normcut for the fake labels? normcut(A, y) normcut(A, rand_y) # *** The one with random number is MUCH bigger *** # ## Part C # # We have now defined a normalized cut objective which takes small values when the input clusters are (a) joined by relatively few entries in $A$ and (b) not too small. One approach to clustering is to try to find a cluster vector `y` such that `normcut(A,y)` is small. However, this is an NP-hard combinatorial optimization problem, which means that may not be possible to find the best clustering in practical time, even for relatively small data sets. We need a math trick! # # Here's the trick: define a new vector $\mathbf{z} \in \mathbb{R}^n$ such that: # # $$ # z_i = # \begin{cases} # \frac{1}{\mathbf{vol}(C_0)} &\quad \text{if } y_i = 0 \\ # -\frac{1}{\mathbf{vol}(C_1)} &\quad \text{if } y_i = 1 \\ # \end{cases} # $$ # # # Note that the signs of the elements of $\mathbf{z}$ contain all the information from $\mathbf{y}$: if $i$ is in cluster $C_0$, then $y_i = 0$ and $z_i > 0$. # # Next, if you like linear algebra, you can show that # # $$\mathbf{N}_{\mathbf{A}}(C_0, C_1) = \frac{\mathbf{z}^T (\mathbf{D} - \mathbf{A})\mathbf{z}}{\mathbf{z}^T\mathbf{D}\mathbf{z}}\;,$$ # # where $\mathbf{D}$ is the diagonal matrix with nonzero entries $d_{ii} = d_i$, and where $d_i = \sum_{j = 1}^n a_i$ is the degree (row-sum) from before. # # 1. Write a function called `transform(A,y)` to compute the appropriate $\mathbf{z}$ vector given `A` and `y`, using the formula above. # 2. Then, check the equation above that relates the matrix product to the normcut objective, by computing each side separately and checking that they are equal. # 3. While you're here, also check the identity $\mathbf{z}^T\mathbf{D}\mathbb{1} = 0$, where $\mathbb{1}$ is the vector of `n` ones (i.e. `np.ones(n)`). This identity effectively says that $\mathbf{z}$ should contain roughly as many positive as negative entries. # # #### Programming Note # # You can compute $\mathbf{z}^T\mathbf{D}\mathbf{z}$ as `z@D@z`, provided that you have constructed these objects correctly. # # #### Note # # The equation above is exact, but computer arithmetic is not! `np.isclose(a,b)` is a good way to check if `a` is "close" to `b`, in the sense that they differ by less than the smallest amount that the computer is (by default) able to quantify. # # Also, still no for-loops. def transform(A, y): v0, v1 = vols(A, y) z = y * 1/v0 + (y-1) * 1/v1 return z z = transform(A,y) D = np.diag(A.sum(axis = 1)) est = (z@(D-A)@z) / (z@D@z) est*2 normcut(A,y) np.isclose(normcut(A,y), est) z@D@(np.ones(n)) # ## Part D # # In the last part, we saw that the problem of minimizing the normcut objective is mathematically related to the problem of minimizing the function # # $$ R_\mathbf{A}(\mathbf{z})\equiv \frac{\mathbf{z}^T (\mathbf{D} - \mathbf{A})\mathbf{z}}{\mathbf{z}^T\mathbf{D}\mathbf{z}} $$ # # subject to the condition $\mathbf{z}^T\mathbf{D}\mathbb{1} = 0$. It's actually possible to bake this condition into the optimization, by substituting for $\mathbf{z}$ the orthogonal complement of $\mathbf{z}$ relative to $\mathbf{D}\mathbf{1}$. In the code below, I define an `orth_obj` function which handles this for you. # # Use the `minimize` function from `scipy.optimize` to minimize the function `orth_obj` with respect to $\mathbf{z}$. Note that this computation might take a little while. Explicit optimization can be pretty slow! Give the minimizing vector a name `z_min`. # + def orth(u, v): return (u @ v) / (v @ v) * v e = np.ones(n) d = D @ e def orth_obj(z): z_o = z - orth(z, d) return (z_o @ (D - A) @ z_o)/(z_o @ D @ z_o) # - from scipy.optimize import minimize z_min = minimize(orth_obj, np.ones(n)).x # **Note**: there's a cheat going on here! We originally specified that the entries of $\mathbf{z}$ should take only one of two values (back in Part C), whereas now we're allowing the entries to have *any* value! This means that we are no longer exactly optimizing the normcut objective, but rather an approximation. This cheat is so common that deserves a name: it is called the *continuous relaxation* of the normcut problem. # ## Part E # # Recall that, by design, only the sign of `z_min[i]` actually contains information about the cluster label of data point `i`. Plot the original data, using one color for points such that `z_min[i] < 0` and another color for points such that `z_min[i] >= 0`. # # Does it look like we came close to correctly clustering the data? plt.scatter(X[:,0], X[:,1], c = (z_min.x > 0)) # ## Part F # # Explicitly optimizing the orthogonal objective is *way* too slow to be practical. If spectral clustering required that we do this each time, no one would use it. # # The reason that spectral clustering actually matters, and indeed the reason that spectral clustering is called *spectral* clustering, is that we can actually solve the problem from Part E using eigenvalues and eigenvectors of matrices. # # Recall that what we would like to do is minimize the function # # $$ R_\mathbf{A}(\mathbf{z})\equiv \frac{\mathbf{z}^T (\mathbf{D} - \mathbf{A})\mathbf{z}}{\mathbf{z}^T\mathbf{D}\mathbf{z}} $$ # # with respect to $\mathbf{z}$, subject to the condition $\mathbf{z}^T\mathbf{D}\mathbb{1} = 0$. # # The Rayleigh-Ritz Theorem states that the minimizing $\mathbf{z}$ must be the solution with smallest eigenvalue of the generalized eigenvalue problem # # $$ (\mathbf{D} - \mathbf{A}) \mathbf{z} = \lambda \mathbf{D}\mathbf{z}\;, \quad \mathbf{z}^T\mathbf{D}\mathbb{1} = 0$$ # # which is equivalent to the standard eigenvalue problem # # $$ \mathbf{D}^{-1}(\mathbf{D} - \mathbf{A}) \mathbf{z} = \lambda \mathbf{z}\;, \quad \mathbf{z}^T\mathbb{1} = 0\;.$$ # # Why is this helpful? Well, $\mathbb{1}$ is actually the eigenvector with smallest eigenvalue of the matrix $\mathbf{D}^{-1}(\mathbf{D} - \mathbf{A})$. # # > So, the vector $\mathbf{z}$ that we want must be the eigenvector with the *second*-smallest eigenvalue. # # Construct the matrix $\mathbf{L} = \mathbf{D}^{-1}(\mathbf{D} - \mathbf{A})$, which is often called the (normalized) *Laplacian* matrix of the similarity matrix $\mathbf{A}$. Find the eigenvector corresponding to its second-smallest eigenvalue, and call it `z_eig`. Then, plot the data again, using the sign of `z_eig` as the color. How did we do? D_inv = np.linalg.inv(D) L = D_inv @ (D - A) # + Lam, U = np.linalg.eig(L) index = Lam.argsort() Lam, U = Lam[index], U[:,index] z_eig = U[:,1].astype(float) # - U[:,1] plt.scatter(X[:,0], X[:,1], c = (z_eig > 0)) # In fact, `z_eig` should be proportional to `z_min`, although this won't be exact because minimization has limited precision by default. # ## Part G # # Synthesize your results from the previous parts. In particular, write a function called `spectral_clustering(X, epsilon)` which takes in the input data `X` (in the same format as Part A) and the distance threshold `epsilon` and performs spectral clustering, returning an array of binary labels indicating whether data point `i` is in group `0` or group `1`. Demonstrate your function using the supplied data from the beginning of the problem. # # #### Notes # # Despite the fact that this has been a long journey, the final function should be quite short. You should definitely aim to keep your solution under 10, very compact lines. # # **In this part only, please supply an informative docstring!** # # #### Outline # # Given data, you need to: # # 1. Construct the similarity matrix. # 2. Construct the Laplacian matrix. # 3. Compute the eigenvector with second-smallest eigenvalue of the Laplacian matrix. # 4. Return labels based on this eigenvector. def spectral_clustering(X, epsilon): A = sklearn.metrics.pairwise_distances(X) < epsilon z = transform(A,y) D = np.diag(A.sum(axis = 1)) D_inv = np.linalg.inv(D) L = D_inv @ (D - A) #Get second smallest eigenvector Lam, U = np.linalg.eig(L) index = Lam.argsort() Lam, U = Lam[index], U[:,index] z_eig = U[:,1].astype(float) return (z_eig > 0).astype(int) # ## Part H # # Run a few experiments using your function, by generating different data sets using `make_moons`. What happens when you increase the `noise`? Does spectral clustering still find the two half-moon clusters? For these experiments, you may find it useful to increase `n` to `1000` or so -- we can do this now, because of our fast algorithm! # + X, y = datasets.make_moons(n_samples=1000, shuffle=True, noise=0.1, random_state=None) labels = spectral_clustering(X, eps) plt.scatter(X[:,0], X[:,1], c = labels) # + X, y = datasets.make_moons(n_samples=1000, shuffle=True, noise=0.15, random_state=None) labels = spectral_clustering(X, .3) plt.scatter(X[:,0], X[:,1], c = labels) # - # ## Part I # # Now try your spectral clustering function on another data set -- the bull's eye! n = 1000 X, y = datasets.make_circles(n_samples=n, shuffle=True, noise=0.05, random_state=None, factor = 0.4) plt.scatter(X[:,0], X[:,1]) # There are two concentric circles. As before k-means will not do well here at all. km = KMeans(n_clusters = 2) km.fit(X) plt.scatter(X[:,0], X[:,1], c = km.predict(X)) # Can your function successfully separate the two circles? Some experimentation here with the value of `epsilon` is likely to be required. Try values of `epsilon` between `0` and `1.0` and describe your findings. For roughly what values of `epsilon` are you able to correctly separate the two rings? labels = spectral_clustering(X, .3) plt.scatter(X[:,0], X[:,1], c = labels) # ## Part J # # Great work! Turn this notebook into a blog post with plenty of helpful explanation for your reader. Remember that your blog post should be entirely in your own words, without any copying and pasting from this notebook. Remember also that extreme mathematical detail is not required.
notebooks/spectral-clustering copy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Bioferineries # The `biorefineries` package comes with key BioSTEAM biorefinery designs, including a design for 2nd generation ethanol production from corntover and a design for the co-production of ethanol and biodiesel from lipidcane [[1, 2]](#References). To load the cornstover biorefinery, simply load the `system`: import biosteam as bst # First "pip install biorefineries" from biorefineries.cornstover import system # Now your flowsheet should change to the cornstover biorefinery: bst.find # All systems, unit operations, and streams are registered in your flowsheet: bst.find.system # By convention, the complete biorefinery system begins with the same name as the flowsheet: cornstover_sys = bst.find.system.cornstover_sys cornstover_sys.diagram() # Similarly, you can also load the lipidcane biorefinery: from biorefineries.lipidcane import system lipidcane_sys = bst.find.system.lipidcane_sys lipidcane_sys.diagram() # Note that your flowsheet is now "lipidcane": bst.find # You can switch flowsheets anytime with the `set_flowsheet` method: bst.find.flowsheet bst.find.set_flowsheet('default') bst.find # You can also import only the Chemicals object used to model the thermodynamic properties, without having to load the whole biorefinery system: from biorefineries.lipidcane.chemicals import lipidcane_chemicals # Note: The species module contains all species objects lipidcane_chemicals # **References** # # <a id='References'></a> # # 1. <NAME>., <NAME>., & <NAME>. (2016) "Techno-economic analysis of biodiesel and ethanol co-production from lipid-producing sugarcane" Biofuels, Bioproducts and Biorefining, 10(3), 299–315. https://doi.org/10.1002/bbb.1640 # # 2. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2011). Process Design and Economics for Biochemical Conversion of Lignocellulosic Biomass to Ethanol: Dilute-Acid Pretreatment and Enzymatic Hydrolysis of Corn Stover (No. NREL/TP-5100-47764, 1013269). https://doi.org/10.2172/1013269 #
docs/tutorial/Biorefineries.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## 출처 : 머신러닝 교과서 with 파이썬 # # - 퍼셉트론은 두 클래스가 선형적으로 구분되고 학습률이 충분히 작을 때만 수렴이 보장 됨. # - 두 클래스를 선형 결정 경계로 나눌 수 없다면 훈련 데이터셋을 반복할 최대횟수 (epoch:에포크)와 분류 허용 오차를 지정 # - 그렇지 않으면 퍼셉트론은 가중치 업데이트를 멈추지 않음 # # ## 과제1. 아래의 코드에 주석을 달고 각 결과물이 무엇을 보이고 있는지 코멘트 남겨주세요. # + import numpy as np class Perceptron(object): def __init__(self, eta=0.01, n_iter=50, random_state=1): self.eta = eta self.n_iter = n_iter self.random_state = random_state def fit(self, X, y): rgen = np.random.RandomState(self.random_state) self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1]) self.errors_ = [] for _ in range(self.n_iter): errors = 0 for xi, target in zip(X, y): update = self.eta * (target - self.predict(xi)) self.w_[1:] += update * xi self.w_[0] += update errors += int(update != 0.0) self.errors_.append(errors) return self def net_input(self, X): return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, -1) # - # ## iris data에서 퍼셉트론 훈련 # + import pandas as pd df = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/iris/iris.data', header=None) df.tail() # + # %matplotlib inline import matplotlib.pyplot as plt import numpy as np # setosa와 versicolor를 선택합니다 y = df.iloc[0:100, 4].values # setosa일 경우 -1, 아니면(versicolor) 1 y = np.where(y == 'Iris-setosa', -1, 1) # 꽃받침 길이와 꽃잎 길이를 추출합니다 X = df.iloc[0:100, [0, 2]].values # 산점도를 그립니다 plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa') plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='versicolor') plt.xlabel('sepal length [cm]') plt.ylabel('petal length [cm]') plt.legend(loc='upper left') plt.show() # + ppn = Perceptron(eta=0.1, n_iter=10) ppn.fit(X, y) print(ppn.errors_) plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') plt.xlabel('Epochs') plt.ylabel('Number of errors') plt.show() # + from matplotlib.colors import ListedColormap def plot_decision_regions(X, y, classifier, resolution=0.02): # 마커와 컬러맵을 설정합니다 markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # 결정 경계를 그립니다 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # 샘플의 산점도를 그립니다 for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolor='black') # + plot_decision_regions(X, y, classifier=ppn) plt.xlabel('sepal length [cm]') plt.ylabel('petal length [cm]') plt.legend(loc='upper left') plt.show() # + from sklearn import datasets #만약 datasets가 없다는 오류 메세지가 뜬다면 위에서 불러온 방법으로 로딩 import numpy as np iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target print('class label:', np.unique(y)) # + from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y) # - print('label count of y:', np.bincount(y)) print('label count of y_train:', np.bincount(y_train)) print('label count of y_test:', np.bincount(y_test)) # + from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) # + from sklearn.linear_model import Perceptron ppn = Perceptron(max_iter=40, eta0=0.1, tol=1e-3, random_state=1) ppn.fit(X_train_std, y_train) # - y_pred = ppn.predict(X_test_std) print('The number of misclassified sample : %d' % (y_test != y_pred).sum()) # + from sklearn.metrics import accuracy_score print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) # + from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # 마커와 컬러맵을 설정합니다. markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # 결정 경계를 그립니다. x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolor='black') # 테스트 샘플을 부각하여 그립니다. if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], facecolors='none', edgecolor='black', alpha=1.0, linewidth=1, marker='o', s=100, label='test set') # + X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() plt.show() # - # -https://scikit-learn.org/stable/modules/neural_networks_supervised.html # # - 여기를 참고하셔서 수업시간에 배운 내용을 상기시켜보면 이 사이트의 내용이 이해가 되실 것이라 생각됩니다. # - 이곳에서 MLPClassifier에 주어지는 parameter에 대해 이해하시기 바랍니다. # - https://tensorflow.blog/%ed%8c%8c%ec%9d%b4%ec%8d%ac-%eb%a8%b8%ec%8b%a0%eb%9f%ac%eb%8b%9d/2-3-8-%ec%8b%a0%ea%b2%bd%eb%a7%9d%eb%94%a5%eb%9f%ac%eb%8b%9d/#neural-model # - 위 사이트가 introduction to machine learning with python 의 번역본이고 교재의 코드입니다. # # ## 과제2. 아래의 코드에 주석을 달고 결과물이 무엇을 의미하는지 교재를 보고 요약해서 코멘트하기 # # - 반복되는 코드의 주석을 모두 달아줄 필요는 없습니다. 변경 된 부분만! 스스로에게 도움이 되는 과제가 되세요. # + from sklearn.neural_network import MLPClassifier from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split import mglearn X,y = make_moons(n_samples=100, noise=0.25, random_state=3) X_train, X_test, y_train, y_test=train_test_split(X,y, stratify=y, random_state=42) mlp=MLPClassifier(solver='lbfgs', random_state=0).fit(X_train, y_train) mglearn.plots.plot_2d_separator(mlp, X_train, fill=True, alpha=.3) mglearn.discrete_scatter(X_train[:,0], X_train[:,1], y_train) plt.xlabel('zero') plt.ylabel('one') # - mlp = MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[10]) mlp.fit(X_train, y_train) mglearn.plots.plot_2d_separator(mlp, X_train, fill=True, alpha=.3) mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train) plt.xlabel('zero') plt.ylabel('one') fig, axes = plt.subplots(2, 4, figsize=(20, 8)) for axx, n_hidden_nodes in zip(axes, [10, 100]): for ax, alpha in zip(axx, [0.0001, 0.01, 0.1, 1]): mlp = MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[n_hidden_nodes, n_hidden_nodes], alpha=alpha) mlp.fit(X_train, y_train) mglearn.plots.plot_2d_separator(mlp, X_train, fill=True, alpha=.3, ax=ax) mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train, ax=ax) ax.set_title("n_hidden=[{}, {}]\nalpha={:.4f}".format( n_hidden_nodes, n_hidden_nodes, alpha)) fig, axes = plt.subplots(2, 4, figsize=(20, 8)) for i, ax in enumerate(axes.ravel()): mlp = MLPClassifier(solver='lbfgs', random_state=i, hidden_layer_sizes=[100, 100]) mlp.fit(X_train, y_train) mglearn.plots.plot_2d_separator(mlp, X_train, fill=True, alpha=.3, ax=ax) mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train, ax=ax) from sklearn.datasets import load_breast_cancer cancer=load_breast_cancer() print("max:\n{}".format(cancer.data.max(axis=0))) # + X_train, X_test, y_train, y_test = train_test_split( cancer.data, cancer.target, random_state=0) mlp = MLPClassifier(random_state=42) mlp.fit(X_train, y_train) print("train accuracy: {:.2f}".format(mlp.score(X_train, y_train))) print("test accuracy: {:.2f}".format(mlp.score(X_test, y_test))) # + # 훈련 세트 각 특성의 평균을 계산합니다. mean_on_train = X_train.mean(axis=0) # 훈련 세트 각 특성의 표준 편차를 계산합니다. std_on_train = X_train.std(axis=0) # 데이터에서 평균을 빼고 표준 편차로 나누면 # 평균 0, 표준 편차 1인 데이터로 변환됩니다. X_train_scaled = (X_train - mean_on_train) / std_on_train # (훈련 데이터의 평균과 표준 편차를 이용해) 같은 변환을 테스트 세트에도 합니다. X_test_scaled = (X_test - mean_on_train) / std_on_train mlp = MLPClassifier(random_state=0) mlp.fit(X_train_scaled, y_train) print("train accuracy: {:.3f}".format(mlp.score(X_train_scaled, y_train))) print("test accuracy: {:.3f}".format(mlp.score(X_test_scaled, y_test))) # + mlp = MLPClassifier(max_iter=1000, random_state=0) mlp.fit(X_train_scaled, y_train) print("train accuracy: {:.3f}".format(mlp.score(X_train_scaled, y_train))) print("test accuracy: {:.3f}".format(mlp.score(X_test_scaled, y_test))) # + mlp = MLPClassifier(max_iter=1000, alpha=1, random_state=0) mlp.fit(X_train_scaled, y_train) print("train accuracy: {:.3f}".format(mlp.score(X_train_scaled, y_train))) print("test accuracy: {:.3f}".format(mlp.score(X_test_scaled, y_test))) # - plt.figure(figsize=(20, 5)) plt.imshow(mlp.coefs_[0], interpolation='none', cmap='viridis') plt.yticks(range(30), cancer.feature_names) plt.xlabel("hidden unit") plt.ylabel("input") plt.colorbar() # ## 과제 3. breast cancer에 대해 앞서 제출했던 분류 모델과 신경망까지 모두 사용해서 정확도를 표준화 전후를 포함해서 비교해주세요.
Assignment_05_Neural_Network/nn example iris.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Shadow cast by an thin emission disk around a Schwarzschild Black Hole # + import astropy.units as u from einsteinpy.rays import Shadow from einsteinpy.plotting import ShadowPlotter # - # Defining the conditions mass = 1 * u.kg fov = 30 * u.km # What field of view is the user expecting shadow = Shadow(mass=mass, fov=fov, n_rays=1000) obj = ShadowPlotter(shadow=shadow, is_line_plot=True) obj.plot() obj.show() obj = ShadowPlotter(shadow=shadow, is_line_plot=False) obj.plot() obj.show()
docs/source/examples/Shadow cast by an thin emission disk around a black hole.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: venv # language: python # name: venv # --- # # Reef Check - abalone size/frequency data # # Abalone size surveys are conducted north of the Golden Gate. Any red abalone encountered during usual Reef Check surveys are sized using calipers. In addition, independent abalone surveys are conducted where a diver swims over the reef and measures every red abalone encountered, with a goal of measuring 250 animals. # + ## Imports import pandas as pd import numpy as np import random from datetime import datetime # for handling dates # + ## Ensure my general functions for the MPA data integration project can be imported, and import them import sys sys.path.insert(0, "C:\\Users\\dianalg\\PycharmProjects\\PythonScripts\\MPA data integration") import WoRMS # functions for querying WoRMS REST API # + ## Load data data = pd.read_csv('RCCA_abalone_size_data.csv') print(data.shape) data.head() # - # **A couple questions here:** # 1. I thought these surveys were conducted at the site level. Why are they broken out by transect? **Looking closer, the transect column is not actually informative. I don't need to aggregate by transect, since each individual has its own row and is assigned to the correct site and survey date regardless of transect. It's just weird that this information is available, seeing as the divers could measure abalone off-transect, and transect is never NaN.** # 2. Based on the protocol document, I thought these surveys only covered red abalone, but several different species are listed here. # # According to the table metadata, starting in 2015, red abalone north of San Francisco were measured to the nearest mm. Prior to 2015 and south of San Francisco abalone were measured to the nearest cm. # # ## Create occurrence file # # Here, it seems reasonable for the **event** to be the survey (e.g. site + survey date). The **occurrrences** can be the abalone observations. # + ## Get site names w/o spaces for use in eventID # Get a list of site names with spaces removed site_names = [name.replace(' ', '') for name in data['Site']] # Map site_names to sites site_name_dict = dict(zip(data['Site'], site_names)) site_name_dict["Lover's 3"] = 'Lovers3' site_name_dict['West Long Point'] = 'LongPointWest' # Create SiteName column from Site column data['SiteName'] = data['Site'] data['SiteName'].replace(site_name_dict, inplace=True) data.head() # + ## Pad month and day as needed paddedDay = ['0' + str(data['Day'].iloc[i]) if len(str(data['Day'].iloc[i])) == 1 else str(data['Day'].iloc[i]) for i in range(len(data['Day']))] paddedMonth = ['0' + str(data['Month'].iloc[i]) if len(str(data['Month'].iloc[i])) == 1 else str(data['Month'].iloc[i]) for i in range(len(data['Month']))] # + ## Create eventID eventID = [data['SiteName'].iloc[i] + '_' + str(data['Year'].iloc[i]) + paddedMonth[i] + paddedDay[i] for i in range(len(data['Site']))] occ = pd.DataFrame({'eventID':eventID}) occ.head() # + ## Format dates and add eventDate eventDate = [datetime.strptime(dt, '%d-%b-%y').date().isoformat() for dt in data['SurveyDate']] occ['eventDate'] = eventDate occ.head() # + ## Add datasetID occ['datasetID'] = 'RCCA abalone size' occ.head() # + ## Add locality and countryCode # locality occ['locality'] = data['Site'] occ.loc[occ['locality'] == "Lover's 3", 'locality'] = 'Lovers 3' occ.loc[occ['locality'] == 'West Long Point', 'locality'] = 'Long Point West' # countryCode occ['countryCode'] = 'US' occ.head() # - # **Note** that some lat, lon pairs were missing from the abalone size data, although the sites are listed in the site table, and the lon, lat for those same sites are listed elsewhere in the data. For example, the following query will show some missing values for the Aquarium site: # # ``` python # data[data['Site'] == 'Aquarium'] # ``` # # Given this, it seemed most reasonable to load the site table and populate lat, lons from there. # + ## Load site table to get lat, lon filename = 'RCCA_site_table.csv' sites = pd.read_csv(filename, usecols=range(7)) sites.head() # + ## Add rows to site table -- CAN BE DELETED WHEN SITE TABLE IS UPDATED ON DATAONE sites_to_add = pd.DataFrame({'Research_group':['RCCA']*5, 'Site':['Cayucos', 'Hurricane Ridge', 'LA Federal Breakwater', 'Ocean Cove Kelper', 'Pier 400'], 'Latitude':[35.4408, 37.4701, 33.711899, 38.555119, 33.716301], 'Longitude':[-120.936302, -122.4796, -118.241997, -123.3046, -118.258003]}) sites = pd.concat([sites, sites_to_add]) # + ## Merge to obtain decimalLat, decimalLon # Merge occ = occ.merge(sites[['Site', 'MPA_status', 'Latitude', 'Longitude']], how='left', left_on='locality', right_on='Site') # Rename columns occ.rename(columns={'MPA_status':'locationRemarks', 'Latitude':'decimalLatitude', 'Longitude':'decimalLongitude'}, inplace=True) # Drop Site occ.drop(columns='Site', inplace=True) occ.head() # - # According to the metadata on DataONE, locationRemarks can take on the following values: # - MPA = Site is in MPA # - REF = Site is outside of MPA and used as MPA refernce site # - NaN = Site is not part of MPA monitoring # - MPA/REF = Site is in MPA and used as refercnes site for another MPA # # Based on this, it sounds like MPA and MPA/REF should be converted to "marine protected area" and REF and NaN should be converted to "fished area" # # **Note** that for the sites I added to the site table, I looked up manually whether the location was inside an MPA or not: # - Cayucos = fished # - Hurricane Ridge = fished # - LA Federal Breakwater = fished # - Ocean Cove Kelper = fished? # - Pier 400 = fished # + ## Clean locationRemarks occ['locationRemarks'] = occ['locationRemarks'].replace({'MPA':'marine protected area', 'REF':'fished area', np.nan:'fished area', 'MPA/REF':'marine protected area'}) occ.loc[occ['locality'].isin(['Cayucos', 'Hurricane Ridge', 'LA Federal Breakwater', 'Ocean Cove Kelper', 'Pier 400']), 'locationRemarks'] = 'fished area' occ['locationRemarks'].unique() # + ## Add coordinateUncertainty in Meters occ['coordinateUncertaintyInMeters'] = 250 # + ## Add occurrenceID occ['occurrenceID'] = data.groupby(['Site', 'SurveyDate'])['Classcode'].cumcount()+1 occ['occurrenceID'] = occ['eventID'] + '_occ' + occ['occurrenceID'].astype(str) occ.head() # + ## Get unique common names names = data['Classcode'].unique() names # + ## Load species table to obtain scientific names filename = 'RCCA_invertebrate_lookup_table.csv' species = pd.read_csv(filename, encoding='ansi') print(species.shape) species.head() # + ## Map scientific names to classcodes and create scientificName # Create scientific name column in species species['scientificName'] = species['Genus'] + ' ' + species['Species'] # Map scientific names to classcodes subset = species[species['Classcode'].isin(names)].copy() code_to_species_dict = dict(zip(subset['Classcode'], subset['scientificName'])) # Add missing code code_to_species_dict['unknown abalone'] = 'Haliotis' # Fix misspellings code_to_species_dict['black abalone'] = 'Haliotis cracherodii' # Create scientificName occ['scientificName'] = data['Classcode'] occ['scientificName'].replace(code_to_species_dict, inplace=True) # Strip any whitespace occ['scientificName'] = occ['scientificName'].str.strip() occ.head() # + ## Match species in WoRMS name_id_dict, name_name_dict, name_taxid_dict, name_class_dict = WoRMS.run_get_worms_from_scientific_name(occ['scientificName'].unique(), verbose_flag=True) # + ## Add scientific name-related columns occ['scientificNameID'] = occ['scientificName'] occ['scientificNameID'].replace(name_id_dict, inplace=True) occ['taxonID'] = occ['scientificName'] occ['taxonID'].replace(name_taxid_dict, inplace=True) occ.head() # + ## Add vernacularName occ.insert(9, 'vernacularName', data['Classcode']) occ.head() # + ## Add final name-related columns occ['nameAccordingTo'] = 'WoRMS' occ['occurrenceStatus'] = 'present' occ['basisOfRecord'] = 'HumanObservation' occ.head() # + ## Add depth # Add eventID column to data data['eventID'] = occ['eventID'] # Aggregate data to handle different transects with different depths depth = data.groupby(['eventID']).agg({'Depth_ft':[min, max]}) depth.reset_index(inplace=True) depth.columns = depth.columns.droplevel() depth.rename(columns={'':'eventID'}, inplace=True) # Join occ = occ.merge(depth, how='left', on='eventID') occ.rename(columns={'min':'minimumDepthInMeters', 'max':'maximumDepthInMeters'}, inplace=True) # Convert from feet to meters occ['minimumDepthInMeters'] = round(occ['minimumDepthInMeters']*0.3048, 1) occ['maximumDepthInMeters'] = round(occ['maximumDepthInMeters']*0.3048, 1) occ.head() # - # **Note** that there are 326 records where depth was not available. # # ```python # cc[occ['minimumDepthInMeters'].isna() == True] # ``` # # ## Save # + ## Save occ.to_csv('RCCA_abalone_size_occurrence_20210212.csv', index=False, na_rep='NaN') # - # ## Create MoF # # I can include abalone sizes, temperature and visibility in MoF. # + ## Add eventID, occurrenceID and size mof = pd.DataFrame({'eventID':occ['eventID']}) mof['occurrenceID'] = occ['occurrenceID'] mof['measurementType'] = 'diameter' mof['measurementValue'] = data['Size'] mof['measurementUnit'] = 'centimeters' mof['measurementMethod'] = 'measured with calipers to the nearest millimeter; rounded to the nearest centimeter if prior to 2015 or south of San Francisco' print(mof.shape) mof.head() # + ## Group temperature and visibility to event level (NOTE that there are different visibility measures for one event, but not for temperature) # Aggregate (using np.mean) event_mof = data.groupby(['eventID']).agg({ 'Temp10m':[lambda x: round(np.mean(x), 1)], 'Visibility':[lambda x: round(np.mean(x), 0)] }) # Tidy event_mof.reset_index(inplace=True) event_mof.columns = event_mof.columns.droplevel() event_mof.columns = ['eventID', 'Temp10m_mean', 'Visibility_mean'] event_mof.head() # + ## Add temperature temp = pd.DataFrame({'eventID':event_mof['eventID']}) temp['occurrenceID'] = np.nan temp['measurementType'] = 'temperature' temp['measurementValue'] = event_mof['Temp10m_mean'] temp['measurementUnit'] = 'degrees Celsius' temp['measurementMethod'] = 'measured by dive computer at 10 m depth, or at the seafloor if shallower than 10 m' # Drop events that lack temperature data temp.dropna(subset=['measurementValue'], inplace=True) temp.head() # + ## Add visibility vis = pd.DataFrame({'eventID':event_mof['eventID']}) vis['occurrenceID'] = np.nan vis['measurementType'] = 'average visibility' vis['measurementValue'] = event_mof['Visibility_mean'] vis['measurementUnit'] = 'meters' vis['measurementMethod'] = 'determined by divers by measuring the distance from which the fingers on a hand held up into the water column can be counted accurately' # Drop events that lack visibility data (32 events) vis.dropna(subset=['measurementValue'], inplace=True) vis.head() # - # **Note** that there are 295 events where multiple visibility measures were reported. I've averaged them here. # # ```python # out = vis.groupby('eventID')['measurementValue'].nunique() # out[out > 1] # # # View a specific example # data[data['eventID'] == 'AlbionCove_20190504'] # ``` # + ## Concatenate mof = pd.concat([mof, temp, vis]) print(mof.shape) mof.head() # + ## Replace NaN with '' in string fields mof['occurrenceID'] = mof['occurrenceID'].replace(np.nan, '') mof.isna().sum() # - # ## Save # + ## Save mof.to_csv('RCCA_abalone_size_MoF_20210212.csv', index=False, na_rep='NaN') # - # ## Questions # # 1. Verify that for these surveys, abalone can be found anywhere in the site (not just on transect). **From Dan: First when we do kelp forest monitoring invert transects we count and size all species of abalone to the nearest cm. Though many times the abalone is back in crack and can’t be measured but we still count it for density. We have been doing these surveys since 2006. In 2016 we started doing additional abalone size-frequency surveys for just red abalone, just north of the golden gate, using specialized calipers that measure to the nearest mm.** # 2. I thought this was only supposed to be for red abalone. When did you start tracking other species? **See the above response. Dan says that even though some abalone are found during transects, it's probably OK to exclude transect numbers for this data set. THIS LIKELY HAS THE SAME DUPLICATED RECORDS ISSUE AS THE PISCO DATA, WHERE AN INDIVIDUAL ABALONE CAN APPEAR TWICE: ONCE IN THE TRANSECT DATA AND ONCE IN THE SIZE-FREQUENCY DATA. HOW IMPORTANT IS THIS? DO I NEED TO DEAL WITH IT?** # 3. Verify that the widest width of the shell is what's measured. What if there are fewer than 250 abalone at a site? Is there a search time associated with this survey type (especially if the survey is done independently of other transect-based surveys)? **Yes, the widest width is measured. There is not really a rigorously monitored search time associated with these surveys. During the red abalone surveys that started in 2016, they just try to measure as many as they can, and usually get a good number, although this is getting harder. Last year (2019) they averaged 100 individuals per survey.** # 4. Some records are missing latitude and longitude, even though these are known and provided for other records from the same site. # 5. Note that there were some surveys where visibility values differed by transect. I've averaged these for the MoF file. # # ## Find number of years each MPA was surveyed surveys_per_year = data.groupby(['Site', 'Year'], as_index=False)['SurveyDate'].nunique() # 1, 2, or 4, mode=1 sites_and_years = data[['Site', 'Year']].drop_duplicates() merged = sites_and_years.merge(sites.loc[sites['CA_MPA_Name_Short'].isna() == False, ['Site', 'CA_MPA_Name_Short']], how='left', on='Site') merged = merged[merged['CA_MPA_Name_Short'].isna() == False] num_years_per_site = merged.groupby(['CA_MPA_Name_Short', 'Site'], as_index=False)['Year'].nunique() num_sites_per_mpa = merged.groupby('CA_MPA_Name_Short', as_index=False)['Site'].nunique() # 1-4, mode=1 num_years_per_mpa = merged.groupby('CA_MPA_Name_Short', as_index=False)['Year'].nunique() num_years_per_mpa = num_years_per_mpa.sort_values('CA_MPA_Name_Short') num_years_per_mpa.to_csv('rcca_abalone_size_years_per_mpa.csv', index=False)
Reef Check/ReefCheck_abalone_size_conversion.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import random my_recs = [] fasta_sequences = SeqIO.parse(open("seqs.fa"),'fasta') for fasta in fasta_sequences: name, sequence = fasta.id, str(fasta.seq) print(name) print(sequence) # - #
lab02/Lab_2/Lab 2 BLAST.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Working with MODFLOW-NWT v 1.1 option blocks # # In MODFLOW-NWT an option block is present for the WEL file, UZF file, and SFR file. This block takes keyword arguments that are supplied in an option line in other versions of MODFLOW. # # The `OptionBlock` class was created to provide combatibility with the MODFLOW-NWT option block and allow the user to easily edit values within the option block # + import os import sys import platform try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy from flopy.utils import OptionBlock print(sys.version) print('flopy version: {}'.format(flopy.__version__)) # - load_ws = os.path.join("..", "data", "options", "sagehen") model_ws = os.path.join("temp", "nwt_options", "output") # ## Loading a MODFLOW-NWT model that has option block options # # It is critical to set the `version` flag in `flopy.modflow.Modflow.load()` to `version='mfnwt'` # # We are going to load a modified version of the Sagehen test problem from GSFLOW to illustrate compatibility # + mfexe = "mfnwt" if platform.system() == 'Windows': mfexe += '.exe' ml = flopy.modflow.Modflow.load('sagehen.nam', model_ws=load_ws, exe_name=mfexe, version='mfnwt') ml.change_model_ws(new_pth=model_ws) ml.write_input() success, buff = ml.run_model(silent=True) if not success: print ('Something bad happened.') # - # ## Let's look at the options attribute of the UZF object # # The `uzf.options` attribute is an `OptionBlock` object. The representation of this object is the option block that will be written to output, which allows the user to easily check to make sure the block has the options they want. uzf = ml.get_package("UZF") uzf.options # The `OptionBlock` object also has attributes which correspond to the option names listed in the online guide to modflow # # The user can call and edit the options within the option block print(uzf.options.nosurfleak) print(uzf.options.savefinf) uzf.options.etsquare = False uzf.options uzf.options.etsquare = True uzf.options # ### The user can also see the single line representation of the options uzf.options.single_line_options # ### And the user can easily change to single line options writing # + uzf.options.block = False # write out only the uzf file uzf_name = "uzf_opt.uzf" uzf.write_file(os.path.join(model_ws, uzf_name)) # - # Now let's examine the first few lines of the new UZF file f = open(os.path.join(model_ws, uzf_name)) for ix, line in enumerate(f): if ix == 3: break else: print(line) # And let's load the new UZF file uzf2 = flopy.modflow.ModflowUzf1.load(os.path.join(model_ws, uzf_name), ml, check=False) # ### Now we can look at the options object, and check if it's block or line format # # `block=False` indicates that options will be written as line format print(uzf2.options) print(uzf2.options.block) # ### Finally we can convert back to block format # + uzf2.options.block = True uzf2.write_file(os.path.join(model_ws, uzf_name)) ml.remove_package("UZF") uzf3 = flopy.modflow.ModflowUzf1.load(os.path.join(model_ws, uzf_name), ml, check=False) print("\n") print(uzf3.options) print(uzf3.options.block) # - # ## We can also look at the WEL object wel = ml.get_package("WEL") wel.options # Let's write this out as a single line option block and examine the first few lines # + wel_name = "wel_opt.wel" wel.options.block = False wel.write_file(os.path.join(model_ws, wel_name)) f = open(os.path.join(model_ws,wel_name)) for ix, line in enumerate(f): if ix == 4: break else: print(line) # - # And we can load the new single line options WEL file and confirm that it is being read as an option line # + ml.remove_package("WEL") wel2 = flopy.modflow.ModflowWel.load(os.path.join(model_ws, wel_name), ml, nper=ml.nper, check=False) wel2.options wel2.options.block # - # # Building an OptionBlock from scratch # # The user can also build an `OptionBlock` object from scratch to add to a `ModflowSfr2`, `ModflowUzf1`, or `ModflowWel` file. # # The `OptionBlock` class has two required parameters and one optional parameter # # `option_line`: a one line, string based representation of the options # # `package`: a modflow package object # # `block`: boolean flag for line based or block based options opt_line = "specify 0.1 20" options = OptionBlock(opt_line, flopy.modflow.ModflowWel, block=True) options # from here we can set the noprint flag by using `options.noprint` options.noprint = True # and the user can also add auxillary variables by using `options.auxillary` options.auxillary = ["aux", "iface"] # ### Now we can create a new wel file using this `OptionBlock` # # and write it to output # + wel3 = flopy.modflow.ModflowWel(ml, stress_period_data=wel.stress_period_data, options=options, unitnumber=99) wel3.write_file(os.path.join(model_ws, wel_name)) # - # And now let's examine the first few lines of the file f = open(os.path.join(model_ws, wel_name)) for ix, line in enumerate(f): if ix == 8: break else: print(line) # We can see that everything that the OptionBlock class writes out options in the correct location. # ### The user can also switch the options over to option line style and write out the output too! # + wel3.options.block = False wel3.write_file(os.path.join(model_ws, wel_name)) f = open(os.path.join(model_ws, wel_name)) for ix, line in enumerate(f): if ix == 6: break else: print(line) # -
examples/Notebooks/flopy3_nwt_options.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## Malaria Detection using Convolutional Neural Networks # import the necessary libraries import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import keras from keras.models import Sequential from keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout , BatchNormalization from keras.preprocessing.image import ImageDataGenerator from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report,confusion_matrix from keras.callbacks import ReduceLROnPlateau import cv2 from keras.models import load_model # ### Load the dataset labels = ['parasite', 'normal'] img_size = 150 def fetch(data_dir): data = [] for label in labels: path = os.path.join(data_dir, label) class_num = labels.index(label) for img in os.listdir(path): try: img_arr = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) resized_arr = cv2.resize(img_arr, (img_size, img_size)) data.append([resized_arr, class_num]) except Exception as e: print(e) return np.array(data) # ### Get the train and test dataset train = fetch('dataset/train') test = fetch('dataset/test') # ### See Malaria Data malaria_infected = os.listdir('dataset/train/parasite') malaria_dir = 'dataset/train/parasite' normal = os.listdir('dataset/test/normal') normal_dir = 'dataset/test/normal' # ### Visualize the image # - Infected Image plt.figure(figsize = (20,10)) for i in range(9): plt.subplot(3, 3, i+1) img = plt.imread(os.path.join(malaria_dir, malaria_infected[i])) plt.imshow(img, cmap='gray') plt.title('Malaria infection image') plt.show() # - Normal Image plt.figure(figsize = (20,10)) for i in range(9): plt.subplot(3, 3, i+1) img = plt.imread(os.path.join(normal_dir, normal[i])) plt.imshow(img, cmap='gray') plt.title('Normal Image') plt.show() # ### Closer look to both normal and infected # ### Malaria Infected plt.figure(figsize = (6,6)) plt.imshow(train[0][0],cmap='gray') plt.title(labels[train[0][1]]) # ### Normal plt.figure(figsize = (6,6)) plt.imshow(train[-1][0], cmap='gray') plt.title(labels[train[-1][1]]) # ### Count plot of the individual datapoints counter = [] for i in train: if (i[1] == 0): counter.append('parasite') else: counter.append('normal') sns.set_style('darkgrid') sns.countplot(counter) # ### Preprocessing the data # + x_train = [] y_train = [] x_test = [] y_test = [] for feature, label in train: x_train.append(feature) y_train.append(label) for feature, label in test: x_test.append(feature) y_test.append(label) # - # ### Normalization of the data # + x_train = np.array(x_train)/255 x_train = x_train.reshape(-1, img_size, img_size, 1) y_train = np.array(y_train) x_test = np.array(x_test)/255 x_test = x_test.reshape(-1, img_size, img_size, 1) y_test = np.array(y_test) # - # ### Training with CNN # + model = Sequential() model.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu' , input_shape = (150,150,1))) model.add(BatchNormalization()) model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same')) model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu')) model.add(Dropout(0.1)) model.add(BatchNormalization()) model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same')) model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu')) model.add(BatchNormalization()) model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same')) model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu')) model.add(Dropout(0.2)) model.add(BatchNormalization()) model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same')) model.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu')) model.add(Dropout(0.2)) model.add(BatchNormalization()) model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same')) model.add(Flatten()) model.add(Dense(units = 128 , activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(units = 1 , activation = 'sigmoid')) model.compile(optimizer = "rmsprop" , loss = 'binary_crossentropy' , metrics = ['accuracy']) model.summary() # - rate_reduction = ReduceLROnPlateau(monitor='accuracy', patience = 2, verbose=1,factor=0.3, min_lr=0.000001) history = model.fit(x_train,y_train, batch_size = 32 ,epochs = 16 ,callbacks = [rate_reduction]) # ### Loss and the accuracy score = model.evaluate(x_train, y_train, verbose = 0) print('Train loss:', score[0]) print('Train accuracy:', score[1]) score = model.evaluate(x_test, y_test, verbose = 0) print('Train loss:', score[0]) print('Train accuracy:', score[1]) # ### Visualization of loss and accuracy plt.figure(figsize = (15,10)) plt.plot(history.history['loss']) plt.plot(history.history['accuracy']) plt.title('Model Loss vs accuracy') plt.ylabel('Loss vs accuracy') plt.xlabel('Epoch') plt.legend(['Accuracy', 'Loss'], loc='upper right') plt.show() # ### Model Prediction and analysis y_pred = model.predict(x_test) y_pred = np.round(y_pred).astype(int).reshape(-1) # ### Classification report print(classification_report(y_test, y_pred, target_names = ['Infected','Normal'])) # ### Confusion matrix cm = confusion_matrix(y_test,y_pred) cm cm = pd.DataFrame(cm , index = ['0','1'] , columns = ['0','1']) plt.figure(figsize = (10,10)) sns.heatmap(cm,cmap= "BrBG", linecolor = 'black' , linewidth = 1 , annot = True, fmt='',xticklabels = labels,yticklabels = labels) correct = np.nonzero(y_pred == y_test)[0] incorrect = np.nonzero(y_pred != y_test)[0] # ### Correctly predicted i = 0 for c in correct[:6]: plt.subplot(4,2,i+1) plt.xticks([]) plt.yticks([]) plt.imshow(x_test[c].reshape(150,150), cmap="gray", interpolation='none') plt.title("Predicted Class {},Actual Class {}".format(y_pred[c], y_test[c])) plt.tight_layout() i += 1 # ### Incorrect Prediction i = 0 for c in incorrect[:6]: plt.subplot(4,2,i+1) plt.xticks([]) plt.yticks([]) plt.imshow(x_test[c].reshape(150,150), cmap="gray", interpolation='none') plt.title("Predicted Class {},Actual Class {}".format(y_pred[c], y_test[c])) plt.tight_layout() i += 1
notebooks/Malaria-Detection-Deep-Learning-CNN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys, os, hashlib from collections import OrderedDict as od def getHashSums(file_path): hashSums = od() hashSums['md5sum'] = hashlib.md5() hashSums['sha1sum'] = hashlib.sha1() hashSums['sha224sum'] = hashlib.sha224() hashSums['sha256sum'] = hashlib.sha256() hashSums['sha384sum'] = hashlib.sha384() hashSums['sha512sum'] = hashlib.sha512() with open(file_path, 'rb') as fd: dataChunk = fd.read(1024) while dataChunk: for hashsum in hashSums.keys(): hashSums[hashsum].update(dataChunk) dataChunk = fd.read(1024) results = od() for key,value in hashSums.items(): results[key] = value.hexdigest() return results for i in range(1, 115): print("sore", i, " checksum : ") for key,value in getHashSums("data/clean-aya/" + str(i) + ".txt").items(): print(key,value) print("") for i in range(1, 115): print("sore", i, " checksum : ") for key,value in getHashSums("data/quran-aya/" + str(i) + ".txt").items(): print(key,value) print("") for i in range(1, 115): print("sore", i, " checksum : ") for key,value in getHashSums("data/uthmani-aya/" + str(i) + ".txt").items(): print(key,value) print("")
checksum-quran-aya.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Ideas on Serial Path Discovering (Jan 14) # This is the continuation of 2010-01-12-jgil-Ideas. # + import random import networkx as nx import matplotlib.pyplot as plt import pandas as pd import sys sys.path.append("../../") from src.models.synthetic_logs import * # - # ## Functions def get_successor_pairs_by_freq( traces, sensitivity=-1 ): pairs_by_freq = {} for trace in traces: for pair in get_successor_pairs(trace): if pair in pairs_by_freq.keys(): pairs_by_freq[pair] = pairs_by_freq[pair] + 1 else: pairs_by_freq[pair] = 1 return pairs_by_freq def get_successor_pairs( this_trace ): pairs = [] for idx in range(0, len(this_trace)-1): partial_subtrace = this_trace[idx:] # For every s_i in s_0...s_i...partial_subtrace s_i = partial_subtrace.pop(0) # Find first K+1 such s_i == s_(k+1) try: k_plus_1 = partial_subtrace.index(s_i) except: k_plus_1 = len(partial_subtrace) # This is the subtrace T, the maximal that not contains s0 T=partial_subtrace[:k_plus_1] # Collect all (s_i, s_k) with i < k < k+1: for s_k in T: e = (s_i, s_k) pairs.append(e) return pairs def cluster_same_freq(pairs_dic, threshold=0): freq = list(set(pairs_dic.values())) groups = {} for pair in pairs_dic.keys(): f = pairs_dic[pair] if f in groups.keys(): groups[f].append( pair ) else: groups[f] = [ pair ] return groups # + def get_serial_paths( data, minfreq=0, minsymbols=4): if len(data) == 0: return [] # Case: pairs elif type(data[0]) == type((1,1)): pairs = data paths = [] G = nx.DiGraph() G.add_edges_from( pairs ) # Search cliques G_prime=nx.to_undirected(G) for V in nx.algorithms.clique.find_cliques(G_prime): if len(V) > CLIQUE_THRESHOLD: # Create complete graph from clique G_complete = G.copy() for node in set(G_complete.nodes).difference( set(V) ): G_complete.remove_node(node) # Order nodes by outer degree nodes = sorted( G_complete.out_degree() , key=lambda p: p[1], reverse=True) # Strict checking of outer_degree i=len(nodes) put = True for a, outdeg in nodes: i -= 1 if outdeg != i: put = False if put: paths.append ( [ a for a,b in nodes ] ) return paths # Case: set of traces # elif type(data[0]) == type([]): # print( len(data)) # combined = [] # for trace in data: # combined = combined + get_successor_pairs(trace) # print(len(combined)) # return get_serial_paths(combined) elif type(data[0]) == type([]): cluster = cluster_same_freq( get_successor_pairs_by_freq(data) ) paths = {} for f in cluster.keys(): if f >= minfreq: p = [] for X in get_serial_paths( cluster[f] ): if len(X) >= minsymbols: p.append(X) if len(p) > 0: paths[f] = p return paths # - # ## Succesor pairs # Given $ N $ finite integer and a trace $T=s_0 ... s_i ... s_k ... s_j ... s_N$, count $s_i$ get successors pairs with the form $(s_i, s_k)$ such that $0 \le i < k \le j \le N$ and with $j$ maximal such that holds $s_k \neq s_i$. Those pairs preserves the order of appearance and discards loops by construction. # ### Examples get_successor_pairs(list("A")) get_successor_pairs(list("AB")) get_successor_pairs(list("ABCD")) get_successor_pairs(list("ABCABCABC")) # ### Succesors pairs in a trace # If given a set of traces $\overline{T} = \{T_0, ...., T_M\}$, is useful to have the successor combining all the traces and separate them by its frequency of apparition. # # Note that this is *not* equivalent to have all the traces concatenated, because some extra pairs will appear in the concatenation. T = [ list("ABC"), list("ABCABC"), ] get_successor_pairs_by_freq(T) # Another view of this data is to have the successor pairs grouped by frecuency cluster_same_freq( get_successor_pairs_by_freq(T) ) # ## Equivalent Graph of Serial Path representation # If we assume that the traces are complete in the sense that it contains entire serial paths, then a directed graph can be constructed $G_{freq}=(V_{freq},E_{freq})$ with all successor pairs $E_{freq}$ of the same frequency group, and vertex set $v \in V_{freq}$ iff $ (u, v) \in E_{freq}$ or $(v, u) \in E_{freq}$ for some $u \in V_{freq}$. By construction of successor pairs it's true that: # # i) the path $S=s_1...s_L$ of length $L$ exists in $G_{freq}$, # # ii) if $(s_i, s_{i+1}), (s_j, s_{j+1}) \in S$ from some $0 \le i < j \le L$, then $(s_i, s_j), (s_i, s_{j+1}), (s_{i+1}, s_j), (s_{i+1}, s_{j+1}) \in E_{freq}$ # # iii) Any subset of vertex of $S$ is also a valid path, then the goal is to search the **maximal** serial path $S$ sharing the same nodes. # # From *ii)* it follows that the equivalent undirected graph $G'_{freq}=(V,E)$ is complete. To reconstruct $S$, the *outer degree* of each node (how many edges goes from node) can be used: $outdeg(s_i) < outdeg(s_j)$ for all $0 \le i < j \le L$. # For example, the path ```ABCD``` forms the following pairs G = nx.DiGraph() G.add_edges_from( get_successor_pairs(list("ABCD")) ) G.edges() # The following images shows a progression of graphs with different size G = nx.DiGraph() G.add_edges_from( get_successor_pairs(list("ABCD")) ) nx.draw_circular(G, with_labels=True) G = nx.DiGraph() G.add_edges_from( get_successor_pairs(list("ABCDEF")) ) nx.draw_circular(G, with_labels=True) # ## Extending Graph # Be $G=(V,E)$ a graph containing $G_{freq}$, i.e. with $V_{freq} \subset V, E_{freq} \subset E$. Given the fact that $G'_{freq}$ is complete, it follows that the undirected graph $G'=(V,E)$ has at least one **clique** of size $|V_{freq}|$ made by $V_{freq}$. And from *iii)* above, the cliques must be maximal. # # (See https://en.wikipedia.org/wiki/Clique_(graph_theory) and https://www.geeksforgeeks.org/operations-on-graph-and-special-graphs-using-networkx-module-python/ ) # ### Example: few extra edges # In the examples below, a CLIQUE_THRESHOLD is set to avoid subgraphs composed by a single edge. CLIQUE_THRESHOLD=2 # + S = list("ABCDEFGHIJK") S_pairs = get_successor_pairs(S) + [ ("w", "z"), ("B", "y"), ("z", "A") ] G = nx.DiGraph() G.add_edges_from( S_pairs ) nx.draw_circular(G, with_labels=True) # + V_unordered = [] # Search cliques G_prime=nx.to_undirected(G) for i in nx.algorithms.clique.find_cliques(G_prime): if len(i) > CLIQUE_THRESHOLD: print( "size=%3d: %s" %(len(i), i)) V_unordered.append(i) # Iterate over cliques for V in V_unordered: # Create complete graph from clique G_complete = G.copy() for node in set(G_complete.nodes).difference( set(V) ): G_complete.remove_node(node) nodes = sorted( G_complete.out_degree() , key=lambda p: p[1], reverse=True) print(nodes) S_reconstructed = [ a for a,b in nodes ] print( "".join(S_reconstructed) ) nx.draw_circular(G_complete, with_labels=True) # - # Same functionality with a function pairs = get_successor_pairs(list("ABCDEFGHIJK")) + [ ("w", "z"), ("B", "y"), ("z", "A") ] get_serial_paths( pairs ) # ### Example: random tails T = [ list("ABCD1"), list("ABCD12"), list("ABCD23"), list("ABCD1268"), list("ABCD841"), ] get_serial_paths( T, minfreq=1 ) # ### Example: random noise T = [ list("A1B2CDE"), list("2AB1CDE"), list("3AB5CD9E"), list("ABCDE7"), list("A1BC8DE1"), ] get_serial_paths( T, minfreq=1 ) get_serial_paths( T, minfreq=2 ) # ### Example: similar paths (if then) # *Emerging property*... this resembles the if-then cycle T = [ list("ABCDE01234"), list("ABCDE5678") ] get_serial_paths( T, minfreq=1 ) T = [ list("ABCDE01234"), list("ABCDE01234"), list("ABCDE5678"), list("ABCDE5678") ] get_serial_paths( T, minfreq=1 ) T = [ list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE5678"), list("ABCDE5678"), list("ABCDE5678") ] get_serial_paths( T, minfreq=1 ) T = [ list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE5678"), list("ABCDE5678") ] get_serial_paths( T, minfreq=1 ) T = [ list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE01234"), list("ABCDE5678") ] get_serial_paths( T, minfreq=1 ) T = [ list("ABC123456"), list("ABC123456"), list("ABC123789"), list("ABC123789"), list("ABCWXYZ"), list("ABCWXYZ"), ] get_serial_paths( T, minfreq=1 ) # ### Example: repeated traces (loops) # Strange example... with repetitions in the same trace the serial path appears inverted ```DCBA``` ... **did I found loops by mistake??** T = [ list("ABCD"), list("ABCDABCD"), list("ABCDABCDABCD"), list("EFGHI"), list("EFGHIABCD"), list("EFGHIEFGHIEFGHIEFGHI"), ] get_serial_paths( T, minfreq=2 ) # ## Dataset play # ### Serial with some noise # + logs = synthetic_logs() logs.add( noisy_path( every=10, num_symbols=10, count=20) ) logs.add( serial_path( size=7, every=25, error=5, probability=1) ) instances = logs.generate_instances(100) logs.show_instances(3) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq= 5 ) # ### Shuffled serials, equal appearance # + # Very unordered series has... far better results!! logs = synthetic_logs() logs.add( serial_path( size=7, every=25, error=15, probability=1) ) logs.add( serial_path( size=7, every=25, error=15, probability=1) ) instances = logs.generate_instances(100) logs.show_instances(5) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq=5 ) # ### Merged serials, unbalanced # + logs = synthetic_logs() logs.add( serial_path( size=7, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=7, every=25, error=5, probability=0.9) ) instances = logs.generate_instances(100) logs.show_instances(5) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq=5 ) # ### Merged unbalanced serials plus noise # + logs = synthetic_logs() logs.add( serial_path( size=7, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=7, every=25, error=5, probability=0.9) ) logs.add( noisy_path( every=10, num_symbols=20, count=25) ) instances = logs.generate_instances(100) logs.show_instances(5) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq=5 ) # ### Several unbalanced serials plus noise # + logs = synthetic_logs() logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( noisy_path( every=10, num_symbols=20, count=25) ) instances = logs.generate_instances(100) logs.show_instances(5) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq= 5 ) # ### serials plus noise, but one with P=1 # + logs = synthetic_logs() logs.add( serial_path( size=10, every=25, error=5, probability=1) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( serial_path( size=10, every=25, error=5, probability=0.9) ) logs.add( noisy_path( every=10, num_symbols=20, count=25) ) instances = logs.generate_instances(100) logs.show_instances(5) # - pd.DataFrame(logs.describe()['generators']) traces = [ [ s for (t, s) in serie ] for serie in instances ] get_serial_paths( traces, minfreq= int( len(traces) / 10) ) # ## Conclusions # 1. The algorithm is useful for a len(S) > 3, because the high probability to have the edge set $(s_0, s_1), (s_1, s_2), (s_0, s_1)$, while in contrast, the chances are dramatically lower to have this set in the same frequency range: $(s_0, s_1), (s_1, s_2), (s_2, s_3), (s_0, s_1), (s_0, s_2), (s_0, s_3), (s_1, s_3)$ # 1. Using cliques, the time to get results is quite low # 1. If just one serial path appears, the precision is 100% # 1. When several serial paths are in the same dataset, two cases appears. 1) If each path appears in less than 100% of the instances, they are quite well detected. 2) If at least one path is present in all instances, the detection is good for that one but shows several false positives in the others. # 1. I developed a powerful sample instance generator. # ## Pending tasks # # 1. Add tolerance to incomplete sequences # 1. Test with Observatory logs
notebooks/2-structures/2020-01-14-jgil-Serial-Discovery.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) # # <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/StatisticsProject/AccessingData/climate-monthly.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> # # Monthly Climate Data # # We can get temperature and precipitation data averaged by month for 1901 to 2016 from [World Bank Climate Change Knowledge Portal](https://climateknowledgeportal.worldbank.org). You will need the latitude and longitude of a location from a site such as [latlong.net](https://www.latlong.net). # + latitude = 43.7521 longitude = -79.7614 import pandas as pd temperature_url = 'https://climateknowledgeportal.worldbank.org/api/data/get-download-data/historical/tas/1901-2016/'+str(latitude)+'$cckp$'+str(longitude)+'/'+str(latitude)+'$cckp$'+str(longitude) temperature_all = pd.read_csv(temperature_url) temperature = temperature_all.replace(' Average','',regex=True).replace(' ','',regex=True).rename(columns={'Temperature - (Celsius)':'Temperature (°C)', ' Statistics':'Month'}) precipitation_url = 'https://climateknowledgeportal.worldbank.org/api/data/get-download-data/historical/pr/1901-2016/'+str(latitude)+'$cckp$'+str(longitude)+'/'+str(latitude)+'$cckp$'+str(longitude) precipitation_all = pd.read_csv(precipitation_url) precipitation = precipitation_all.replace(' Average','',regex=True).replace(' ','',regex=True).rename(columns={'Rainfall - (MM)':'Precipitation (mm)', ' Statistics':'Month'}) climate = pd.merge(temperature, precipitation).drop(columns=[' Longitude',' Latitude']) climate # - # [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
_build/html/_sources/curriculum-notebooks/Mathematics/StatisticsProject/AccessingData/climate-monthly.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Emojify! # # Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. # # Have you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. # So rather than writing: # >"Congratulations on the promotion! Let's get coffee and talk. Love you!" # # The emojifier can automatically turn this into: # >"Congratulations on the promotion! 👍 Let's get coffee and talk. ☕️ Love you! ❤️" # # * You will implement a model which inputs a sentence (such as "Let's go see the baseball game tonight!") and finds the most appropriate emoji to be used with this sentence (⚾️). # # #### Using word vectors to improve emoji lookups # * In many emoji interfaces, you need to remember that ❤️ is the "heart" symbol rather than the "love" symbol. # * In other words, you'll have to remember to type "heart" to find the desired emoji, and typing "love" won't bring up that symbol. # * We can make a more flexible emoji interface by using word vectors! # * When using word vectors, you'll see that even if your training set explicitly relates only a few words to a particular emoji, your algorithm will be able to generalize and associate additional words in the test set to the same emoji. # * This works even if those additional words don't even appear in the training set. # * This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set. # # #### What you'll build # 1. In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings. # 2. Then you will build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM. # ## <font color='darkblue'>Updates</font> # # #### If you were working on the notebook before this update... # * The current notebook is version "2a". # * You can find your original work saved in the notebook with the previous version name ("v2") # * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. # # #### List of updates # * sentence_to_avg # * Updated instructions. # * Use separate variables to store the total and the average (instead of just `avg`). # * Additional hint about how to initialize the shape of `avg` vector. # * sentences_to_indices # * Updated preceding text and instructions, added additional hints. # * pretrained_embedding_layer # * Additional instructions to explain how to implement each step. # * Emoify_V2 # * Modifies instructions to specify which parameters are needed for each Keras layer. # * Remind users of Keras syntax. # * Explanation of how to use the layer object that is returned by `pretrained_embedding_layer`. # * Provides sample Keras code. # * Spelling, grammar and wording corrections. # Let's get started! Run the following cell to load the package you are going to use. # + import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt # %matplotlib inline # - # ## 1 - Baseline model: Emojifier-V1 # # ### 1.1 - Dataset EMOJISET # # Let's start by building a simple baseline classifier. # # You have a tiny dataset (X, Y) where: # - X contains 127 sentences (strings). # - Y contains an integer label between 0 and 4 corresponding to an emoji for each sentence. # # <img src="images/data_set.png" style="width:700px;height:300px;"> # <caption><center> **Figure 1**: EMOJISET - a classification problem with 5 classes. A few examples of sentences are given here. </center></caption> # # Let's load the dataset using the code below. We split the dataset between training (127 examples) and testing (56 examples). X_train, Y_train = read_csv('data/train_emoji.csv') X_test, Y_test = read_csv('data/tesss.csv') maxLen = len(max(X_train, key=len).split()) # Run the following cell to print sentences from X_train and corresponding labels from Y_train. # * Change `idx` to see different examples. # * Note that due to the font used by iPython notebook, the heart emoji may be colored black rather than red. for idx in range(10): print(X_train[idx], label_to_emoji(Y_train[idx])) # ### 1.2 - Overview of the Emojifier-V1 # # In this part, you are going to implement a baseline model called "Emojifier-v1". # # <center> # <img src="images/image_1.png" style="width:900px;height:300px;"> # <caption><center> **Figure 2**: Baseline model (Emojifier-V1).</center></caption> # </center> # # # #### Inputs and outputs # * The input of the model is a string corresponding to a sentence (e.g. "I love you). # * The output will be a probability vector of shape (1,5), (there are 5 emojis to choose from). # * The (1,5) probability vector is passed to an argmax layer, which extracts the index of the emoji with the highest probability. # #### One-hot encoding # * To get our labels into a format suitable for training a softmax classifier, lets convert $Y$ from its current shape $(m, 1)$ into a "one-hot representation" $(m, 5)$, # * Each row is a one-hot vector giving the label of one example. # * Here, `Y_oh` stands for "Y-one-hot" in the variable names `Y_oh_train` and `Y_oh_test`: Y_oh_train = convert_to_one_hot(Y_train, C = 5) Y_oh_test = convert_to_one_hot(Y_test, C = 5) # Let's see what `convert_to_one_hot()` did. Feel free to change `index` to print out different values. idx = 50 print(f"Sentence '{X_train[50]}' has label index {Y_train[idx]}, which is emoji {label_to_emoji(Y_train[idx])}", ) print(f"Label index {Y_train[idx]} in one-hot encoding format is {Y_oh_train[idx]}") # All the data is now ready to be fed into the Emojify-V1 model. Let's implement the model! # ### 1.3 - Implementing Emojifier-V1 # # As shown in Figure 2 (above), the first step is to: # * Convert each word in the input sentence into their word vector representations. # * Then take an average of the word vectors. # * Similar to the previous exercise, we will use pre-trained 50-dimensional GloVe embeddings. # # Run the following cell to load the `word_to_vec_map`, which contains all the vector representations. word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('../../readonly/glove.6B.50d.txt') # You've loaded: # - `word_to_index`: dictionary mapping from words to their indices in the vocabulary # - (400,001 words, with the valid indices ranging from 0 to 400,000) # - `index_to_word`: dictionary mapping from indices to their corresponding words in the vocabulary # - `word_to_vec_map`: dictionary mapping words to their GloVe vector representation. # # Run the following cell to check if it works. word = "cucumber" idx = 289846 print("the index of", word, "in the vocabulary is", word_to_index[word]) print("the", str(idx) + "th word in the vocabulary is", index_to_word[idx]) # **Exercise**: Implement `sentence_to_avg()`. You will need to carry out two steps: # 1. Convert every sentence to lower-case, then split the sentence into a list of words. # * `X.lower()` and `X.split()` might be useful. # 2. For each word in the sentence, access its GloVe representation. # * Then take the average of all of these word vectors. # * You might use `numpy.zeros()`. # # # #### Additional Hints # * When creating the `avg` array of zeros, you'll want it to be a vector of the same shape as the other word vectors in the `word_to_vec_map`. # * You can choose a word that exists in the `word_to_vec_map` and access its `.shape` field. # * Be careful not to hard code the word that you access. In other words, don't assume that if you see the word 'the' in the `word_to_vec_map` within this notebook, that this word will be in the `word_to_vec_map` when the function is being called by the automatic grader. # * Hint: you can use any one of the word vectors that you retrieved from the input `sentence` to find the shape of a word vector. # + # GRADED FUNCTION: sentence_to_avg def sentence_to_avg(sentence, word_to_vec_map): """ Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: sentence -- string, one training example from X word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation Returns: avg -- average vector encoding information about the sentence, numpy-array of shape (50,) """ ### START CODE HERE ### # Step 1: Split sentence into list of lower case words (≈ 1 line) words = list(map(str.lower, sentence.split())) # Initialize the average word vector, should have the same shape as your word vectors. avg = np.zeros(50) # Step 2: average the word vectors. You can loop over the words in the list "words". total = 0 for w in words: total += word_to_vec_map[w] avg = total/len(words) ### END CODE HERE ### return avg # - avg = sentence_to_avg("Morrocan couscous is my favorite dish", word_to_vec_map) print("avg = \n", avg) # **Expected Output**: # # ```Python # avg = # [-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 # -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 # 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.26037767 # 0.05820667 -0.01578167 -0.12078833 -0.02471267 0.4128455 0.5152061 # 0.38756167 -0.898661 -0.535145 0.33501167 0.68806933 -0.2156265 # 1.797155 0.10476933 -0.36775333 0.750785 0.10282583 0.348925 # -0.27262833 0.66768 -0.10706167 -0.283635 0.59580117 0.28747333 # -0.3366635 0.23393817 0.34349183 0.178405 0.1166155 -0.076433 # 0.1445417 0.09808667] # ``` # #### Model # # You now have all the pieces to finish implementing the `model()` function. # After using `sentence_to_avg()` you need to: # * Pass the average through forward propagation # * Compute the cost # * Backpropagate to update the softmax parameters # # **Exercise**: Implement the `model()` function described in Figure (2). # # * The equations you need to implement in the forward pass and to compute the cross-entropy cost are below: # * The variable $Y_{oh}$ ("Y one hot") is the one-hot encoding of the output labels. # # $$ z^{(i)} = W . avg^{(i)} + b$$ # # $$ a^{(i)} = softmax(z^{(i)})$$ # # $$ \mathcal{L}^{(i)} = - \sum_{k = 0}^{n_y - 1} Y_{oh,k}^{(i)} * log(a^{(i)}_k)$$ # # **Note** It is possible to come up with a more efficient vectorized implementation. For now, let's use nested for loops to better understand the algorithm, and for easier debugging. # # We provided the function `softmax()`, which was imported earlier. # + # GRADED FUNCTION: model def model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 400): """ Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation learning_rate -- learning_rate for the stochastic gradient descent algorithm num_iterations -- number of iterations Returns: pred -- vector of predictions, numpy-array of shape (m, 1) W -- weight matrix of the softmax layer, of shape (n_y, n_h) b -- bias of the softmax layer, of shape (n_y,) """ np.random.seed(1) # Define number of training examples m = Y.shape[0] # number of training examples n_y = 5 # number of classes n_h = 50 # dimensions of the GloVe vectors # Initialize parameters using Xavier initialization W = np.random.randn(n_y, n_h) / np.sqrt(n_h) b = np.zeros((n_y,)) # Convert Y to Y_onehot with n_y classes Y_oh = convert_to_one_hot(Y, C = n_y) # Optimization loop for t in range(num_iterations): # Loop over the number of iterations for i in range(m): # Loop over the training examples ### START CODE HERE ### (≈ 4 lines of code) # Average the word vectors of the words from the i'th training example avg = sentence_to_avg(X[i], word_to_vec_map) # Forward propagate the avg through the softmax layer z = np.dot(W, avg) + b a = softmax(z) # Compute cost using the i'th training label's one hot representation and "A" (the output of the softmax) cost = -1 * np.sum(Y_oh[i] * np.log(a)) ### END CODE HERE ### # Compute gradients dz = a - Y_oh[i] dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h)) db = dz # Update parameters with Stochastic Gradient Descent W = W - learning_rate * dW b = b - learning_rate * db if t % 100 == 0: print("Epoch: " + str(t) + " --- cost = " + str(cost)) pred = predict(X, Y, W, b, word_to_vec_map) #predict is defined in emo_utils.py return pred, W, b # + print(X_train.shape) print(Y_train.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(X_train[0]) print(type(X_train)) Y = np.asarray([5,0,0,5, 4, 4, 4, 6, 6, 4, 1, 1, 5, 6, 6, 3, 6, 3, 4, 4]) print(Y.shape) X = np.asarray(['I am going to the bar tonight', 'I love you', 'miss you my dear', 'Lets go party and drinks','Congrats on the new job','Congratulations', 'I am so happy for you', 'Why are you feeling bad', 'What is wrong with you', 'You totally deserve this prize', 'Let us go play football', 'Are you down for football this afternoon', 'Work hard play harder', 'It is suprising how people can be dumb sometimes', 'I am very disappointed','It is the best day in my life', 'I think I will end up alone','My life is so boring','Good job', 'Great so awesome']) print(X.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(type(X_train)) # - # Run the next cell to train your model and learn the softmax parameters (W,b). pred, W, b = model(X_train, Y_train, word_to_vec_map) print(pred) # **Expected Output** (on a subset of iterations): # # <table> # <tr> # <td> # **Epoch: 0** # </td> # <td> # cost = 1.95204988128 # </td> # <td> # Accuracy: 0.348484848485 # </td> # </tr> # # # <tr> # <td> # **Epoch: 100** # </td> # <td> # cost = 0.0797181872601 # </td> # <td> # Accuracy: 0.931818181818 # </td> # </tr> # # <tr> # <td> # **Epoch: 200** # </td> # <td> # cost = 0.0445636924368 # </td> # <td> # Accuracy: 0.954545454545 # </td> # </tr> # # <tr> # <td> # **Epoch: 300** # </td> # <td> # cost = 0.0343226737879 # </td> # <td> # Accuracy: 0.969696969697 # </td> # </tr> # </table> # Great! Your model has pretty high accuracy on the training set. Lets now see how it does on the test set. # ### 1.4 - Examining test set performance # # * Note that the `predict` function used here is defined in emo_util.spy. print("Training set:") pred_train = predict(X_train, Y_train, W, b, word_to_vec_map) print('Test set:') pred_test = predict(X_test, Y_test, W, b, word_to_vec_map) # **Expected Output**: # # <table> # <tr> # <td> # **Train set accuracy** # </td> # <td> # 97.7 # </td> # </tr> # <tr> # <td> # **Test set accuracy** # </td> # <td> # 85.7 # </td> # </tr> # </table> # * Random guessing would have had 20% accuracy given that there are 5 classes. (1/5 = 20%). # * This is pretty good performance after training on only 127 examples. # # # #### The model matches emojis to relevant words # In the training set, the algorithm saw the sentence # >"*I love you*" # # with the label ❤️. # * You can check that the word "adore" does not appear in the training set. # * Nonetheless, lets see what happens if you write "*I adore you*." # # # + X_my_sentences = np.array(["i adore you", "i love you", "funny lol", "lets play with a ball", "food is ready", "not feeling happy"]) Y_my_labels = np.array([[0], [0], [2], [1], [4],[3]]) pred = predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map) print_predictions(X_my_sentences, pred) # - # Amazing! # * Because *adore* has a similar embedding as *love*, the algorithm has generalized correctly even to a word it has never seen before. # * Words such as *heart*, *dear*, *beloved* or *adore* have embedding vectors similar to *love*. # * Feel free to modify the inputs above and try out a variety of input sentences. # * How well does it work? # # #### Word ordering isn't considered in this model # * Note that the model doesn't get the following sentence correct: # >"not feeling happy" # # * This algorithm ignores word ordering, so is not good at understanding phrases like "not happy." # # #### Confusion matrix # * Printing the confusion matrix can also help understand which classes are more difficult for your model. # * A confusion matrix shows how often an example whose label is one class ("actual" class) is mislabeled by the algorithm with a different class ("predicted" class). print(Y_test.shape) print(' '+ label_to_emoji(0)+ ' ' + label_to_emoji(1) + ' ' + label_to_emoji(2)+ ' ' + label_to_emoji(3)+' ' + label_to_emoji(4)) print(pd.crosstab(Y_test, pred_test.reshape(56,), rownames=['Actual'], colnames=['Predicted'], margins=True)) plot_confusion_matrix(Y_test, pred_test) # # ## What you should remember from this section # - Even with a 127 training examples, you can get a reasonably good model for Emojifying. # - This is due to the generalization power word vectors gives you. # - Emojify-V1 will perform poorly on sentences such as *"This movie is not good and not enjoyable"* # - It doesn't understand combinations of words. # - It just averages all the words' embedding vectors together, without considering the ordering of words. # # **You will build a better algorithm in the next section!** # ## 2 - Emojifier-V2: Using LSTMs in Keras: # # Let's build an LSTM model that takes word **sequences** as input! # * This model will be able to account for the word ordering. # * Emojifier-V2 will continue to use pre-trained word embeddings to represent words. # * We will feed word embeddings into an LSTM. # * The LSTM will learn to predict the most appropriate emoji. # # Run the following cell to load the Keras packages. import numpy as np np.random.seed(0) from keras.models import Model from keras.layers import Dense, Input, Dropout, LSTM, Activation from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from keras.initializers import glorot_uniform np.random.seed(1) # ### 2.1 - Overview of the model # # Here is the Emojifier-v2 you will implement: # # <img src="images/emojifier-v2.png" style="width:700px;height:400px;"> <br> # <caption><center> **Figure 3**: Emojifier-V2. A 2-layer LSTM sequence classifier. </center></caption> # # # ### 2.2 Keras and mini-batching # # * In this exercise, we want to train Keras using mini-batches. # * However, most deep learning frameworks require that all sequences in the same mini-batch have the **same length**. # * This is what allows vectorization to work: If you had a 3-word sentence and a 4-word sentence, then the computations needed for them are different (one takes 3 steps of an LSTM, one takes 4 steps) so it's just not possible to do them both at the same time. # # #### Padding handles sequences of varying length # * The common solution to handling sequences of **different length** is to use padding. Specifically: # * Set a maximum sequence length # * Pad all sequences to have the same length. # # ##### Example of padding # * Given a maximum sequence length of 20, we could pad every sentence with "0"s so that each input sentence is of length 20. # * Thus, the sentence "I love you" would be represented as $(e_{I}, e_{love}, e_{you}, \vec{0}, \vec{0}, \ldots, \vec{0})$. # * In this example, any sentences longer than 20 words would have to be truncated. # * One way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set. # # ### 2.3 - The Embedding layer # # * In Keras, the embedding matrix is represented as a "layer". # * The embedding matrix maps word indices to embedding vectors. # * The word indices are positive integers. # * The embedding vectors are dense vectors of fixed size. # * When we say a vector is "dense", in this context, it means that most of the values are non-zero. As a counter-example, a one-hot encoded vector is not "dense." # * The embedding matrix can be derived in two ways: # * Training a model to derive the embeddings from scratch. # * Using a pretrained embedding # # #### Using and updating pre-trained embeddings # * In this part, you will learn how to create an [Embedding()](https://keras.io/layers/embeddings/) layer in Keras # * You will initialize the Embedding layer with the GloVe 50-dimensional vectors. # * In the code below, we'll show you how Keras allows you to either train or leave fixed this layer. # * Because our training set is quite small, we will leave the GloVe embeddings fixed instead of updating them. # # # #### Inputs and outputs to the embedding layer # # * The `Embedding()` layer's input is an integer matrix of size **(batch size, max input length)**. # * This input corresponds to sentences converted into lists of indices (integers). # * The largest integer (the highest word index) in the input should be no larger than the vocabulary size. # * The embedding layer outputs an array of shape (batch size, max input length, dimension of word vectors). # # * The figure shows the propagation of two example sentences through the embedding layer. # * Both examples have been zero-padded to a length of `max_len=5`. # * The word embeddings are 50 units in length. # * The final dimension of the representation is `(2,max_len,50)`. # # <img src="images/embedding1.png" style="width:700px;height:250px;"> # <caption><center> **Figure 4**: Embedding layer</center></caption> # #### Prepare the input sentences # **Exercise**: # * Implement `sentences_to_indices`, which processes an array of sentences (X) and returns inputs to the embedding layer: # * Convert each training sentences into a list of indices (the indices correspond to each word in the sentence) # * Zero-pad all these lists so that their length is the length of the longest sentence. # # ##### Additional Hints # * Note that you may have considered using the `enumerate()` function in the for loop, but for the purposes of passing the autograder, please follow the starter code by initializing and incrementing `j` explicitly. for idx, val in enumerate(["I", "like", "learning"]): print(idx,val) # + # GRADED FUNCTION: sentences_to_indices def sentences_to_indices(X, word_to_index, max_len): """ Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). Arguments: X -- array of sentences (strings), of shape (m, 1) word_to_index -- a dictionary containing the each word mapped to its index max_len -- maximum number of words in a sentence. You can assume every sentence in X is no longer than this. Returns: X_indices -- array of indices corresponding to words in the sentences from X, of shape (m, max_len) """ m = X.shape[0] # number of training examples ### START CODE HERE ### # Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line) X_indices = np.zeros((m, max_len)) for i in range(m): # loop over training examples # Convert the ith training sentence in lower case and split is into words. You should get a list of words. sentence_words = list(map(str.lower, X[i].split())) # Initialize j to 0 j = 0 # Loop over the words of sentence_words for w in sentence_words: # Set the (i,j)th entry of X_indices to the index of the correct word. X_indices[i, j] = word_to_index[w] # Increment j to j + 1 j = j + 1 ### END CODE HERE ### return X_indices # - # Run the following cell to check what `sentences_to_indices()` does, and check your results. X1 = np.array(["funny lol", "lets play baseball", "food is ready for you"]) X1_indices = sentences_to_indices(X1,word_to_index, max_len = 5) print("X1 =", X1) print("X1_indices =\n", X1_indices) # **Expected Output**: # # ```Python # X1 = ['funny lol' 'lets play baseball' 'food is ready for you'] # X1_indices = # [[ 155345. 225122. 0. 0. 0.] # [ 220930. 286375. 69714. 0. 0.] # [ 151204. 192973. 302254. 151349. 394475.]] # ``` # #### Build embedding layer # # * Let's build the `Embedding()` layer in Keras, using pre-trained word vectors. # * The embedding layer takes as input a list of word indices. # * `sentences_to_indices()` creates these word indices. # * The embedding layer will return the word embeddings for a sentence. # # **Exercise**: Implement `pretrained_embedding_layer()` with these steps: # 1. Initialize the embedding matrix as a numpy array of zeros. # * The embedding matrix has a row for each unique word in the vocabulary. # * There is one additional row to handle "unknown" words. # * So vocab_len is the number of unique words plus one. # * Each row will store the vector representation of one word. # * For example, one row may be 50 positions long if using GloVe word vectors. # * In the code below, `emb_dim` represents the length of a word embedding. # 2. Fill in each row of the embedding matrix with the vector representation of a word # * Each word in `word_to_index` is a string. # * word_to_vec_map is a dictionary where the keys are strings and the values are the word vectors. # 3. Define the Keras embedding layer. # * Use [Embedding()](https://keras.io/layers/embeddings/). # * The input dimension is equal to the vocabulary length (number of unique words plus one). # * The output dimension is equal to the number of positions in a word embedding. # * Make this layer's embeddings fixed. # * If you were to set `trainable = True`, then it will allow the optimization algorithm to modify the values of the word embeddings. # * In this case, we don't want the model to modify the word embeddings. # 4. Set the embedding weights to be equal to the embedding matrix. # * Note that this is part of the code is already completed for you and does not need to be modified. # + # GRADED FUNCTION: pretrained_embedding_layer def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: embedding_layer -- pretrained layer Keras instance """ vocab_len = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement) emb_dim = word_to_vec_map["cucumber"].shape[0] # define dimensionality of your GloVe word vectors (= 50) ### START CODE HERE ### # Step 1 # Initialize the embedding matrix as a numpy array of zeros. # See instructions above to choose the correct shape. emb_matrix = np.zeros((vocab_len, emb_dim)) # Step 2 # Set each row "idx" of the embedding matrix to be # the word vector representation of the idx'th word of the vocabulary for word, idx in word_to_index.items(): emb_matrix[idx, :] = word_to_vec_map[word] # Step 3 # Define Keras embedding layer with the correct input and output sizes # Make it non-trainable. embedding_layer = Embedding(vocab_len, emb_dim, trainable=False) ### END CODE HERE ### # Step 4 (already done for you; please do not modify) # Build the embedding layer, it is required before setting the weights of the embedding layer. embedding_layer.build((None,)) # Do not modify the "None". This line of code is complete as-is. # Set the weights of the embedding layer to the embedding matrix. Your layer is now pretrained. embedding_layer.set_weights([emb_matrix]) return embedding_layer # - embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) print("weights[0][1][3] =", embedding_layer.get_weights()[0][1][3]) # **Expected Output**: # # ```Python # weights[0][1][3] = -0.3403 # ``` # ## 2.3 Building the Emojifier-V2 # # Lets now build the Emojifier-V2 model. # * You feed the embedding layer's output to an LSTM network. # # <img src="images/emojifier-v2.png" style="width:700px;height:400px;"> <br> # <caption><center> **Figure 3**: Emojifier-v2. A 2-layer LSTM sequence classifier. </center></caption> # # # **Exercise:** Implement `Emojify_V2()`, which builds a Keras graph of the architecture shown in Figure 3. # * The model takes as input an array of sentences of shape (`m`, `max_len`, ) defined by `input_shape`. # * The model outputs a softmax probability vector of shape (`m`, `C = 5`). # # * You may need to use the following Keras layers: # * [Input()](https://keras.io/layers/core/#input) # * Set the `shape` and `dtype` parameters. # * The inputs are integers, so you can specify the data type as a string, 'int32'. # * [LSTM()](https://keras.io/layers/recurrent/#lstm) # * Set the `units` and `return_sequences` parameters. # * [Dropout()](https://keras.io/layers/core/#dropout) # * Set the `rate` parameter. # * [Dense()](https://keras.io/layers/core/#dense) # * Set the `units`, # * Note that `Dense()` has an `activation` parameter. For the purposes of passing the autograder, please do not set the activation within `Dense()`. Use the separate `Activation` layer to do so. # * [Activation()](https://keras.io/activations/). # * You can pass in the activation of your choice as a lowercase string. # * [Model](https://keras.io/models/model/) # Set `inputs` and `outputs`. # # # #### Additional Hints # * Remember that these Keras layers return an object, and you will feed in the outputs of the previous layer as the input arguments to that object. The returned object can be created and called in the same line. # # ```Python # # How to use Keras layers in two lines of code # dense_object = Dense(units = ...) # X = dense_object(inputs) # # # How to use Keras layers in one line of code # X = Dense(units = ...)(inputs) # ``` # # * The `embedding_layer` that is returned by `pretrained_embedding_layer` is a layer object that can be called as a function, passing in a single argument (sentence indices). # # * Here is some sample code in case you're stuck # ```Python # raw_inputs = Input(shape=(maxLen,), dtype='int32') # preprocessed_inputs = ... # some pre-processing # X = LSTM(units = ..., return_sequences= ...)(processed_inputs) # X = Dropout(rate = ..., )(X) # ... # X = Dense(units = ...)(X) # X = Activation(...)(X) # model = Model(inputs=..., outputs=...) # ... # ``` # # # + # GRADED FUNCTION: Emojify_V2 def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: model -- a model instance in Keras """ ### START CODE HERE ### # Define sentence_indices as the input of the graph. # It should be of shape input_shape and dtype 'int32' (as it contains indices, which are integers). sentence_indices = Input(shape=input_shape, dtype='int32') # Create the embedding layer pretrained with GloVe Vectors (≈1 line) embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) # Propagate sentence_indices through your embedding layer, you get back the embeddings embeddings = embedding_layer(sentence_indices) # Propagate the embeddings through an LSTM layer with 128-dimensional hidden state # The returned output should be a batch of sequences. X = LSTM(128, return_sequences=True)(embeddings) # Add dropout with a probability of 0.5 X = Dropout(0.5)(X) # Propagate X trough another LSTM layer with 128-dimensional hidden state # Be careful, the returned output should be a single hidden state, not a batch of sequences. X = LSTM(128, return_sequences=False)(X) # Add dropout with a probability of 0.5 X = Dropout(0.5)(X) # Propagate X through a Dense layer with 5 units X = Dense(units=5)(X) # Add a softmax activation X = Activation('softmax')(X) # Create Model instance which converts sentence_indices into X. model = Model(inputs=sentence_indices, outputs=X) ### END CODE HERE ### return model # - # Run the following cell to create your model and check its summary. Because all sentences in the dataset are less than 10 words, we chose `max_len = 10`. You should see your architecture, it uses "20,223,927" parameters, of which 20,000,050 (the word embeddings) are non-trainable, and the remaining 223,877 are. Because our vocabulary size has 400,001 words (with valid indices from 0 to 400,000) there are 400,001\*50 = 20,000,050 non-trainable parameters. model = Emojify_V2((maxLen,), word_to_vec_map, word_to_index) model.summary() # As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using `categorical_crossentropy` loss, `adam` optimizer and `['accuracy']` metrics: model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # It's time to train your model. Your Emojifier-V2 `model` takes as input an array of shape (`m`, `max_len`) and outputs probability vectors of shape (`m`, `number of classes`). We thus have to convert X_train (array of sentences as strings) to X_train_indices (array of sentences as list of word indices), and Y_train (labels as indices) to Y_train_oh (labels as one-hot vectors). X_train_indices = sentences_to_indices(X_train, word_to_index, maxLen) Y_train_oh = convert_to_one_hot(Y_train, C = 5) # Fit the Keras model on `X_train_indices` and `Y_train_oh`. We will use `epochs = 50` and `batch_size = 32`. model.fit(X_train_indices, Y_train_oh, epochs = 50, batch_size = 32, shuffle=True) # Your model should perform around **90% to 100% accuracy** on the training set. The exact accuracy you get may be a little different. Run the following cell to evaluate your model on the test set. X_test_indices = sentences_to_indices(X_test, word_to_index, max_len = maxLen) Y_test_oh = convert_to_one_hot(Y_test, C = 5) loss, acc = model.evaluate(X_test_indices, Y_test_oh) print() print("Test accuracy = ", acc) # You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples. # This code allows you to see the mislabelled examples C = 5 y_test_oh = np.eye(C)[Y_test.reshape(-1)] X_test_indices = sentences_to_indices(X_test, word_to_index, maxLen) pred = model.predict(X_test_indices) for i in range(len(X_test)): x = X_test_indices num = np.argmax(pred[i]) if(num != Y_test[i]): print('Expected emoji:'+ label_to_emoji(Y_test[i]) + ' prediction: '+ X_test[i] + label_to_emoji(num).strip()) # Now you can try it on your own example. Write your own sentence below. # Change the sentence below to see your prediction. Make sure all the words are in the Glove embeddings. x_test = np.array(['not feeling happy']) X_test_indices = sentences_to_indices(x_test, word_to_index, maxLen) print(x_test[0] +' '+ label_to_emoji(np.argmax(model.predict(X_test_indices)))) # ## LSTM version accounts for word order # * Previously, Emojify-V1 model did not correctly label "not feeling happy," but our implementation of Emojiy-V2 got it right. # * (Keras' outputs are slightly random each time, so you may not have obtained the same result.) # * The current model still isn't very robust at understanding negation (such as "not happy") # * This is because the training set is small and doesn't have a lot of examples of negation. # * But if the training set were larger, the LSTM model would be much better than the Emojify-V1 model at understanding such complex sentences. # # ### Congratulations! # # You have completed this notebook! ❤️❤️❤️ # # # ## What you should remember # - If you have an NLP task where the training set is small, using word embeddings can help your algorithm significantly. # - Word embeddings allow your model to work on words in the test set that may not even appear in the training set. # - Training sequence models in Keras (and in most other deep learning frameworks) requires a few important details: # - To use mini-batches, the sequences need to be **padded** so that all the examples in a mini-batch have the **same length**. # - An `Embedding()` layer can be initialized with pretrained values. # - These values can be either fixed or trained further on your dataset. # - If however your labeled dataset is small, it's usually not worth trying to train a large pre-trained set of embeddings. # - `LSTM()` has a flag called `return_sequences` to decide if you would like to return every hidden states or only the last one. # - You can use `Dropout()` right after `LSTM()` to regularize your network. # # #### Input sentences: # ```Python # "Congratulations on finishing this assignment and building an Emojifier." # "We hope you're happy with what you've accomplished in this notebook!" # ``` # #### Output emojis: # # 😀😀😀😀😀😀 # ## Acknowledgments # # Thanks to <NAME> and the Woebot team for their advice on the creation of this assignment. # * Woebot is a chatbot friend that is ready to speak with you 24/7. # * Part of Woebot's technology uses word embeddings to understand the emotions of what you say. # * You can chat with Woebot by going to http://woebot.io # # <img src="images/woebot.png" style="width:600px;height:300px;">
Sequence-Models/week2/notebooks/Emojify_v2a.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + import numpy as np import pandas as pd from os.path import join from pylab import rcParams import matplotlib.pyplot as plt # %matplotlib inline rcParams['figure.figsize'] = (13, 6) plt.style.use('ggplot') import nilmtk from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore from nilmtk.disaggregate import CombinatorialOptimisation, fhmm_exact from nilmtk.utils import print_dict from nilmtk.metrics import f1_score import warnings warnings.filterwarnings("ignore") # - data_dir = '/Users/nipunbatra/Downloads/' we = DataSet(join(data_dir, 'redd.h5')) print('loaded ' + str(len(we.buildings)) + ' buildings') building_number = 1 print_dict(we.buildings[building_number].metadata) we.buildings[building_number].elec.draw_wiring_graph()
notebooks/issues/390.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Module 1 - Introducing Libraries: NumPy # ## Introduction # # #### _Our goals today are to be able to_: <br/> # # - Identify and import Python libraries # - Identify differences between NumPy and base Python in usage and operation # - Create a new library of our own # # #### _Big questions for this lesson_: <br/> # - What is a package, what do packages do, and why might we want to use them? # - When do we want to use NumPy? # ### Activation: # # ![excel](excelpic.jpg) # # Most people have used Microsoft Excel or Google sheets. But what are the limitations of excel? # # - [Take a minute to read this article](https://www.bbc.com/news/magazine-22223190) # - make a list of problems excel presents # # How is using python different? # ## 1. Importing Python Libraries # # # In an earlier lesson, we wrote a function to calculate the mean of an list. That was **tedious**. # # Thankfully, other people have wrote and optimized functions and wrapped them into **libraries** we can then call and use in our analysis. # # ![numpy](https://raw.githubusercontent.com/donnemartin/data-science-ipython-notebooks/master/images/numpy.png) # # [NumPy](https://www.numpy.org/) is the fundamental package for scientific computing with Python. # # # To import a package type `import` followed by the name of the library as shown below. import numpy l = [1,2,3] x=numpy.array([1,2,3]) print(x) type(x) # + # Many packages have a canonical way to import them import numpy as np y=np.array([4,5,6]) print(y) # - # Because of numpy we can now get the **mean** and other quick math of lists and arrays. example = [4,3,25,40,62,20] print(np.mean(example)) # Now let's import some other packages. We will cover in more detail some fun options for numpy later. import scipy import pandas as pd import matplotlib as mpl # + # sometimes we will want to import a specific module from a library import matplotlib.pyplot as plt from matplotlib import pyplot as plt # What happens when we uncomment the next line? # %matplotlib inline plt.plot(x,y) # - # OR we can also import it this way from matplotlib import pyplot as plt plt.plot(x,y) # Try importing the seaborn library as ['sns'](https://en.wikipedia.org/wiki/Sam_Seaborn) which is the convention. #type your code here! import seaborn as sns # What happens if we mess with naming conventions? For example, import one of our previous libraries as `print`. # # # **PLEASE NOTE THAT WE WILL HAVE TO RESET THE KERNEL AFTER RUNNING THIS.**<br> Comment out your code after running it. # # + #your code here! # + #Did we get an error? What about when we run the following command? print(x) #Restart your kernel and clear cells # - # #### Helpful links: library documenation # # Libraries have associated documentation to explain how to use the different tools included in a library. # # - [NumPy](https://docs.scipy.org/doc/numpy/) # - [SciPy](https://docs.scipy.org/doc/scipy/reference/) # - [Pandas](http://pandas.pydata.org/pandas-docs/stable/) # - [Matplotlib](https://matplotlib.org/contents.html) # ## 2. NumPy versus base Python # # Now that we know libraries exist, why do we want to use them? Let us examine a comparison between base Python and Numpy. # # Python has lists and normal python can do basic math. NumPy, however, has the helpful objects called arrays. # # Numpy has a few advantages over base Python which we will look at. names_list=['Bob','John','Sally'] names_array=numpy.char.array(['Bob','John','Sally']) #use numpy.array for numbers and numpy.char.array for strings print(names_list) print(names_array) # + # Make a list and an array of three numbers #your code here numbers_list = [5,22,33,90] numbers_array = np.array([5,22,33,90]) # + # divide your array by 2 numbers_array/2 # + # divide your list by 2 numbers_list/2 # - # Numpy arrays support the `_div_()` operator while python lists do not. There are other things that make it useful to utilize numpy over base python for evaluating data. # + # shape tells us the size of the array numbers_array.shape # - # Selection and assignment work as you might expect numbers_array[1] numbers_array[1] = 10 numbers_array # Take 5 minutes and explore each of the following functions. What does each one do? What is the syntax of each? # - `np.zeros()` # - `np.ones()` # - `np.full()` # - `np.eye()` # - `np.random.random()` np.zeros(5) np.ones(5) np.full((3,3),3.3) np.eye(6) np.random.random(6) # ### Slicing in NumPy # We remember slicing from lists numbers_list = list(range(10)) numbers_list[3:7] # Slicing in NumPy Arrays is very similar! a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) a a.shape # first 2 rows, columns 1 & 2 (remember 0-index!) b = a[:2, 1:3] b # ### Datatypes in NumPy a.dtype names_list.dtype a.astype(np.float64) # ### More Array Math # + x = np.array([[1,2],[3,4]], dtype=np.float64) y = np.array([[5,6],[7,8]], dtype=np.float64) # Elementwise sum; both produce the array # [[ 6.0 8.0] # [10.0 12.0]] print(x + y) # - print(np.add(x, y)) # Elementwise difference; both produce the array # [[-4.0 -4.0] # [-4.0 -4.0]] print(x - y) print(np.subtract(x, y)) # Elementwise product; both produce the array # [[ 5.0 12.0] # [21.0 32.0]] print(x * y) print(np.multiply(x, y)) # Elementwise division; both produce the array # [[ 0.2 0.33333333] # [ 0.42857143 0.5 ]] print(x / y) print(np.divide(x, y)) # Elementwise square root; both produce the same array # [[ 1. 1.41421356] # [ 1.73205081 2. ]] print(x ** (1/2)) print(np.sqrt(x)) # Below, you will find a piece of code we will use to compare the speed of operations on a list and operations on an array. In this speed test, we will use the library [time](https://docs.python.org/3/library/time.html). # + import time import numpy as np size_of_vec = 100000000000 def pure_python_version(): t1 = time.time() X = range(size_of_vec) Y = range(size_of_vec) Z = [X[i] + Y[i] for i in range(len(X))] return time.time() - t1 def numpy_version(): t1 = time.time() X = np.arange(size_of_vec) Y = np.arange(size_of_vec) Z = X + Y return time.time() - t1 t1 = pure_python_version() t2 = numpy_version() print("python: " + str(t1), "numpy: "+ str(t2)) print("Numpy is in this example " + str(t1/t2) + " times faster!") # - # In pairs, run the speed test with a different number, and share your results with the class. # ## 3. Making our own library # ![belle](https://media1.giphy.com/media/14ouz31oYQe1BS/giphy.gif?cid=790b76115d2fa99c4c4c535263dea9d0&rid=giphy.gif) # %load_ext autoreload # %autoreload 2 import temperizer_sol as tps # ## Example: Convert F to C # # 1. This function is already implemented in `temperizer.py`. # 2. Notice that we can call the imported function and see the result. # 32F should equal 0C tps.convert_f_to_c(32) # -40F should equal -40C tps.convert_f_to_c(-40) # 212F should equal 100C tps.convert_f_to_c(212) # ## Your turn: Convert C to F # # 1. Find the stub function in `temperizer.py` # 2. The word `pass` means "this space intentionally left blank." # 3. Add your code _in place of_ the `pass` keyword, _below_ the docstring. # 4. Run these cells and make sure that your code works. # 0C should equal 32F tps.convert_c_to_f(0) # -40C should equal -40F tps.convert_c_to_f(-40) # 100C should equal 212F tps.convert_c_to_f(100) # ## Next: Adding New Functions # # You need to add support for Kelvin to the `temperizer` library. # # 1. Create new _stub functions_ in `temperizer.py`: # # * `convert_c_to_k` # * `convert_f_to_k` # * `convert_k_to_c` # * `convert_k_to_f` # # Start each function with a docstring and the `pass` keyword, e.g.: # # ``` # def convert_f_to_k(temperature_f): # """Convert Fahrenheit to Kelvin.""" # pass # ``` # # 2. Add cells to this notebook to test and validate these functions, similar to the ones above. # # 3. Then, go back to `temperizer.py` to replace `pass` with your code. # # 4. Run the notebook cells to make sure that your new functions work. tps.convert_f_to_c() # ### Extra credit: # # make a function in your temperizer that will take a temp in F, and print out: # # ``` # The temperature [number] F is: # - x in C # - y in k # ``` tps.convert_f_to_all(89)
intro_to_libraries_numpy_solution.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # About this Book # # __Welcome to "The Debugging Book"!__ # Software has bugs, and finding bugs can involve lots of effort. This book addresses this problem by _automating_ software debugging, specifically by _locating errors and their causes automatically_. Recent years have seen the development of novel techniques that lead to dramatic improvements in automated software debugging. They now are mature enough to be assembled in a book – even with executable code. # <!-- # **<span style="background-color: yellow"> # <i class="fa fa-fw fa-wrench"></i> # This book is work in progress. It will be released to the public in Spring 2021.</span>** # --> # + slideshow={"slide_type": "skip"} from bookutils import YouTubeVideo YouTubeVideo("-nOxI6Ev_I4") # + [markdown] slideshow={"slide_type": "slide"} # ## A Textbook for Paper, Screen, and Keyboard # # You can use this book in four ways: # # * You can __read chapters in your browser__. Check out the list of chapters in the menu above, or start right away with the [introduction to debugging](Intro_Debugging.ipynb) or [how debuggers work](Debugger.ipynb). All code is available for download. # # * You can __interact with chapters as Jupyter Notebooks__ (beta). This allows you to edit and extend the code, experimenting _live in your browser._ Simply select "Resources → Edit as Notebook" at the top of each chapter. <a href="https://mybinder.org/v2/gh/uds-se/debuggingbook/master?filepath=docs/notebooks/Debugger.ipynb" target=_blank>Try interacting with the introduction to interactive debuggers.</a> # # * You can __use the code in your own projects__. You can download the code as Python programs; simply select "Resources → Download Code" for one chapter or "Resources → All Code" for all chapters. These code files can be executed, yielding (hopefully) the same results as the notebooks. Once the book is out of beta, you can also [install the Python package](Importing.ipynb). # # * You can __present chapters as slides__. This allows for presenting the material in lectures. Just select "Resources → View slides" at the top of each chapter. <a href="https://www.debuggingbook.org/slides/Debugger.slides.html" target=_blank>Try viewing the slides for how debuggers work.</a> # + [markdown] slideshow={"slide_type": "slide"} # ## Who this Book is for # # This work is designed as a _textbook_ for a course in software debugging; as _supplementary material_ in a software testing or software engineering course; and as a _resource for software developers_. We cover fault localization, program slicing, input reduction, automated repair, and much more, illustrating all techniques with code examples that you can try out yourself. # + [markdown] slideshow={"slide_type": "slide"} # ## News # # This book is _work in progress_, with new chapters being released every week. To get notified on updates, <a href="https://twitter.com/Debugging_Book?ref_src=twsrc%5Etfw" data-show-count="false">follow us on Twitter</a>. # # <a class="twitter-timeline" data-width="500" data-chrome="noheader nofooter noborders transparent" data-link-color="#A93226" data-align="center" href="https://twitter.com/Debugging_Book?ref_src=twsrc%5Etfw" data-dnt="true">News from @Debugging_Book</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> # # <a href="https://twitter.com/Debugging_Book?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @Debugging_Book</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> # + [markdown] slideshow={"slide_type": "slide"} # ## About the Author # # This book is written by [<NAME>](https://andreas-zeller.info), a long-standing expert in automated debugging, software analysis and software testing. Andreas is happy to share his expertise and making it accessible to the public. # # <p><a href="https://twitter.com/AndreasZeller?ref_src=twsrc%5Etfw" class="twitter-follow-button">Follow @AndreasZeller</a><script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p> # + [markdown] slideshow={"slide_type": "slide"} # ## Frequently Asked Questions # + [markdown] slideshow={"slide_type": "subslide"} # ### Troubleshooting # + [markdown] slideshow={"slide_type": "subslide"} # #### Why does it take so long to start an interactive notebook? # # The interactive notebook uses the [mybinder.org](https://mybinder.org) service, which runs notebooks on their own servers. Starting Jupyter through mybinder.org normally takes about 30 seconds, depending on your Internet connection. If, however, you are the first to invoke binder after a book update, binder recreates its environment, which will take a few minutes. Reload the page occasionally. # + [markdown] slideshow={"slide_type": "subslide"} # #### The interactive notebook does not work! # # mybinder.org imposes a [limit of 100 concurrent users for a repository](https://mybinder.readthedocs.io/en/latest/user-guidelines.html). Also, as listed on the [mybinder.org status and reliability page](https://mybinder.readthedocs.io/en/latest/reliability.html), # # > As mybinder.org is a research pilot project, the main goal for the project is to understand usage patterns and workloads for future project evolution. While we strive for site reliability and availability, we want our users to understand the intent of this service is research and we offer no guarantees of its performance in mission critical uses. # + [markdown] slideshow={"slide_type": "fragment"} # There are alternatives to mybinder.org; see below. # + [markdown] slideshow={"slide_type": "subslide"} # #### Do I have alternatives to the interactive notebook? # # If mybinder.org does not work or match your needs, you have a number of alternatives: # # 1. **Download the Python code** (using the menu at the top) and edit and run it in your favorite environment. This is easy to do and does not require lots of resources. # 2. **Download the Jupyter Notebooks** (using the menu at the top) and open them in Jupyter. Here's [how to install jupyter notebook on your machine](https://www.dataquest.io/blog/jupyter-notebook-tutorial/). # # For details, see our article on [Using Debuggingbook Code in your own Programs](Importing.ipynb). Enjoy! # + [markdown] slideshow={"slide_type": "subslide"} # #### Can I run the code on my Windows machine? # # We try to keep the code as general as possible, but occasionally, when we interact with the operating system, we assume a Unix-like environment (because that is what Binder provides). To run these examples on your own Windows machine, you can install a Linux VM or a [Docker environment](https://github.com/uds-se/debuggingbook/blob/master/deploy/README.md). # + [markdown] slideshow={"slide_type": "subslide"} # #### Can't you run your own dedicated cloud service? # # Technically, yes; but this would cost money and effort, which we'd rather spend on the book at this point. If you'd like to host a [JupyterHub](http://jupyter.org/hub) or [BinderHub](https://github.com/jupyterhub/binderhub) instance for the public, please _do so_ and let us know. # + [markdown] slideshow={"slide_type": "subslide"} # ### Content # + [markdown] slideshow={"slide_type": "subslide"} # #### Can I use your code in my own programs? # # Yes! See the [installation instructions](Importing.ipynb) for details. # + [markdown] slideshow={"slide_type": "subslide"} # #### Do your techniques apply to Python programs only? How about C code? # # We use Python to implement our tools and techniques because we can get things done *quickly.* Building an [interactive debugger](Debugger.ipynb) in Python is less than 100 lines of code and took us 2-3 days; doing the same for C is tens of thousands of lines and a year-long project. Instrumenting code, say for [dynamic slicing](Slicer.ipynb), gets us savings of similar magnitude. Also, Python code allows us (and you) to focus on the main concepts, rather than implementation details that are out of place in a textbook. # # Having said this, many of the techniques in this book can also be applied to C and other code. This is notably true for _black-box_ techniques such as [reducing inputs](DeltaDebugger.ipynb) or [changes](ChangeDebugger.ipynb) or [generalizers](DDSetDebugger.ipynb); these are all language-agnostic. Tools related to the debugging process such as [bug tracking](Tracking.ipynb) or [mining repositories](ChangeCounter.ipynb) are language-agnostic as well. Finally, in all chapters, we provide pointers to implementations in and for other languages, for instance for [assertions](Assertions.ipynb) or [program repair](Repairer.ipynb). # + [markdown] slideshow={"slide_type": "subslide"} # #### What are the latest changes? # # For changes to individual chapters, see the "Last change" link at the end of a chapter. For the `debuggingbook` Python package, see the [release notes](ReleaseNotes.ipynb) for details. # + [markdown] slideshow={"slide_type": "subslide"} # #### How do I cite your work? # # Thanks for referring to our work! Just click on the "cite" button at the bottom of the Web page for each chapter to get a citation entry. # + [markdown] slideshow={"slide_type": "subslide"} # #### Can you cite my paper? And possibly write a chapter about it? # # We're always happy to get suggestions! If we missed an important reference, we will of course add it. If you'd like specific material to be covered, the best way is to _write a notebook_ yourself; see our [Guide for Authors](Guide_for_Authors.ipynb) for instructions on coding and writing. We can then refer to it or even host it. # + [markdown] slideshow={"slide_type": "subslide"} # ### Teaching and Coursework # + [markdown] slideshow={"slide_type": "subslide"} # #### Can I use your material in my course? # # Of course! Just respect the [license](https://github.com/uds-se/debuggingbook/blob/master/LICENSE.md) (including attribution and share alike). If you want to use the material for commercial purposes, contact us. # + [markdown] slideshow={"slide_type": "subslide"} # #### Can I extend or adapt your material? # # Yes! Again, please see the [license](https://github.com/uds-se/debuggingbook/blob/master/LICENSE.md) for details. # + [markdown] slideshow={"slide_type": "subslide"} # #### How can I run a course based on the book? # # We have successfully used the material in various courses. # # * Initially, we used the slides and code and did _live coding_ in lectures to illustrate how a technique works. # # * Now, the goal of the book is to be completely self-contained; that is, it should work without additional support. Hence, we now give out completed chapters to students in a _flipped classroom_ setting, with the students working on the notebooks at their leisure. We would meet in the classroom (or in Zoom) to discuss experiences with past notebooks and discuss future notebooks. # # * We have the students work on exercises from the book or work on larger (automated debugging) projects. We also have students who use the book as a base for their research; indeed, it is very easy to prototype in Python for Python. # # When running a course, [do not rely on mybinder.org](#Troubleshooting) – it will not provide sufficient resources for a larger group of students. Instead, [install and run your own hub.](#Do-I-have-alternatives-to-the-interactive-notebook?) # + [markdown] slideshow={"slide_type": "subslide"} # #### Are there specific subsets I can focus on? # # We will compile a number of [tours through the book](Tours.ipynb) for various audiences. Our [Sitemap](00_Table_of_Contents.ipynb) lists the dependencies between the individual chapters. # + [markdown] slideshow={"slide_type": "subslide"} # #### How can I extend or adapt your slides? # # Download the Jupyter Notebooks (using the menu at the top) and adapt the notebooks at your leisure (see above), including "Slide Type" settings. Then, # # 1. Download slides from Jupyter Notebook; or # 2. Use the RISE extension ([instructions](http://www.blog.pythonlibrary.org/2018/09/25/creating-presentations-with-jupyter-notebook/)) to present your slides right out of Jupyter notebook. # + [markdown] slideshow={"slide_type": "subslide"} # #### Do you provide PDFs of your material? # # Technically, we can produce PDF and print versions from notebooks, but it is low on our priority list as we find the interactive formats to be so much superior. Let us know if you'd like PDF versions. # + [markdown] slideshow={"slide_type": "subslide"} # ### Other Issues # + [markdown] slideshow={"slide_type": "subslide"} # #### I have a question, comment, or a suggestion. What do I do? # # You can [tweet to @debugging_book on Twitter](https://twitter.com/debugging_book), allowing the community of readers to chime in. For bugs you'd like to get fixed, report an issue on the [development page](https://github.com/uds-se/debuggingbook/issues). # + [markdown] slideshow={"slide_type": "subslide"} # #### I have reported an issue two weeks ago. When will it be addressed? # # We prioritize issues as follows: # # 1. Bugs in code published on debuggingbook.org # 2. Bugs in text published on debuggingbook.org # 3. Writing missing chapters # 4. Issues in yet unpublished code or text # 5. Issues related to development or construction # 6. Things marked as "beta" # 7. Everything else # + [markdown] slideshow={"slide_type": "subslide"} # #### How can I solve problems myself? # # We're glad you ask that. The [development page](https://github.com/uds-se/debuggingbook/) has all sources and some supplementary material. Pull requests that fix issues are very welcome. # + [markdown] slideshow={"slide_type": "subslide"} # #### How can I contribute? # # Again, we're glad you're here! We are happy to accept # # * **Code fixes and improvements.** Please place any code under the MIT license such that we can easily include it. # * **Additional text, chapters, and notebooks** on specialized topics. We plan to set up a special folder for third-party contributions. # # See our [Guide for Authors](Guide_for_Authors.ipynb) for instructions on coding and writing.
docs/notebooks/index.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd df = pd.read_csv('SMSSpamCollection', delimiter='\t', names=['label', 'messages']) df sentence = list(df.iloc[:,1]) sentence # #### Cleaning the dataset # + # removing the stopwords from tehe dataset # also converting all the words into the lower case # creaitng the stem of the words import nltk import re from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords # - # creating the object of the lemmitizer ls = WordNetLemmatizer() # craeting the clean corpus by removing the stopwords, punktuation and creating the stem in every sentence corpus = [] for i in range(len(df)): message = re.sub('^[a-zA-Z]', ' ', sentence[i]) message = message.lower() message = message.split() message = [ls.lemmatize(word) for word in message if word not in set(stopwords.words('english'))] message = ' '.join(message) corpus.append(message) # + # Creating the Bag of Word model # - #importing the required library from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer #initialising the vectorizers. we are using max feaure because ( all the words are not significantly repeating # that means some of the words are just present one time so those word doesn't play much significance so we can select less # features than we actually have to increase the efficiency and performance.) cv = CountVectorizer(max_features=5000) tfidf_cv = TfidfVectorizer(max_features=5000) #fitting the corpus to create the vector cv_X = cv.fit_transform(corpus).toarray() tfidf_cv = tfidf_cv.fit_transform(corpus).toarray() cv_X.shape # we need to convet the output value to the numeric. Since we have only two category so we are going to convert using getdummies df['label'] #converting the labels into 1 and 0 where o represents the ham and 1 represents the spam. y = pd.get_dummies(df['label']) y = y.iloc[:,1].values y # creating the test and the train set of data from sklearn.model_selection import train_test_split X_train,X_test, y_train, y_test = train_test_split(cv_X, y, test_size = 0.2, random_state = 0) # #### implementing the random forest classifier to classify the spam sms # Let me use random forest tp classify the sms now from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_jobs=-1, random_state= 0, n_estimators= 200, verbose=1) rf.fit(X_train, y_train) y_pred = rf.predict(X_test) from sklearn.metrics import classification_report, accuracy_score, confusion_matrix confusion_matrix(y_test, y_pred) accuracy_score(y_test, y_pred) test_df = pd.DataFrame() test_df['test'] = y_test test_df['Pred'] = y_pred test_df # + # creating the TF-IDF model # - from sklearn.model_selection import train_test_split X_train,X_test, y_train, y_test = train_test_split(tfidf_cv, y, test_size = 0.2, random_state = 0) # Let me use random forest tp classify the sms now from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_jobs=-1, random_state= 0, n_estimators= 200, verbose=1) rf.fit(X_train, y_train) y_pred = rf.predict(X_test) accuracy_score(y_test, y_pred) print(confusion_matrix(y_test, y_pred)) # # Naive bayes works very good in case of NLP from sklearn.naive_bayes import MultinomialNB model = MultinomialNB().fit(X_train, y_train) y_pred = model.predict(X_test) from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred) print(cm) print(accuracy_score(y_test, y_pred))
Spam detection Machine Learning practise using Bag of words and the TF-IDF.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Use PyTorch to recognize hand-written digits with Watson Machine Learning REST API # This notebook contains steps and code to demonstrate support of PyTorch Deep Learning experiments in Watson Machine Learning Service. It introduces commands for getting data, training experiments, persisting pipelines, publishing models, deploying models and scoring. # # Some familiarity with cURL is helpful. This notebook uses cURL examples. # # # ## Learning goals # # The learning goals of this notebook are: # # - Working with Watson Machine Learning experiments to train Deep Learning models. # - Downloading computed models to local storage. # - Online deployment and scoring of trained model. # # # ## Contents # # This notebook contains the following parts: # # 1. [Setup](#setup) # 2. [Experiment definition](#experiment_definition) # 3. [Model definition](#model_definition) # 4. [Experiment Run](#run) # 5. [Historical runs](#runs) # 6. [Deploy and Score](#deploy_and_score) # 7. [Cleaning](#cleaning) # 8. [Summary and next steps](#summary) # <a id="setup"></a> # ## 1. Set up the environment # # Before you use the sample code in this notebook, you must perform the following setup tasks: # # - Create a <a href="https://console.ng.bluemix.net/catalog/services/ibm-watson-machine-learning/" target="_blank" rel="noopener no referrer">Watson Machine Learning (WML) Service</a> instance (a free plan is offered and information about how to create the instance can be found <a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/ml-service-instance.html?context=analytics" target="_blank" rel="noopener no referrer">here</a>). # - Create a <a href="https://console.bluemix.net/catalog/infrastructure/cloud-object-storage" target="_blank" rel="noopener no referrer">Cloud Object Storage (COS)</a> instance (a lite plan is offered and information about how to order storage can be found <a href="https://console.bluemix.net/docs/services/cloud-object-storage/basics/order-storage.html#order-storage" target="_blank" rel="noopener no referrer">here</a>). <br/>**Note: When using Watson Studio, you already have a COS instance associated with the project you are running the notebook in.** # You can find your COS credentials in COS instance dashboard under the **Service credentials** tab. # Go to the **Endpoint** tab in the COS instance's dashboard to get the endpoint information. # # Authenticate the Watson Machine Learning service on IBM Cloud. # # Your Cloud API key can be generated by going to the [**Users** section of the Cloud console](https://cloud.ibm.com/iam#/users). From that page, click your name, scroll down to the **API Keys** section, and click **Create an IBM Cloud API key**. Give your key a name and click **Create**, then copy the created key and paste it below. # # **NOTE:** You can also get service specific apikey by going to the [**Service IDs** section of the Cloud Console](https://cloud.ibm.com/iam/serviceids). From that page, click **Create**, then copy the created key and paste it below. # # + # %env API_KEY=... # %env WML_ENDPOINT_URL=... # %env WML_INSTANCE_CRN="fill out only if you want to create a new space" # %env WML_INSTANCE_NAME=... # %env COS_CRN="fill out only if you want to create a new space" # %env COS_ENDPOINT=... # %env COS_BUCKET=... # %env COS_ACCESS_KEY_ID=... # %env COS_SECRET_ACCESS_KEY=... # %env COS_API_KEY=... # %env SPACE_ID="fill out only if you have space already created" # %env DATAPLATFORM_URL=https://api.dataplatform.cloud.ibm.com # %env AUTH_ENDPOINT=https://iam.cloud.ibm.com/oidc/token # - # <a id="wml_token"></a> # ### Getting WML authorization token for further cURL calls # <a href="https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-curl#curl-token" target="_blank" rel="noopener no referrer">Example of cURL call to get WML token</a> # + magic_args="--out token" language="bash" # # curl -sk -X POST \ # --header "Content-Type: application/x-www-form-urlencoded" \ # --header "Accept: application/json" \ # --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey" \ # --data-urlencode "apikey=$API_KEY" \ # "$AUTH_ENDPOINT" \ # | cut -d '"' -f 4 # - # %env TOKEN=$token # <a id="space_creation"></a> # ### Space creation # **Tip:** If you do not have `space` already created, please convert below three cells to `code` and run them. # # First of all, you need to create a `space` that will be used in all of your further cURL calls. # If you do not have `space` already created, below is the cURL call to create one. # <a href="https://cpd-spaces-api.eu-gb.cf.appdomain.cloud/#/Spaces/spaces_create" # target="_blank" rel="noopener no referrer">Space creation</a> # + magic_args="--out space_id" language="bash" active="" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data '{"name": "curl_DL", "storage": {"type": "bmcos_object_storage", "resource_crn": "'"$COS_CRN"'"}, "compute": [{"name": "'"$WML_INSTANCE_NAME"'", "crn": "'"$WML_INSTANCE_CRN"'", "type": "machine_learning"}]}' \ # "$DATAPLATFORM_URL/v2/spaces" \ # | grep '"id": ' | awk -F '"' '{ print $4 }' # + active="" # space_id = space_id.split('\n')[1] # %env SPACE_ID=$space_id # - # Space creation is asynchronous. This means that you need to check space creation status after creation call. # Make sure that your newly created space is `active`. # <a href="https://cpd-spaces-api.eu-gb.cf.appdomain.cloud/#/Spaces/spaces_get" # target="_blank" rel="noopener no referrer">Get space information</a> # + language="bash" active="" # # curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$DATAPLATFORM_URL/v2/spaces/$SPACE_ID" # - # <a id="experiment_definition"></a> # ## 2. Experiment / optimizer configuration # <a id="training_connection"></a> # ### Training data connection # # Define connection information to COS bucket and training data npz file. This example uses the MNIST dataset. # **Action**: Upload training data to COS bucket and enter location information in the next cURL examples. # + language="bash" # # wget -q https://s3.amazonaws.com/img-datasets/mnist.npz \ # -O mnist.npz # - # <a id="cos_token"></a> # ### Get COS token # Retrieve COS token for further authentication calls. # <a href="https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-curl#curl-token" # target="_blank" rel="noopener no referrer">Retrieve COS authentication token</a> # + magic_args="--out cos_token" language="bash" # # curl -s -X "POST" "$AUTH_ENDPOINT" \ # -H 'Accept: application/json' \ # -H 'Content-Type: application/x-www-form-urlencoded' \ # --data-urlencode "apikey=$COS_API_KEY" \ # --data-urlencode "response_type=cloud_iam" \ # --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey" \ # | cut -d '"' -f 4 # - # %env COS_TOKEN=$cos_token # <a id="cos_upload"></a> # ### Upload file to COS # Upload your local dataset into your COS bucket # <a href="https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-curl#curl-put-object" # target="_blank" rel="noopener no referrer">Upload file to COS</a> # There should be an empty response when upload finished succesfully. # + language="bash" # # curl -sk -X PUT \ # --header "Authorization: Bearer $COS_TOKEN" \ # --header "Content-Type: application/octet-stream" \ # --data-binary "@mnist.npz" \ # "$COS_ENDPOINT/$COS_BUCKET/mnist.npz" # - # ### Create connection to COS # # Created connections will be used in training for pointing to given COS location. # + magic_args="--out connection_payload" language="bash" # # CONNECTION_PAYLOAD='{"name": "REST COS connection", "datasource_type": "193a97c1-4475-4a19-b90c-295c4fdc6517", "properties": {"bucket": "'"$COS_BUCKET"'", "access_key": "'"$COS_ACCESS_KEY_ID"'", "secret_key": "'"$COS_SECRET_ACCESS_KEY"'", "iam_url": "'"$AUTH_ENDPOINT"'", "url": "'"$COS_ENDPOINT"'"}, "origin_country": "US"}' # echo $CONNECTION_PAYLOAD | python -m json.tool # - # %env CONNECTION_PAYLOAD=$connection_payload # + magic_args="--out connection_id" language="bash" # CONNECTION_ID=$(curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data "$CONNECTION_PAYLOAD" \ # "$DATAPLATFORM_URL/v2/connections?space_id=$SPACE_ID") # # CONNECTION_ID=${CONNECTION_ID#*asset_id\":\"} # CONNECTION_ID=${CONNECTION_ID%%\"*} # echo $CONNECTION_ID # - # %env CONNECTION_ID=$connection_id # <a id="model_definition"></a> # ## 3. Model definition # # This section provides samples about how to store model definition via cURL calls. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Model%20Definitions/model_definitions_create" # target="_blank" rel="noopener no referrer">Store a model definition for Deep Learning experiment</a> # + magic_args="--out model_definition_payload" language="bash" # # MODEL_DEFINITION_PAYLOAD='{"name": "PyTorch Hand-written Digit Recognition", "space_id": "'"$SPACE_ID"'", "description": "PyTorch Hand-written Digit Recognition", "tags": ["DL", "PyTorch"], "version": "2.0", "platform": {"name": "python", "versions": ["3.7"]}, "command": "python3 torch_mnist.py --epochs 1"}' # echo $MODEL_DEFINITION_PAYLOAD | python -m json.tool # - # %env MODEL_DEFINITION_PAYLOAD=$model_definition_payload # + magic_args="--out model_definition_id" language="bash" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data "$MODEL_DEFINITION_PAYLOAD" \ # "$WML_ENDPOINT_URL/ml/v4/model_definitions?version=2020-08-01"| grep '"id": ' | awk -F '"' '{ print $4 }' # - # %env MODEL_DEFINITION_ID=$model_definition_id # <a id="model_preparation"></a> # ### Model preparation # # Download files with keras code. You can either download it via link below or run the cell below the link. # <a href="https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/definitions/keras/mnist/MNIST.zip" # target="_blank" rel="noopener no referrer">Download pytorch-model.zip</a> # + language="bash" # # wget https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/definitions/pytorch/mnist/pytorch-model.zip \ # -O pytorch-model.zip # - # **Tip**: Convert below cell to code and run it to see model deinition's code. # + active="" # !unzip -oqd . pytorch-model.zip.zip && cat torch_mnist.py # - # <a id="def_upload"></a> # ### Upload model for the model definition # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Model%20Definitions/model_definitions_upload_model" # target="_blank" rel="noopener no referrer">Upload model for the model definition</a> # + language="bash" # # curl -sk -X PUT \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data-binary "@pytorch-model.zip" \ # "$WML_ENDPOINT_URL/ml/v4/model_definitions/$MODEL_DEFINITION_ID/model?version=2020-08-01&space_id=$SPACE_ID" \ # | python -m json.tool # - # <a id="run"></a> # ## 4. Experiment run # # This section provides samples about how to trigger Deep Learning experiment via cURL calls. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Trainings/trainings_create" # target="_blank" rel="noopener no referrer">Schedule a training job for Deep Learning experiment</a> # + magic_args="--out training_payload" language="bash" # # TRAINING_PAYLOAD='{"training_data_references": [{"name": "training_input_data", "type": "connection_asset", "connection": {"id": "'"$CONNECTION_ID"'"}, "location": {"bucket": "'"$COS_BUCKET"'", "file_name": "."}, "schema": {"id": "idmlp_schema", "fields": [{"name": "text", "type": "string"}]}}], "results_reference": {"name": "MNIST results", "connection": {"id": "'"$CONNECTION_ID"'"}, "location": {"bucket": "'"$COS_BUCKET"'", "file_name": "."}, "type": "connection_asset"}, "tags": [{"value": "tags_pytorch", "description": "Tags PyTorch"}], "name": "PyTorch hand-written Digit Recognition", "description": "PyTorch hand-written Digit Recognition", "model_definition": {"id": "'"$MODEL_DEFINITION_ID"'", "hardware_spec": {"name": "K80", "nodes": 1}, "software_spec": {"name": "pytorch-onnx_1.7-py3.7"}, "parameters": {"name": "PyTorch_mnist", "description": "PyTorch mnist recognition"}}, "space_id": "'"$SPACE_ID"'"}' # echo $TRAINING_PAYLOAD | python -m json.tool # - # %env TRAINING_PAYLOAD=$training_payload # + magic_args="--out training_id" language="bash" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data "$TRAINING_PAYLOAD" \ # "$WML_ENDPOINT_URL/ml/v4/trainings?version=2020-08-01" | awk -F'"id":' '{print $2}' | cut -c2-37 # - # %env TRAINING_ID=$training_id # <a id="training_details"></a> # ### Get training details # Treining is an asynchronous endpoint. In case you want to monitor training status and details, # you need to use a GET method and specify which training you want to monitor by usage of training ID. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Trainings/trainings_get" # target="_blank" rel="noopener no referrer">Get information about training job</a> # + language="bash" active="" # # curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings/$TRAINING_ID?space_id=$SPACE_ID&version=2020-08-01" \ # | python -m json.tool # - # ### Get training status # + language="bash" # # STATUS=$(curl -sk -X GET\ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings/$TRAINING_ID?space_id=$SPACE_ID&version=2020-08-01") # # STATUS=${STATUS#*state\":\"} # STATUS=${STATUS%%\"*} # echo $STATUS # - # Please make sure that training is completed before you go to the next sections. # Monitor `state` of your training by running above cell couple of times. # <a id="download_model"></a> # ### Get selected model # # Get a Keras saved model location in COS from the Deep Learning training job. # + magic_args="--out model_name" language="bash" # # PATH=$(curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings/$TRAINING_ID?space_id=$SPACE_ID&version=2020-08-01") # # # PATH=${PATH#*logs\":\"} # MODEL_NAME=${PATH%%\"*} # echo $MODEL_NAME # - # %env MODEL_NAME=$model_name # <a id="runs"></a> # ## 5. Historical runs # # In this section you will see cURL examples describing how to get historical training runs information. # Output should be similar to the output from training creation but you should see more trainings entries. # Listing trainings: # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Trainings/trainings_list" # target="_blank" rel="noopener no referrer">Get list of historical training jobs information</a> # + language="bash" # # HISTORICAL_TRAINING_LIMIT_TO_GET=2 # # curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings?space_id=$SPACE_ID&version=2020-08-01&limit=$HISTORICAL_TRAINING_LIMIT_TO_GET" \ # | python -m json.tool # - # <a id="training_cancel"></a> # ### Cancel training run # # **Tip:** If you want to cancel your training, please convert below cell to `code`, specify training ID and run. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Trainings/trainings_delete" # target="_blank" rel="noopener no referrer">Canceling training</a> # + language="bash" active="" # # TRAINING_ID_TO_CANCEL=... # # curl -sk -X DELETE \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings/$TRAINING_ID_TO_DELETE?space_id=$SPACE_ID&version=2020-08-01" # - # --- # <a id="deploy_and_score"></a> # ## 6. Deploy and Score # # In this section you will learn how to deploy and score pipeline model as webservice using WML instance. # Before deployment creation, you need store your model in WML repository. # Please see below cURL call example how to do it. Remember that you need to # specify where your chosen model is stored in COS. # <a id="model_store"></a> # ### Store Deep Learning model # # Store information about your model to WML repository. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Models/models_create" # target="_blank" rel="noopener no referrer">Model storing</a> # + magic_args="--out model_payload" language="bash" # # MODEL_PAYLOAD='{"space_id": "'"$SPACE_ID"'", "name": "PyTorch Mnist Model", "description": "PyTorch model to recognize hand-written digits", "type": "pytorch-onnx_1.7", "software_spec": {"name": "default_py3.7_opence"}, "content_location": { "type": "s3", "contents": [{ "content_format": "native", "file_name": "'"$MODEL_NAME.zip"'", "location": "'"$TRAINING_ID/assets/$TRAINING_ID/resources/wml_model/$MODEL_NAME.zip"'"}],"connection": {"endpoint_url": "'"$COS_ENDPOINT"'", "access_key_id": "'"$COS_ACCESS_KEY_ID"'", "secret_access_key": "'"$COS_SECRET_ACCESS_KEY"'"}, "location": {"bucket": "'"$COS_BUCKET"'"}}}' # echo $MODEL_PAYLOAD | python -m json.tool # - # %env MODEL_PAYLOAD=$model_payload # + magic_args="--out model_id" language="bash" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data "$MODEL_PAYLOAD" \ # "$WML_ENDPOINT_URL/ml/v4/models?version=2020-08-01" | grep '"id": ' | awk -F '"' '{ print $4 }' | sed -n 2p # - # %env MODEL_ID=$model_id # <a id="deployment_creation"></a> # ### Deployment creation # # An Deep Learning online deployment creation is presented below. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Deployments/deployments_create" # target="_blank" rel="noopener no referrer">Create deployment</a> # + magic_args="--out deployment_payload" language="bash" # # DEPLOYMENT_PAYLOAD='{"space_id": "'"$SPACE_ID"'","name": "PyTorch Mnist deployment", "description": "PyTorch model to recognize hand-written digits","online": {},"hardware_spec": {"name": "S"},"asset": {"id": "'"$MODEL_ID"'"}}' # echo $DEPLOYMENT_PAYLOAD | python -m json.tool # - # %env DEPLOYMENT_PAYLOAD=$deployment_payload # + magic_args="--out deployment_id" language="bash" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data "$DEPLOYMENT_PAYLOAD" \ # "$WML_ENDPOINT_URL/ml/v4/deployments?version=2020-08-01" \ # | grep '"id": ' | awk -F '"' '{ print $4 }' | sed -n 3p # - # %env DEPLOYMENT_ID=$deployment_id # <a id="deployment_details"></a> # ### Get deployment details # As deployment API is asynchronous, please make sure your deployment is in `ready` state before going to the next points. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Deployments/deployments_get" # target="_blank" rel="noopener no referrer">Get deployment details</a> # + language="bash" # # curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/deployments/$DEPLOYMENT_ID?space_id=$SPACE_ID&version=2020-08-01" \ # | python -m json.tool # - # <a id="input_score"></a> # ### Prepare scoring input data # **Hint:** You may need to install numpy using following command `!pip install numpy` # + import numpy as np mnist_dataset = np.load('mnist.npz') test_mnist = mnist_dataset['x_test'] # - image_1 = [test_mnist[0].tolist()] image_2 = [test_mnist[1].tolist()] # %matplotlib inline import matplotlib.pyplot as plt for i, image in enumerate([test_mnist[0], test_mnist[1]]): plt.subplot(2, 2, i + 1) plt.axis('off') plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') # <a id="webservice_score"></a> # ### Scoring of a webservice # If you want to make a `score` call on your deployment, please follow a below method: # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Deployment%20Jobs/deployment_jobs_create" # target="_blank" rel="noopener no referrer">Create deployment job</a> # + magic_args="-s \"$image_1\" \"$image_2\"" language="bash" # # curl -sk -X POST \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # --data '{"space_id": "$SPACE_ID","input_data": [{"values": ['"$1"', '"$2"']}]}' \ # "$WML_ENDPOINT_URL/ml/v4/deployments/$DEPLOYMENT_ID/predictions?version=2020-08-01" \ # | python -m json.tool # - # <a id="deployments_list"></a> # ### Listing all deployments # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Deployments/deployments_list" # target="_blank" rel="noopener no referrer">List deployments details</a> # + language="bash" # # curl -sk -X GET \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/deployments?space_id=$SPACE_ID&version=2020-08-01" \ # | python -m json.tool # - # <a id="cleaning"></a> # ## 7. Cleaning section # # Below section is useful when you want to clean all of your previous work within this notebook. # Just convert below cells into the `code` and run them. # <a id="training_delete"></a> # ### Delete training run # **Tip:** You can completely delete a training run with its metadata. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Trainings/trainings_delete" # target="_blank" rel="noopener no referrer">Deleting training</a> # + language="bash" active="" # # TRAINING_ID_TO_DELETE=... # # curl -sk -X DELETE \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/trainings/$TRAINING_ID_TO_DELETE?space_id=$SPACE_ID&version=2020-08-01&hard_delete=true" # - # <a id="deployment_delete"></a> # ### Deleting deployment # **Tip:** You can delete existing deployment by calling DELETE method. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Deployments/deployments_delete" # target="_blank" rel="noopener no referrer">Delete deployment</a> # + language="bash" active="" # # curl -sk -X DELETE \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # --header "Accept: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/deployments/$DEPLOYMENT_ID?space_id=$SPACE_ID&version=2020-08-01" # - # <a id="model_delete"></a> # ### Delete model from repository # **Tip:** If you want to completely remove your stored model and model metadata, just use a DELETE method. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Models/models_delete" # target="_blank" rel="noopener no referrer">Delete model from repository</a> # + language="bash" active="" # # curl -sk -X DELETE \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/models/$MODEL_ID?space_id=$SPACE_ID&version=2020-08-01" # - # <a id="def_delete"></a> # ### Delete model definition # **Tip:** If you want to completely remove your model definition, just use a DELETE method. # <a href="https://watson-ml-v4-api.mybluemix.net/wml-restapi-cloud.html#/Model%20Definitions/model_definitions_delete" # target="_blank" rel="noopener no referrer">Delete model definition</a> # + language="bash" active="" # # curl -sk -X DELETE \ # --header "Authorization: Bearer $TOKEN" \ # --header "Content-Type: application/json" \ # "$WML_ENDPOINT_URL/ml/v4/model_definitions/$MODEL_DEFINITION_ID?space_id=$SPACE_ID&version=2020-08-01" # - # <a id="summary"></a> # ## 8. Summary and next steps # # You successfully completed this notebook!. # # You learned how to use `cURL` calls to store, deploy and score a PyTorch Deep Learning model in WML. # ### Authors # # **<NAME>**, Intern in Watson Machine Learning at IBM # Copyright © 2020, 2021 IBM. This notebook and its source code are released under the terms of the MIT License.
cloud/notebooks/rest_api/curl/experiments/deep_learning/Use PyTorch to recognize hand-written digits.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + ## Here I am checking for how many datapoints prediction changes after switching the value of protected attribute (Default ) import pandas as pd import random,time,csv import numpy as np import math,copy,os from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn import tree from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC import sklearn.metrics as metrics import sys sys.path.append(os.path.abspath('..')) from Measure import measure_final_score,calculate_recall,calculate_far,calculate_precision,calculate_accuracy # + ## Load dataset dataset_orig = pd.read_csv('../dataset/compas-scores-two-years.csv') ## Drop categorical features ## Removed two duplicate coumns - 'decile_score','priors_count' dataset_orig = dataset_orig.drop(['id','name','first','last','compas_screening_date','dob','age','juv_fel_count','decile_score','juv_misd_count','juv_other_count','days_b_screening_arrest','c_jail_in','c_jail_out','c_case_number','c_offense_date','c_arrest_date','c_days_from_compas','c_charge_desc','is_recid','r_case_number','r_charge_degree','r_days_from_arrest','r_offense_date','r_charge_desc','r_jail_in','r_jail_out','violent_recid','is_violent_recid','vr_case_number','vr_charge_degree','vr_offense_date','vr_charge_desc','type_of_assessment','decile_score','score_text','screening_date','v_type_of_assessment','v_decile_score','v_score_text','v_screening_date','in_custody','out_custody','start','end','event'],axis=1) ## Drop NULL values dataset_orig = dataset_orig.dropna() ## Change symbolics to numerics dataset_orig['sex'] = np.where(dataset_orig['sex'] == 'Female', 1, 0) dataset_orig['race'] = np.where(dataset_orig['race'] != 'Caucasian', 0, 1) dataset_orig['priors_count'] = np.where((dataset_orig['priors_count'] >= 1 ) & (dataset_orig['priors_count'] <= 3), 3, dataset_orig['priors_count']) dataset_orig['priors_count'] = np.where(dataset_orig['priors_count'] > 3, 4, dataset_orig['priors_count']) dataset_orig['age_cat'] = np.where(dataset_orig['age_cat'] == 'Greater than 45',45,dataset_orig['age_cat']) dataset_orig['age_cat'] = np.where(dataset_orig['age_cat'] == '25 - 45', 25, dataset_orig['age_cat']) dataset_orig['age_cat'] = np.where(dataset_orig['age_cat'] == 'Less than 25', 0, dataset_orig['age_cat']) dataset_orig['c_charge_degree'] = np.where(dataset_orig['c_charge_degree'] == 'F', 1, 0) ## Rename class column dataset_orig.rename(index=str, columns={"two_year_recid": "Probability"}, inplace=True) ## Here did not rec means 0 is the favorable lable # dataset_orig['Probability'] = np.where(dataset_orig['Probability'] == 0, 1, 0) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() dataset_orig = pd.DataFrame(scaler.fit_transform(dataset_orig),columns = dataset_orig.columns) print(dataset_orig.columns) # + ## Divide into train,validation,test # dataset_orig_train, dataset_orig_test = train_test_split(dataset_orig, test_size=0.2, random_state = 0, shuffle = True) dataset_orig_train, dataset_orig_test = train_test_split(dataset_orig, test_size=0.2, shuffle = True) X_train, y_train = dataset_orig_train.loc[:, dataset_orig_train.columns != 'Probability'], dataset_orig_train['Probability'] X_test , y_test = dataset_orig_test.loc[:, dataset_orig_test.columns != 'Probability'], dataset_orig_test['Probability'] # - # Train LSR model clf = LogisticRegression(C=1.0, penalty='l2', solver='liblinear', max_iter=100) clf.fit(X_train, y_train) # Create new test by switching the value of prottected attribute same , not_same = 0,0 for index,row in dataset_orig_test.iterrows(): row_ = [row.values[0:len(row.values)-1]] y_normal = clf.predict(row_) # Here protected attribute value gets switched if row_[0][2] == 0: ## index of Sex is 0, Race is 2 row_[0][2] = 1 else: row_[0][2] = 0 y_reverse = clf.predict(row_) if y_normal[0] != y_reverse[0]: not_same += 1 else: same += 1 print(same , not_same)
Verification/Compas_Default.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Dependencies # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _kg_hide-input=false _kg_hide-output=true _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" from utillity_script_cloud_segmentation import * from utillity_script_lr_schedulers import * seed = 0 seed_everything(seed) warnings.filterwarnings("ignore") # - # ### Load data # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _kg_hide-input=true _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" train = pd.read_csv('../input/understanding_cloud_organization/train.csv') kfold_set = pd.read_csv('../input/cloud-data-split-v2/3-fold.csv') X_train = kfold_set[kfold_set['fold_0'] == 'train'] X_val = kfold_set[kfold_set['fold_0'] == 'validation'] print('Compete set samples:', len(train)) print('Train samples: ', len(X_train)) print('Validation samples: ', len(X_val)) # Preprocecss data train['image'] = train['Image_Label'].apply(lambda x: x.split('_')[0]) display(X_train.head()) # - # # Model parameters # + BACKBONE = 'efficientnetb0' BATCH_SIZE = 16 EPOCHS_PT1 = 5 EPOCHS = 15 LEARNING_RATE = 10**(-1.8) HEIGHT_PT1 = 256 WIDTH_PT1 = 384 HEIGHT = 320 WIDTH = 480 CHANNELS = 3 N_CLASSES = 4 ES_PATIENCE = 7 STEP_SIZE_TRAIN = len(X_train)//BATCH_SIZE STEP_SIZE_VALID = len(X_val)//BATCH_SIZE model_path = '71-fold1_unet_%s_%sx%s.h5' % (BACKBONE, HEIGHT, WIDTH) train_images_pt1_path = '../input/cloud-images-resized-256x384/train_images256x384/train_images/' train_images_path = '../input/cloud-images-resized-320x480/train_images320x480/train_images/' # + _kg_hide-input=false preprocessing = sm.get_preprocessing(BACKBONE) augmentation_pt1 = albu.Compose([albu.OneOf([ albu.HorizontalFlip(p=0.5), albu.VerticalFlip(p=0.5), albu.Flip(p=0.5), ], p=0.6), albu.OneOf([ albu.GridDistortion(p=0.5), albu.OpticalDistortion(p=0.2), albu.ElasticTransform(p=0.5), ], p=0.4), albu.OneOf([ albu.RandomContrast(p=0.5), albu.RandomBrightnessContrast(p=0.5), ], p=0.5), albu.OneOf([ albu.ShiftScaleRotate(scale_limit=0.2, rotate_limit=0, shift_limit=0.1, border_mode=0, p=0.5), ], p=0.3), ]) augmentation = albu.Compose([albu.OneOf([ albu.HorizontalFlip(p=0.5), albu.VerticalFlip(p=0.5), albu.Flip(p=0.5), ], p=0.6), albu.OneOf([ albu.GridDistortion(p=0.5), albu.OpticalDistortion(p=0.2), albu.ElasticTransform(p=0.5), ], p=0.4), albu.OneOf([ albu.RandomContrast(p=0.5), albu.RandomBrightnessContrast(p=0.5), ], p=0.5), albu.OneOf([ albu.RandomSizedCrop(min_max_height=(HEIGHT*0.9, HEIGHT), height=HEIGHT, width=WIDTH, p=0.5), albu.ShiftScaleRotate(scale_limit=0.2, rotate_limit=0, shift_limit=0.1, border_mode=0, p=0.5), ], p=0.3), ]) # - # ### Data generator # + _kg_hide-input=false train_generator_pt1 = DataGenerator( directory=train_images_pt1_path, dataframe=X_train, target_df=train, batch_size=BATCH_SIZE, target_size=(HEIGHT_PT1, WIDTH_PT1), n_channels=CHANNELS, n_classes=N_CLASSES, preprocessing=preprocessing, augmentation=augmentation_pt1, seed=seed) valid_generator_pt1 = DataGenerator( directory=train_images_pt1_path, dataframe=X_val, target_df=train, batch_size=BATCH_SIZE, target_size=(HEIGHT_PT1, WIDTH_PT1), n_channels=CHANNELS, n_classes=N_CLASSES, preprocessing=preprocessing, seed=seed) train_generator = DataGenerator( directory=train_images_path, dataframe=X_train, target_df=train, batch_size=BATCH_SIZE, target_size=(HEIGHT, WIDTH), n_channels=CHANNELS, n_classes=N_CLASSES, preprocessing=preprocessing, augmentation=augmentation, seed=seed) valid_generator = DataGenerator( directory=train_images_path, dataframe=X_val, target_df=train, batch_size=BATCH_SIZE, target_size=(HEIGHT, WIDTH), n_channels=CHANNELS, n_classes=N_CLASSES, preprocessing=preprocessing, seed=seed) # - # # Learning rate finder # + model = sm.Unet(backbone_name=BACKBONE, encoder_weights='imagenet', classes=N_CLASSES, activation='sigmoid', input_shape=(None, None, CHANNELS)) lr_finder = LRFinder(num_samples=len(X_train), batch_size=BATCH_SIZE, minimum_lr=1e-6, maximum_lr=10, verbose=0) optimizer = optimizers.SGD(lr=LEARNING_RATE, momentum=0.9, nesterov=True) model.compile(optimizer=optimizer, loss=sm.losses.bce_dice_loss) model.fit_generator(generator=train_generator_pt1, steps_per_epoch=STEP_SIZE_TRAIN, epochs=1, callbacks=[lr_finder]) plt.rcParams.update({'font.size': 16}) plt.figure(figsize=(24, 8)) plt.axvline(x=np.log10(LEARNING_RATE), color='red') lr_finder.plot_schedule(clip_beginning=15) # - # # Model PT 1 # + _kg_hide-output=true model = sm.Unet(backbone_name=BACKBONE, encoder_weights='imagenet', classes=N_CLASSES, activation='sigmoid', input_shape=(None, None, CHANNELS)) oneCycleLR = OneCycleLR(max_lr=LEARNING_RATE, maximum_momentum=0.9, minimum_momentum=0.9, epochs=EPOCHS_PT1, batch_size=BATCH_SIZE, samples=len(X_train), steps=STEP_SIZE_TRAIN) metric_list = [dice_coef, sm.metrics.iou_score, sm.metrics.f1_score] callback_list = [oneCycleLR] optimizer = optimizers.SGD(lr=LEARNING_RATE, momentum=0.9, nesterov=True) model.compile(optimizer=optimizer, loss=sm.losses.bce_dice_loss, metrics=metric_list) model.summary() # + _kg_hide-output=true history = model.fit_generator(generator=train_generator_pt1, steps_per_epoch=STEP_SIZE_TRAIN, validation_data=valid_generator_pt1, validation_steps=STEP_SIZE_VALID, callbacks=callback_list, epochs=EPOCHS_PT1, verbose=2).history # - # # Model # + _kg_hide-input=false _kg_hide-output=true checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True) es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1) oneCycleLR = OneCycleLR(max_lr=LEARNING_RATE, maximum_momentum=0.9, minimum_momentum=0.9, epochs=EPOCHS_PT1, batch_size=BATCH_SIZE, samples=len(X_train), steps=STEP_SIZE_TRAIN) metric_list = [dice_coef, sm.metrics.iou_score, sm.metrics.f1_score] callback_list = [checkpoint, es, oneCycleLR] optimizer = optimizers.SGD(lr=LEARNING_RATE, momentum=0.9, nesterov=True) model.compile(optimizer=optimizer, loss=sm.losses.bce_dice_loss, metrics=metric_list) model.summary() # + _kg_hide-input=true _kg_hide-output=true history = model.fit_generator(generator=train_generator, steps_per_epoch=STEP_SIZE_TRAIN, validation_data=valid_generator, validation_steps=STEP_SIZE_VALID, callbacks=callback_list, epochs=EPOCHS, verbose=2).history # - # ## Model loss graph # + _kg_hide-input=true plot_metrics(history, metric_list=['loss', 'dice_coef', 'iou_score', 'f1-score'])
Model backlog/Training/Segmentation/Kaggle/71-k-fold1-unet-effnetb0-320x480-prog-learn.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Teams # This dataset describes all the soccer teams in seven prominent soccer competitions (Italian, Spanish, German, French and English first divisions, World Cup 2018, European Cup 2016). It consists of the following fields: # # - city: the city where the team is located. For national teams it is the capital of the country; # - name: the common name of the team; # - area: information about the geographic area associated with the team; # - wyId: the identifier of the team, assigned by Wyscout; # - officialName: the official name of the team (e.g., Juventus FC); # - type: the type of the team. It is "club" for teams in the competitions for clubs and "national" for the teams in international competitions; # # # Events # This dataset describes all the events that occur during each match. Each event refers to a ball touch and contains the following information: # # - eventId: the identifier of the event's type. Each eventId is associated with an event name (see next point); # - eventName: tteamIdhe name of the event's type. There are seven types of events: pass, foul, shot, duel, free kick, offside and touch; # - subEventId: the identifier of the subevent's type. Each subEventId is associated with a subevent name (see next point); # - subEventName: the name of the subevent's type. Each event type is associated with a different set of subevent types; # - tags: a list of event tags, each one describes additional information about the event (e.g., accurate). Each event type is associated with a different set of tags; # - eventSec: the time when the event occurs (in seconds since the beginning of the current half of the match); # - id: a unique identifier of the event; # - matchId: the identifier of the match the event refers to. The identifier refers to the field "wyId" in the match dataset; # - matchPeriod: the period of the match. It can be "1H" (first half of the match), "2H" (second half of the match), "E1" (first extra time), "E2" (second extra time) or "P" (penalties time); # - playerId: the identifier of the player who generated the event. The identifier refers to the field "wyId" in a player dataset; # - positions: the origin and destination positions associated with the event. Each position is a pair of coordinates (x, y). The x and y coordinates are always in the range [0, 100] and indicate the percentage of the field from the perspective of the attacking team. In particular, the value of the x coordinate indicates the event's nearness (in percentage) to the opponent's goal, while the value of the y coordinates indicates the event's nearness (in percentage) to the right side of the field; # - teamId: the identifier of the player's team. The identifier refers to the field "wyId" in the team dataset. # # # Matches # This dataset describes all the matches made available. Each match is a document consisting of the following fields: # # - competitionId: the identifier of the competition to which the match belongs to. It is a integer and refers to the field "wyId" of the competition document; # - date and dateutc: the former specifies date and time when the match starts in explicit format (e.g., May 20, 2018 at 8:45:00 PM GMT+2), the latter contains the same information but in the compact format YYYY-MM-DD hh:mm:ss; # - duration: the duration of the match. It can be "Regular" (matches of regular duration of 90 minutes + stoppage time), "ExtraTime" (matches with supplementary times, as it may happen for matches in continental or international competitions), or "Penalities" (matches which end at penalty kicks, as it may happen for continental or international competitions); # - gameweek: the week of the league, starting from the beginning of the league; # - label: contains the name of the two clubs and the result of the match (e.g., "Lazio - Internazionale, 2 - 3"); # - roundID: indicates the match-day of the competition to which the match belongs to. During a competition for soccer clubs, each of the participating clubs plays against each of the other clubs twice, once at home and once away. The matches are organized in match-days: all the matches in match-day i are played before the matches in match-day i + 1, even tough some matches can be anticipated or postponed to facilitate players and clubs participating in Continental or Intercontinental competitions. During a competition for national teams, the "roundID" indicates the stage of the competition (eliminatory round, round of 16, quarter finals, semifinals, final); # - seasonId: indicates the season of the match; # - status: it can be "Played" (the match has officially finished), "Cancelled" (the match has been canceled for some reason), "Postponed" (the match has been postponed and no new date and time is available yet) or "Suspended" (the match has been suspended and no new date and time is available yet); # - venue: the stadium where the match was held (e.g., "Stadio Olimpico"); # - winner: the identifier of the team which won the game, or 0 if the match ended with a draw; # - wyId: the identifier of the match, assigned by Wyscout; # - teamsData: it contains several subfields describing information about each team that is playing that match: such as lineup, bench composition, list of substitutions, coach and scores: # - hasFormation: it has value 0 if no formation (lineups and benches) is present, and 1 otherwise; # - score: the number of goals scored by the team during the match (not counting penalties); # - scoreET: the number of goals scored by the team during the match, including the extra time (not counting penalties); # - scoreHT: the number of goals scored by the team during the first half of the match; # - scoreP: the total number of goals scored by the team after the penalties; # - side: the team side in the match (it can be "home" or "away"); # - teamId: the identifier of the team; # - coachId: the identifier of the team's coach; # - bench: the list of the team's players that started the match in the bench and some basic statistics about their performance during the match (goals, own goals, cards); # - lineup: the list of the team's players in the starting lineup and some basic statistics about their performance during the match (goals, own goals, cards); # - substitutions: the list of team's substitutions during the match, describing the players involved and the minute of the substitution. # # # Competitions # This dataset describes seven major soccer competitions (Italian, Spanish, German, French, English first divisions, World cup 2018, European cup 2016). Each competition is a document consisting of the following fields: # # area: it denotes the geographic area associated with the league as a sub-document, using the ISO 3166-1 specification (https://www.iso.org/iso-3166-country-codes.html); # format: the format of the competition. All competitions for clubs have value "Domestic league". The competitions for national teams have value "International cup"; # - name: the official name of the competition (e.g., Italian first division, Spanish first division, World Cup, etc.); # - type: the typology of the competition. It is "club" for the competitions for clubs and "international" for the competitions for national teams (World Cup 2018, European Cup 2016); # - wyId: the unique identifier of the competition, assigned by Wyscout. # # # 积分规则 # 赢一局加三分,输一局加零分,平一局加一分 import pandas as pd import numpy as np df_matches_Eng = pd.read_json('matches/matches_England.json') print(df_matches_Eng.columns) for i in range(len(df_matches_Eng)): if 'Everton' in df_matches_Eng['label'][i]: print(df_matches_Eng['label'][i], df_matches_Eng['teamsData'][i].keys(), df_matches_Eng['winner'][i]) df_matches_Eng # 可以根据这个表的名字查出每个球队唯一的wyID,如Everton是1623 df_teams = pd.read_json('teams.json') df_teams # + teamId_dic = {} for i in range(len(df_matches_Eng)): for teamId in df_matches_Eng['teamsData'][i].keys(): if teamId not in teamId_dic: teamId_dic[teamId] = 0 for i in range(len(df_matches_Eng)): if df_matches_Eng['winner'][i] == 0: team0 = list(df_matches_Eng['teamsData'][i].keys())[0] team1 = list(df_matches_Eng['teamsData'][i].keys())[1] teamId_dic[team0] += 1 teamId_dic[team1] += 1 else: teamId_dic[str(df_matches_Eng['winner'][i])] += 3 team_ranking = sorted(teamId_dic.items(), key=lambda x:x[1], reverse=True) # Name:id Name_teamId_matchesId = {} for index, value in enumerate(team_ranking): print(index+1, df_teams[df_teams['wyId']==int(team_ranking[index][0])]['name'].values[0],team_ranking[index][1]) Name_teamId_matchesId[df_teams[df_teams['wyId']==int(team_ranking[index][0])]['name'].values[0]] = {'teamId':team_ranking[index][0], 'matchesId':[]} for i in range(len(df_matches_Eng)): team0_id = list(df_matches_Eng['teamsData'][i].keys())[0] team1_id = list(df_matches_Eng['teamsData'][i].keys())[1] for key, value in Name_teamId_matchesId.items(): if team0_id == value['teamId']: value['matchesId'].append(df_matches_Eng['wyId'][i]) elif team1_id == value['teamId']: value['matchesId'].append(df_matches_Eng['wyId'][i]) # - Name_teamId_matchesId df_events_Eng = pd.read_json('events/events_England.json') # Everton所有的动作 df_events_Eng[df_events_Eng['teamId']==1623] # # 计算每个队的H-indicator数组 # + import pandas as pd import numpy as np def matchId_teamId_passing_table(matchId, teamId, df): player_dic = {} for i in range(len(df)): if df['playerId'][i] not in player_dic: player_dic[df['playerId'][i]] = 0 else: player_dic[df['playerId'][i]] += 1 return player_dic def sub_pitch_passing_table(matchID, teamID, df): table = {(x,y):[0,0]for x in range(101) for y in range(101)} for i in range(len(df)): table[(df['positions'][i][0]['x'], df['positions'][i][0]['y'])][0] += 1 table[(df['positions'][i][1]['x'], df['positions'][i][1]['y'])][1] += 1 return table def H_indicator(matchID, teamID, df): w = len(df) * 2 _matchId_teamId_passing_table = matchId_teamId_passing_table(matchID, teamId, df) #print(_matchId_teamId_passing_table) data = np.array([value for key, value in _matchId_teamId_passing_table.items()]) mu_p = data.mean() sigma_p = np.sqrt(data.var()) #print(sub_pitch_passing_table(matchID, teamID, df)) data = np.array([value[0]+value[1] for key, value in sub_pitch_passing_table(matchID, teamID, df).items()]) mu_z = data.mean() sigma_z = np.sqrt(data.var()) #print(mu_p, sigma_p, mu_z, sigma_z) h = 5/(1/w+1/mu_p+1/sigma_p+1/mu_z+1/sigma_z) return h def get_matchID_teamID_passing_events(matchID, teamID, df_events): df_events = df_events[df_events['teamId'] == teamID] df_events = df_events[df_events['matchId'] == matchID] df_events = df_events[df_events['eventName'] == 'Pass'] df_events = df_events.reset_index(drop=True) return df_events # - H_value = {} for name, values in Name_teamId_matchesId.items(): H_value[name] = [] for i in range(38): tmp_matchId = values['matchesId'][i] tmp_teamId = values['teamId'] #print(tmp_matchId, tmp_teamId) tmp_df = get_matchID_teamID_passing_events(int(tmp_matchId), int(tmp_teamId), df_events_Eng) #print(tmp_df) H_value[name].append(H_indicator(tmp_matchId, tmp_teamId, tmp_df)) H_value
Big_Data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/PhilippeJustine/CPEN-21A-ECE-2-1/blob/main/Final_Exam.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="fIHmPgKnTAq6" # #Final Exam # + [markdown] id="NfGSfToahj4d" # Binato, <NAME>. # | BSECE 2-1 # + [markdown] id="-KSrRd2OTP7W" # Problem Statement 1 # + colab={"base_uri": "https://localhost:8080/"} id="tmLLxdT1Ta39" outputId="62be624a-e5d9-46fe-c5cf-f602ae6ce15b" print("INPUT NUMBERS LESS THAN 5") print("") num=[] x=0 for x in range (0,10): while True: a=float(input("Input a Numerical Value:")) if a<5: print("") break; else: print(" Invalid Input! Input a numerical value <5.") continue; num.append(a) x+=1 x=0 sum=0 print("The inputs you've entered are", num) print("") for x in num: if x<5: sum=sum+x print("The sum of the inputs less than 5 is", sum ) # + [markdown] id="aJKIXU9YX1bC" # Problem Statement 2 # + colab={"base_uri": "https://localhost:8080/"} id="6UC8GWd6a0C9" outputId="e5d766ec-03ee-45bc-8f8c-6ee91e0771e7" print("INPUT FIVE NUMBERS") print("") a=1 num={} sum=0 while a<=5: num[a]=float(input("Input a Numerical Value:")) print("") a+=1 if a==6: sum=float(num[1])+float(num[5]) print("The sum of first and last inputs is", sum) # + [markdown] id="CtUn-08raCTl" # Problem Statement 3 # + colab={"base_uri": "https://localhost:8080/"} id="5ZZpILXlxPhi" outputId="da3897a7-32eb-4ac4-ae50-d63f27895b2e" print("INPUT YOUR GRADE") print("") while True: try: grade = int(input("Input your grade: ")) if grade<=float('inf'): break; else: print(" Input should be an integer") except: print(" Input should be an integer") continue; print("") if grade >= 90: print("You got an A!") else: if grade >= 80: print("You got a B!") elif grade >= 70: print("You got a C!") elif grade >= 60: print("You got a D!") else: print("You got and F!")
Final_Exam.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- my_list = [1,2,3,4,5] for number in my_list: print(number) for item in my_list: new_number = item * 5 print(new_number) for number in my_list: if number % 2 == 0: print(number) if 2 in my_list: print("true") for num in my_list: if num == 2: print("true") my_string = "<NAME>" for letter in my_string: print(letter) my_tuple = (1,2,3) for item in my_tuple: print(item * 5 - 10) my_new_list = [("a","b"),("c","d"),("e","f"),("g","h")] for element in my_new_list: print(element) for (x,y) in my_new_list: print(x) print(y) my_tuple_list = [(0,1,2),(3,4,5),(9,10,11)] for (x,y,z) in my_tuple_list: print(z) my_dictionary = {"key1": 100, "key2" : 200, "key3" : 300} for (key,value) in my_dictionary.items(): print(key)
PythonCourse-master/PythonCourse-master/13-ForLoop.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] papermill={"duration": 0.011418, "end_time": "2021-08-09T21:54:41.259899", "exception": false, "start_time": "2021-08-09T21:54:41.248481", "status": "completed"} tags=[] # # Imports # + papermill={"duration": 1.369762, "end_time": "2021-08-09T21:54:42.640222", "exception": false, "start_time": "2021-08-09T21:54:41.270460", "status": "completed"} tags=[] import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from xgboost import XGBRegressor # + [markdown] papermill={"duration": 0.009925, "end_time": "2021-08-09T21:54:42.660567", "exception": false, "start_time": "2021-08-09T21:54:42.650642", "status": "completed"} tags=[] # # Load dataset # + papermill={"duration": 11.417377, "end_time": "2021-08-09T21:54:54.088164", "exception": false, "start_time": "2021-08-09T21:54:42.670787", "status": "completed"} tags=[] train = pd.read_csv('../input/tabular-playground-series-aug-2021/train.csv') test = pd.read_csv('../input/tabular-playground-series-aug-2021/test.csv') print('train shape:',train.shape) print('test shape:',test.shape) # + papermill={"duration": 0.067284, "end_time": "2021-08-09T21:54:54.166793", "exception": false, "start_time": "2021-08-09T21:54:54.099509", "status": "completed"} tags=[] train.head() # + papermill={"duration": 0.150455, "end_time": "2021-08-09T21:54:54.328663", "exception": false, "start_time": "2021-08-09T21:54:54.178208", "status": "completed"} tags=[] # Train data X_train = train.drop(columns = ['loss','id']) y_train = train['loss'].values # Test data X_test=test.drop(columns = ['id']) print('Train set:', X_train.shape) print('Test set:', X_test.shape) # + [markdown] papermill={"duration": 0.011132, "end_time": "2021-08-09T21:54:54.351413", "exception": false, "start_time": "2021-08-09T21:54:54.340281", "status": "completed"} tags=[] # # Model training # + papermill={"duration": 0.020657, "end_time": "2021-08-09T21:54:54.383497", "exception": false, "start_time": "2021-08-09T21:54:54.362840", "status": "completed"} tags=[] xgb_params = {'n_estimators': 10000, 'learning_rate': 0.010154255408501112, 'subsample': 0.8406787739843629, 'colsample_bytree': 0.7078557348809151, 'max_depth': 7, 'reg_lambda': 93.9874814976386, 'reg_alpha': 33.26324929265035, 'random_state': 42, 'n_jobs': 4} # + papermill={"duration": 20990.197962, "end_time": "2021-08-10T03:44:44.593198", "exception": false, "start_time": "2021-08-09T21:54:54.395236", "status": "completed"} tags=[] model = XGBRegressor(**xgb_params) model.fit(X_train, y_train, eval_metric="rmse", verbose=True) # + [markdown] papermill={"duration": 0.011621, "end_time": "2021-08-10T03:44:44.616752", "exception": false, "start_time": "2021-08-10T03:44:44.605131", "status": "completed"} tags=[] # # Prediction # + papermill={"duration": 25.059535, "end_time": "2021-08-10T03:45:09.688084", "exception": false, "start_time": "2021-08-10T03:44:44.628549", "status": "completed"} tags=[] y_pred = model.predict(X_test) # + [markdown] papermill={"duration": 0.011937, "end_time": "2021-08-10T03:45:09.713591", "exception": false, "start_time": "2021-08-10T03:45:09.701654", "status": "completed"} tags=[] # # Submission # + papermill={"duration": 0.073816, "end_time": "2021-08-10T03:45:09.799697", "exception": false, "start_time": "2021-08-10T03:45:09.725881", "status": "completed"} tags=[] preds = pd.read_csv("../input/tabular-playground-series-aug-2021/sample_submission.csv") preds.loss = y_pred preds.head() # + papermill={"duration": 0.465395, "end_time": "2021-08-10T03:45:10.278434", "exception": false, "start_time": "2021-08-10T03:45:09.813039", "status": "completed"} tags=[] preds.to_csv('submission_xgbboost_101.csv', index=False)
2021/AUG/tps-aug-2021-xgboost-101-baseline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Fourier Feature Mapping on PytorchLightening with Gabor # + # %load_ext autoreload # %autoreload 2 import numpy as np import matplotlib.pyplot as plt from turboflow.utils import physics as phy import torch import pytorch_lightning as pl from pytorch_lightning.callbacks.early_stopping import EarlyStopping from turboflow.dataloaders import DataModule torch.cuda.is_available() use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") print(device) # - # ## Input data # + ## SET UP DATA path_to_data = '../data/2021-Turb2D_velocities.npy' IMGs = np.load(path_to_data) img_index = 42 X = IMGs[img_index,:,:,:2] / 255 U = IMGs[img_index,:,:,2] V = IMGs[img_index,:,:,3] t = np.arange(0,IMGs.shape[0],step=0.01) Re = 3900 W = phy.compute_vorticity(U,V) D = phy.compute_divergence(U,V) plt.subplot(141) plt.imshow(U) plt.subplot(142) plt.imshow(V) plt.subplot(143) plt.imshow(W) plt.subplot(144) plt.imshow(D) plt.tight_layout() plt.show() # - img_index = 1 X1, X2 = IMGs[img_index,:,:,0], IMGs[img_index+1,:,:,0] Y1, Y2 = IMGs[img_index,:,:,1], IMGs[img_index+1,:,:,1] U1, U2 = IMGs[img_index,:,:,2], IMGs[img_index+1,:,:,2] V1, V2 = IMGs[img_index,:,:,3], IMGs[img_index+1,:,:,3] W1 = phy.compute_vorticity(U1, V1) W2 = phy.compute_vorticity(U2, V2) D1 = phy.compute_divergence(U1, V1) D2 = phy.compute_divergence(U2, V2) # + # normalize output y = IMGs[img_index,:,:,2:4] print(y.shape) print(np.min(y), np.max(y)) y = y / np.max(np.abs(y)) print(np.min(y), np.max(y)) assert np.max(np.abs(y)) <= 1.0 assert np.max(np.abs(X)) <= 1.0 # + inputs = 2*X-1 labels = y # downsampled resultion (one every 2) ds = 2 Xtrain = inputs[::ds,::ds,:] ytrain = labels[::ds,::ds,:] Xtest = inputs ytest = labels plt.figure(figsize=(10,8)) plt.subplot(141) plt.title('[LR] X - res (%d,%d)' % Xtrain[:,:,0].shape) plt.imshow(Xtrain[:,:,0]) plt.subplot(142) plt.title('[LR] Y - res (%d,%d)' % Xtrain[:,:,1].shape) plt.imshow(Xtrain[:,:,1]) plt.subplot(143) plt.title('[LR] Ux - res (%d,%d)' % ytrain[:,:,0].shape) plt.imshow(ytrain[:,:,0]) plt.subplot(144) plt.title('[LR] Uy - res (%d,%d)' % ytrain[:,:,1].shape) plt.imshow(ytrain[:,:,1]) plt.tight_layout() plt.savefig('../figures/turboflow_train.pdf', dpi=150) plt.show() plt.figure(figsize=(10,8)) plt.subplot(141) plt.title('[HR] X - res (%d,%d)' % Xtest[:,:,0].shape) plt.imshow(Xtest[:,:,0]) plt.subplot(142) plt.title('[HR] Y - res (%d,%d)' % Xtest[:,:,1].shape) plt.imshow(Xtest[:,:,1]) plt.subplot(143) plt.title('[HR] Ux - res (%d,%d)' % ytest[:,:,0].shape) plt.imshow(ytest[:,:,0]) plt.subplot(144) plt.title('[HR] Uy - res (%d,%d)' % ytest[:,:,1].shape) plt.imshow(ytest[:,:,1]) plt.tight_layout() plt.savefig('../figures/turboflow_test.pdf', dpi=150) plt.show() # - fig, axs = plt.subplots(2,2,figsize=(20,10)) phy.plot_energy_spec(phy.powerspec(ytrain[:,:,0]), axs[0,0]) phy.plot_energy_spec(phy.powerspec(ytrain[:,:,1]), axs[0,1]) phy.plot_energy_spec(phy.powerspec(ytest[:,:,0]), axs[1,0]) phy.plot_energy_spec(phy.powerspec(ytest[:,:,1]), axs[1,1]) plt.tight_layout() plt.show() # ## Fourier Features Mapping def fourier_features(X, freqs): rFFM = X @ freqs.T return np.concatenate([np.cos(rFFM), np.sin(rFFM)], axis=-1) # + np.random.seed(666) ndim = 2 nfeatures = 512 # random Fourier Feature mapping B = np.random.normal(0, 10, size=(nfeatures, ndim)) rFFM = fourier_features(Xtrain, B) print('Fourier', rFFM.shape) # for f in range(nfeatures): # plt.subplot(121) # plt.imshow(rFFM[:,:,f]) # plt.subplot(122) # plt.imshow(rGFM[:,:,f]) # plt.show() # for f in range(5): # plt.plot(np.abs(rFFM[:,:,f].flatten())) # plt.show() # - print(Xtrain.shape) # ## LEARNING TURBULENCES # + dm_dict = {} dm_dict['None'] = DataModule( train_data=[Xtrain, ytrain], val_data=[Xtrain, ytrain], test_data =[Xtest, ytest] ) dm_dict['NonePh'] = DataModule( train_data=[Xtrain, ytrain], val_data=[Xtrain, ytrain], test_data =[Xtest, ytest] ) dm_dict['Fourier10'] = DataModule( train_data=[Xtrain, ytrain], val_data=[Xtrain, ytrain], test_data =[Xtest, ytest] ) dm_dict['Fourier10Ph'] = DataModule( train_data=[Xtrain, ytrain], val_data=[Xtrain, ytrain], test_data =[Xtest, ytest] ) # + # # test data loader # dm_dict['None'].prepare_data() # for batch in dm_dict['Fourier10'].train_dataloader(): # X, y = batch # print(X.shape) # print(y.shape) # dm_dict['None'].prepare_data() # for batch in dm_dict['Fourier10'].val_dataloader(): # X, y = batch # print(X.shape) # print(y.shape) # + import torch.nn as nn import torch.nn.functional as F def create_blockReLU(n_in, n_out): # do not work with ModuleList here either. block = nn.Sequential( nn.Linear(n_in, n_out), nn.ReLU() ) return block class MLP(pl.LightningModule): def __init__(self, layer_dimension, B, lam_div=1e-4, device=device): super().__init__() layers = [] num_layers = len(layer_dimension) blocks = [] for l in range(num_layers-2): blocks.append(create_blockReLU(layer_dimension[l], layer_dimension[l+1])) blocks.append(nn.Linear(layer_dimension[-2], layer_dimension[-1])) blocks.append(nn.Tanh()) self.mlp = nn.Sequential(*blocks) # Fourier features self.B = B if self.B is not None: self.B = torch.from_numpy(self.B).float().to(device) # PINN losses self.lam_div = lam_div def forward(self, x): if self.B is not None: x = torch.matmul(2.*np.pi*x, self.B.T) # B x F x = torch.cat([torch.sin(x), torch.cos(x)], axis=-1) # in lightning, forward defines the prediction/inference actions return self.mlp(x) def training_step(self, batch, batch_idx): # training_step defined the train loop. # It is independent of forward x, x_true = batch x.requires_grad_(True) x_pred = self.forward(x) # physics based loss - div = 0 u, v = torch.split(x_pred,1,-1) du_x = torch.autograd.grad(u, x, torch.ones_like(u), create_graph=True)[0] dv_y = torch.autograd.grad(v, x, torch.ones_like(v), create_graph=True)[0] loss_div = torch.norm(du_x[...,0] + dv_y[...,1]) # reconstruction loss loss_rec = F.mse_loss(x_pred, x_true) # losses loss = loss_rec + self.lam_div*loss_div # Logging to TensorBoard by default self.log('train_loss', loss) self.log('train_loss_data', loss_rec) self.log('train_loss_div', loss_div) return loss def validation_step(self, batch, batch_idx): x, x_true = batch x_pred = self.forward(x) loss = F.mse_loss(x_pred, x_true) psnr = 10 * np.log(2*loss.item()) self.log('valid_loss', loss, on_step=True) def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=1e-4) return optimizer model_dict = {} max_iters = int(10e3) model_dict = {} # + layers = [2] + 3*[256] + [ytest.shape[-1]] model_dict['None'] = MLP(layers, B=None, lam_div=0, device=device) early_stop_callback = EarlyStopping(monitor='valid_loss') trainer = pl.Trainer(gpus=1, check_val_every_n_epoch=200, max_epochs=max_iters, callbacks=[early_stop_callback]) trainer.fit(model_dict['None'], dm_dict['None']) # + layers = [2*512] + 3*[256] + [ytest.shape[-1]] B = np.random.normal(0, 10, size=(512, ndim)) model_dict['Fourier10'] = MLP(layers, B, lam_div=0, device=device) early_stop_callback = EarlyStopping(monitor='valid_loss') trainer = pl.Trainer(gpus=1, check_val_every_n_epoch=200, max_epochs=max_iters, callbacks=[early_stop_callback]) trainer.fit(model_dict['Fourier10'] , dm_dict['Fourier10']) # + layers = [2] + 3*[256] + [ytest.shape[-1]] max_iters = int(30e3) model_dict['NonePh'] = MLP(layers, B=None, lam_div=1e-5, device=device) early_stop_callback = EarlyStopping(monitor='valid_loss') trainer = pl.Trainer(gpus=1, check_val_every_n_epoch=200, max_epochs=max_iters, callbacks=[early_stop_callback]) trainer.fit(model_dict['NonePh'], dm_dict['NonePh']) # + layers = [2*512] + 3*[256] + [ytest.shape[-1]] B = np.random.normal(0, 10, size=(512, ndim)) max_iters = int(30e3) model_dict['Fourier10Ph'] = MLP(layers, B, lam_div=1e-5, device=device) early_stop_callback = EarlyStopping(monitor='valid_loss') trainer = pl.Trainer(gpus=1, check_val_every_n_epoch=200, max_epochs=max_iters, callbacks=[early_stop_callback]) trainer.fit(model_dict['Fourier10Ph'] , dm_dict['Fourier10Ph']) # - def my_pred(ngrid, model): model.eval().to(device) coords = np.linspace(-1, 1, ngrid, endpoint=False) coords = np.stack(np.meshgrid(coords, coords), -1) # X x Y x 2 tmp = coords[:,:,0].copy() coords[:,:,0] = coords[:,:,1] coords[:,:,1] = tmp pred = model(torch.from_numpy(coords).float().to(device)) ypred = pred.cpu().detach().numpy().squeeze() return ypred # + from scipy import interpolate def my_intr(size, X, y): xx, yy = Xtrain[:,:,0], X[:,:,1] x = np.linspace(-1,1,y[:,:,0].shape[0]) y = np.linspace(-1,1,y[:,:,0].shape[1]) z = ytrain[:,:,0] f_interp2d = interpolate.interp2d(x, y, z, kind='linear') # 'cubic' x = np.linspace(-1,1,size) y = np.linspace(-1,1,size) Ipred = f_interp2d(x, y) return Ipred # - for res in [128, 256, 512]: Npred = my_pred(res, model_dict['None']) Fpred = my_pred(res, model_dict['Fourier10']) Ipred = my_intr(res, Xtrain, ytrain) figsize = (10,10) fig, axs = plt.subplots(1,4, figsize=figsize) axs[0].imshow(Ipred) axs[0].set_title('Bilinear int.') axs[1].imshow(Npred[:,:,0]) axs[1].set_title('No mapping') axs[2].imshow(Fpred[:,:,0]) axs[2].set_title('Fourier Mapping') axs[3].imshow(ytest[:,:,0].squeeze()) axs[3].set_title('Target at %d' % 256) plt.tight_layout() plt.show() Npred256 = my_pred(256, model_dict['None']) Npred256ph = my_pred(256, model_dict['NonePh']) Fpred256 = my_pred(256, model_dict['Fourier10']) Fpred256ph = my_pred(256, model_dict['Fourier10Ph']) Ipred256 = my_intr(256,Xtrain, ytrain) Npred512 = my_pred(512, model_dict['None']) Fpred512 = my_pred(512, model_dict['Fourier10']) Npred512Ph = my_pred(512, model_dict['NonePh']) Fpred512Ph = my_pred(512, model_dict['Fourier10Ph']) Ipred512 = my_intr(512,Xtrain, ytrain) fig, axs = plt.subplots(figsize=(10,10)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_PHY.pdf', dpi=300) plt.show() fig, axs = plt.subplots(figsize=(6,6)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) # plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) # plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) # plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) # plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) # plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) # plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) # plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) # plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_TGT.pdf', dpi=300) plt.show() fig, axs = plt.subplots(figsize=(6,6)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) # plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) # plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) # plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) # plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) # plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) # plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_INT.pdf', dpi=300) plt.show() fig, axs = plt.subplots(figsize=(6,6)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) # plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) # plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) # plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) # plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_NONE.pdf', dpi=300) plt.show() fig, axs = plt.subplots(figsize=(6,6)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) # plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) # plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_RFF.pdf', dpi=300) plt.show() fig, axs = plt.subplots(figsize=(6,6)) plt.loglog(phy.powerspec(ytrain[:,:,0]), 'C0--', label='target at 128', alpha=0.5) plt.loglog(phy.powerspec(ytest[:,:,0]), 'C0--', label='target at 256', alpha=0.9) # plt.loglog(phy.powerspec(Ipred256), 'C1', label='Intrp256', alpha=0.5) plt.loglog(phy.powerspec(Ipred512), 'C1', label='Intrp512', alpha=0.8) # plt.loglog(phy.powerspec(Npred256[:,:,0]), 'C2', label='None256', alpha=0.5) plt.loglog(phy.powerspec(Npred512[:,:,0]), 'C2', label='None512', alpha=0.8) plt.loglog(phy.powerspec(Npred512Ph[:,:,0]), 'C2', label='None512Ph', alpha=1) # plt.loglog(phy.powerspec(Fpred256[:,:,0]), 'C3', label='RFF256', alpha=0.5) plt.loglog(phy.powerspec(Fpred512[:,:,0]), 'C3', label='RFF512', alpha=0.8) plt.loglog(phy.powerspec(Fpred512Ph[:,:,0]), 'C3', label='RFF512Ph', alpha=1) plt.ylim([10**-9,10]) plt.ylabel(r'Energy spectrum $\log E(k)$') plt.xlabel(r'Wavenumber, $k$') plt.legend() plt.savefig('../figures/turboflow_energy_PHY.pdf', dpi=300) plt.show()
notebooks/[TurboNeuralFourier] FFM + Physics on PytorchLightening on Turbulent Data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="lGZgLu6YkenV" colab_type="code" colab={} import tensorflow as tf # + id="2ZQ9NAQdki8m" colab_type="code" colab={} a = tf.Variable(5) # + id="sFdjqm4Rk49G" colab_type="code" colab={} g = tf.global_variables_initializer() # + id="9YZCoGezlBIm" colab_type="code" colab={} update = tf.assign(a, a+2) # + id="-tSIrowulJt9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="ac4b1660-6071-4ade-b425-ae238179dcac" with tf.Session() as sess: sess.run(g) print(sess.run(a)) for _ in range(3): sess.run(update) print(sess.run(a)) # + id="9WAJbzTplitw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="d0e61766-9649-4813-a6e6-197e5214ce13" with tf.Session() as sess: sess.run(g) print(sess.run(a)) # + id="lHbngiARltnc" colab_type="code" colab={} f = tf.placeholder(tf.float32) # + id="qIHmC9CnpTSC" colab_type="code" colab={} g = f *3 # + id="reSh5EL_pVaP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="360be230-d091-46a9-aade-3681a32217b7" with tf.Session() as sess: result = sess.run(g,feed_dict={f:[[1,2,3],[4,5,6],[7,8,9]]}) print(result) # + id="_5tPnVcHpp2w" colab_type="code" colab={}
1. Intro to Tensorflow/Tf_basics_.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Pareto sets for data analysis import pandas as pd from paretoset import paretoset import matplotlib.pyplot as plt import numpy as np COLORS = list(plt.rcParams['axes.prop_cycle'].by_key()['color']) # ## Example - finding a new apartment # + # Data on apartment prices and square meters # from central Oslo, Norway (april 2020) apartments = [(13000, 38), (16000, 55), (29000, 74), (16600, 54), (16200, 68), (12300, 42), (15000, 42), (21000, 90), (13250, 43), (24000, 88), (20000, 85), (12800, 48), (12300, 32), (16700, 66), (13000, 40), (23000, 90), (16000, 70), (24000, 77), (24000, 84), (15500, 84), (19000, 89), (12800, 33), (12900, 35), (14800, 64), (27000, 86), (19800, 79), (18800, 79), (19800, 63), (12900, 42), (15500, 65)] # Load into a dataframe df_apartments = pd.DataFrame(apartments, columns=["price", "square_meters"]) # - # + # Name, screen, RAM, HDD, weight, price computers = [("Apple MacBook Air 13,3 128GB", 13.3, 8, 128, None, 9990), ("Asus ZenBook Pure UX430UN-PURE2", 14, 8, 256, 1.3, 7999), ("HP Pavilion Gaming 15-cx0015no", 15.6, 8, 256, 2.22, 5999), ("Huawei D15 (53010TTV)", 14, 8, 256, 1.53, 5495), ("Apple MacBook Air 13.3 256GB", 13.3, 8, 256, 1.29, 12495), ("Asus Chromebook C523", 15.6, 4, 32, 1.43, 3495), ("Huawei MateBook 13 (18140)", 13, 8, 256, None, 8995), ("Asus ZenBook UX433FN-A6094T", 14, 8, 256, 1.3, 7999), ("Microsoft Surface Laptop 2", 13.5, 8, 128, 1.283, 7999), ("Lenovo Ideapad S145 (81W80028MX)", 15.6, 8, 256, 1.85, 4690), ("Huawei MateBook 13 (51204)", 13, 8, 512, 1.3, 9995), ("Apple MacBook Air (Mid 2017)", 13.3, 8, 128, 1.35, 9199), ("Acer Nitro 5 (NH.Q5XED.018)", 15.6, 16, 512, 2.2, 8499)] columns=["name", "screen", "RAM", "HDD", "weight", "price"] df_computers = pd.DataFrame(computers, columns=columns) len(df_computers) # - print(df_computers.to_latex(index=False,)) # + mask = paretoset(df_computers[["RAM", "HDD", "price"]], sense=[max, max, min]) print(df_computers[mask].to_latex(index=False,)) # + mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]].fillna(0), sense=[max, max, min, min], distinct=True) print(df_computers[mask].to_latex(index=False,)) # + mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]].fillna(0), sense=[max, max, min, min], distinct=False) print(df_computers[mask].to_latex(index=False,)) # - df_computers["weight"] = df_computers["weight"].fillna(0.1) # + mask = paretoset(df_computers[["RAM", "HDD", "weight", "price"]], sense=[max, max, min, min]) print(sum(mask)) # - df_computers[~mask] # # Visualizations # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments1.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.annotate('', xy=(35, 27000), xycoords='data', xytext=(50, 21500), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.annotate('', xy=(45, 27000), xycoords='data', xytext=(50, 23000), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.annotate('', xy=(32, 21000), xycoords='data', xytext=(50, 20000), arrowprops=dict(facecolor='black', shrink=0.05), zorder=50, fontsize=16 ) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments2.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color=COLORS[1], s=75) x = np.linspace(0, 100) for i, diff in enumerate(np.linspace(7150, 15000, num=6)): ax.plot(x, diff + 99 * x, zorder=15, color=COLORS[1], alpha=1 - 0.15 * i) ax.annotate(r'$f(\mathrm{price}, \mathrm{sqm}) = 0.99 \, \mathrm{price} + 0.01 \, (-\mathrm{sqm})$', xy=(32, 22000), xycoords='data', zorder=50, fontsize=12 ) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments3.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([42], [12300], zorder=12, color=COLORS[1], s=75) x = np.linspace(0, 100) for i, diff in enumerate(np.linspace(11800, 20500, num=6)): ax.plot(x, diff + 9 * x, zorder=15, color=COLORS[1], alpha=1 - 0.15 * i) ax.annotate(r'$f(\mathrm{price}, \mathrm{sqm}) = 0.9 \, \mathrm{price} + 0.1 \, (-\mathrm{sqm})$', xy=(32, 22000), xycoords='data', zorder=50, fontsize=12 ) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments4.pdf") # + from scipy.spatial import ConvexHull cvxhull = df_apartments.iloc[ConvexHull(df_apartments.values).vertices,:] list(cvxhull.square_meters) # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) ax.scatter([84, 42, 90, 89], [15500, 12300, 21000, 19000], zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() # 14800 64 ax.scatter([64], [14800], zorder=12, color="k", s=75) edges = pd.DataFrame({"x":[84, 42, 90, 89], "y":[15500, 12300, 21000, 19000]}) edges = edges.sort_values("x") ax.plot(edges.x, edges.y, color=COLORS[1]) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments5.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments6.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") ax.scatter(df_apartments.square_meters, df_apartments.price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) # 15500 84 left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments7.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") at_least_as_good = ((df_apartments.square_meters <= 84) & (df_apartments.price >= 15500)) dominated = at_least_as_good & ((df_apartments.square_meters < 84) | (df_apartments.price > 15500)) ax.scatter(df_apartments[~dominated].square_meters, df_apartments[~dominated].price, zorder=9) ax.scatter(df_apartments[dominated].square_meters, df_apartments[dominated].price, zorder=9, alpha=0.5, color=COLORS[0], s=25) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) # 15500 84 left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments8.pdf") plt.savefig("apartments8.png", dpi=200) # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") at_least_as_good = ((df_apartments.square_meters <= 84) & (df_apartments.price >= 15500)) dominated = at_least_as_good & ((df_apartments.square_meters < 84) | (df_apartments.price > 15500)) print(len(df_apartments[~dominated])) ax.scatter(df_apartments[~dominated].square_meters, df_apartments[~dominated].price, zorder=9) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.scatter([84], [15500], zorder=12, color="k", s=75) # 15500 84 left, bottom, width, height = (0, 15500, 84, 20000) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments9.pdf") # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Apartments for rent") mask = paretoset(df_apartments, sense=[min, max]) ax.scatter(df_apartments[~mask].square_meters, df_apartments[~mask].price, alpha=0.5, color=COLORS[0], s=25) ax.scatter(df_apartments[mask].square_meters, df_apartments[mask].price, zorder=9, color="k", s=75) ax.set_xlabel("Square meters") ax.set_ylabel("Price") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("apartments10.pdf") # - sum(mask), len(df_apartments) # + fig, ax = plt.subplots(figsize=(6, 3)) ax.set_title("Domination in a minimization problem") left, bottom, width, height = (-1, -1, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[0], alpha=0.25, zorder=7) ax.add_patch(rect) ax.text(x=-0.775, y=-0.55, s=r"Dominates $\mathbf{x}$", fontsize=14, zorder=10) left, bottom, width, height = (0, 0, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[1], alpha=0.25, zorder=7) ax.add_patch(rect) ax.text(x=0.15, y=0.45, s=r"Dominated by $\mathbf{x}$", fontsize=14, zorder=10) left, bottom, width, height = (0, -1, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[2], alpha=0.25, zorder=7) ax.add_patch(rect) left, bottom, width, height = (-1, 0, 1, 1) rect = plt.Rectangle((left, bottom), width, height, facecolor=COLORS[2], alpha=0.25, zorder=7) ax.add_patch(rect) ax.scatter([0], [0], color="k", zorder=10) ax.set_xlabel(r"$x_1$") ax.set_ylabel(r"$x_2$") ax.grid(True, ls="--", zorder=5, alpha=0.5) plt.tight_layout() plt.savefig("domination.pdf") plt.savefig("domination.png", dpi=200) # -
scripts/video/paretoset_video.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### artificial_dune_slopes # Demonstrate reduction in overwash with increasingly gentle beach slopes import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # #### Stockdon (2006) runup calculations def calcR2(H,T,slope,igflag=0): """ % % [R2,S,setup, Sinc, SIG, ir] = calcR2(H,T,slope,igflag); % % Calculated 2% runup (R2), swash (S), setup (setup), incident swash (Sinc) % and infragravity swash (SIG) elevations based on parameterizations from runup paper % also Iribarren (ir) % August 2010 - Included 15% runup (R16) statistic that, for a Guassian distribution, % represents mean+sigma. It is calculated as R16 = setup + swash/4. % In a wave tank, Palmsten et al (2010) found this statistic represented initiation of dune erosion. % % % H = significant wave height, reverse shoaled to deep water % T = deep-water peak wave period % slope = radians % igflag = 0 (default)use full equation for all data % = 1 use dissipative-specific calculations when dissipative conditions exist (Iribarren < 0.3) % = 2 use dissipative-specific (IG energy) calculation for all data % % based on: % <NAME>., <NAME>, <NAME>, and <NAME>. (2006), % Empirical parameterization of setup, swash, and runup, % Coastal Engineering, 53, 573-588. % author: <EMAIL> # Converted to Python by <EMAIL> """ g = 9.81 # make slopes positive! slope = np.abs(slope) # compute wavelength and Iribarren L = (g*T**2) / (2.*np.pi) sqHL = np.sqrt(H*L) ir = slope/np.sqrt(H/L) if igflag == 2: # use dissipative equations (IG) for ALL data R2 = 1.1*(0.039 * sqHL) S = 0.046*sqHL setup = 0.016*sqHL elif igflag == 1 and ir < 0.3: # if dissipative site use diss equations R2 = 1.1*(0.039 * sqHL) S = 0.046*sqHL setup = 0.016*sqHL else: # if int/ref site, use full equations setup = 0.35*slope*sqHL Sinc = 0.75*slope*sqHL SIG = 0.06*sqHL S = np.sqrt(Sinc**2 + SIG**2) R2 = 1.1*(setup + S/2.) R16 = 1.1*(setup + S/4.) return R2, S, setup, Sinc, SIG, ir, R16 # #### Run through various (artificial) dune heights and calculate runup, assuming constant volume of sand # + # specify incoming wave H, T H = 4. T = 12. # specify constructed dune height and angle of repose for road-side slope h_init=5 beta_repose = 30. # calculate base distance r1 (run) of road-side half of dune r1 = h_init/(np.tan(np.deg2rad(beta_repose))) # area (volume per unit width) a1 = 0.5*h_init*r1 # total initial volume assuming ocean-side is also at angle of repose. This area remains constant. a = 2.*a1 print("Initial r1, a {:.2f}, {:.2f}:".format(r1,a)) # Array of crest heights hlist = np.arange(h_init,.5,-.25) # Arrays for results runup=np.zeros_like(hlist) tanbeta=np.zeros_like(hlist) r2=np.zeros_like(hlist) # loop through series of decreasing dune heights and calculate run-up print(" h a1 a2 r1 r2 tanbeta runup") for i, h in enumerate(hlist): # new road-side base distance r1 = h/(np.tan(np.deg2rad(beta_repose))) # new road-side area a1 = 0.5*h*r1 # conserve area; calculate ocean-side area and base distance # (dont confuse r2 with runup) a2 = a - a1 r2[i] = 2.*a2/h # calculate beach slope and Stockdon runup elevation beta = np.arctan(h/r2[i]) betad = np.rad2deg(beta) tanbeta[i]=h/r2[i] runup[i],_,_,_,_,_,_ = calcR2(H,T,beta) print("{:5.1f} {:5.1f} {:5.1f} {:5.1f} {:5.1f} {:6.3f} {:5.2f}".format(h,a1,a2,r1,r2[i],tanbeta[i],runup[i])) # - plt.plot(hlist,hlist,linewidth=2,label='Dune Crest') plt.plot(hlist,runup,linewidth=2,label='Runup') plt.gca().invert_xaxis() plt.legend() plt.xlabel('Dune Crest (m)') plt.ylabel('Elevation (m)') ts = "$H_s$ = {:.0f} m, $T$ = {:.0f} s, $V$ = {:.1f} m$^3$/m".format(H,T,a) plt.title(ts) plt.plot(r2,np.ones_like(r2),'--',c='gray') plt.plot(r2,runup/hlist,linewidth=2,label='Runup/h') plt.legend() plt.xlabel('Beach distance r2 (m)') plt.ylabel('Ratio runup/h') ts = "$H_s$ = {:.0f} m, $T$ = {:.0f} s, $V$ = {:.1f} m$^3$/m".format(H,T,a) plt.title(ts)
artificial_dune_slopes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import imgaug.augmenters as iaa import mlflow.pytorch import numpy as np import torch from torch.utils.data import DataLoader from torchvision.transforms import Compose from tqdm import tqdm import sys sys.path.append('../../') from src import MODELS_DIR, MLFLOW_TRACKING_URI, DATA_PATH from src.data import TrainValTestSplitter, MURASubset from src.data.transforms import GrayScale, Resize, HistEqualisation, MinMaxNormalization, ToTensor from src.features.augmentation import Augmentation from src.models.alphagan import AlphaGan from src.models.sagan import SAGAN from src.models.autoencoders import BottleneckAutoencoder, BaselineAutoencoder, SkipConnection from src.models.gans import DCGAN from src.models.vaetorch import VAE from sklearn.metrics import roc_auc_score, average_precision_score import matplotlib.pyplot as plt # %matplotlib inline # - # ## Load sample image # + run_params = { 'image_resolution': (512, 512), 'pipeline': { 'hist_equalisation': False, 'data_source': 'XR_HAND_PHOTOSHOP', } } augmentation_seq = iaa.Sequential([iaa.Affine(fit_output=False, rotate=(20), order=[0, 1]), iaa.PadToFixedSize(*run_params['image_resolution'], position='center')]) composed_transforms = Compose([GrayScale(), HistEqualisation(active=run_params['pipeline']['hist_equalisation']), Resize(run_params['image_resolution'], keep_aspect_ratio=True), Augmentation(augmentation_seq), MinMaxNormalization(), ToTensor()]) # - # Loading image image_path = f'{DATA_PATH}/{run_params["pipeline"]["data_source"]}/patient11178/study1_negative/image3_cropped_1.png' image_path validation = MURASubset(filenames=[image_path], true_labels=[0], patients=[11178], transform=composed_transforms) for batch in validation: inp_image = batch['image'].to('cpu') inp_image_np = inp_image.numpy() plt.imshow(inp_image_np[0,:,:], cmap='gray', vmin=0, vmax=1) plt.savefig('inp_image.png', dpi=300) # ## Baseline autoencoder path_to_model = '/home/ubuntu/mlruns/1/5ca7f67c33674926a00590752c877fe5/artifacts/BaselineAutoencoder.pth' model = torch.load(path_to_model, map_location='cpu') model.eval().to('cpu') with torch.no_grad(): output = model(inp_image.view(1, *inp_image.size())) output_img = output.to('cpu').numpy()[0][0] fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) ax[0].imshow(inp_image_np[0], cmap='gray', vmin=0, vmax=1) ax[1].imshow(output_img, cmap='gray', vmin=0, vmax=1) plt.savefig('baseline_autoencoder_recon.png', dpi=300) # ## Bottleneck autoencoder path_to_model = '/home/ubuntu/mlruns/2/d4fc0453d67b4d5aaac6c353e9264716/artifacts/BottleneckAutoencoder/data/model.pth' model = torch.load(path_to_model, map_location='cpu') model.eval().to('cpu') with torch.no_grad(): output = model(inp_image.view(1, *inp_image.size())) output_img = output.to('cpu').numpy()[0][0] fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) ax[0].imshow(inp_image_np[0], cmap='gray', vmin=0, vmax=1) ax[1].imshow(output_img, cmap='gray', vmin=0, vmax=1) plt.savefig('bottleneck_autoencoder_recon.png', dpi=300) # ## Variational autoencoder path_to_model = '/home/diana/xray/models/VAE.pth' model = torch.load(path_to_model, map_location='cpu') model.eval().to('cpu') model.device = 'cpu' with torch.no_grad(): output, _, _ = model(inp_image.view(1, *inp_image.size())) output_img = output.to('cpu').numpy()[0][0] fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) ax[0].imshow(inp_image_np[0], cmap='gray', vmin=0, vmax=1) ax[1].imshow(output_img, cmap='gray', vmin=0, vmax=1) plt.savefig('vae_recon.png', dpi=300) # ## BiGAN # # + # Loading image image_path = f'{DATA_PATH}/{run_params["pipeline"]["data_source"]}/patient11178/study1_negative/image3_cropped_1.png' image_path run_params = { 'image_resolution': (128, 128), 'pipeline': { 'hist_equalisation': False, 'data_source': 'XR_HAND_PHOTOSHOP', } } augmentation_seq = iaa.Sequential([iaa.Affine(fit_output=False, rotate=(20), order=[0, 1]), iaa.PadToFixedSize(*run_params['image_resolution'], position='center')]) composed_transforms = Compose([GrayScale(), HistEqualisation(active=run_params['pipeline']['hist_equalisation']), Resize(run_params['image_resolution'], keep_aspect_ratio=True), Augmentation(augmentation_seq), MinMaxNormalization(), ToTensor()]) validation = MURASubset(filenames=[image_path], true_labels=[0], patients=[11178], transform=composed_transforms) for batch in validation: inp_image = batch['image'].to('cpu') inp_image_np = inp_image.numpy() plt.imshow(inp_image_np[0,:,:], cmap='gray', vmin=0, vmax=1) plt.savefig('inp_image.png', dpi=300) path_to_model = '/home/ubuntu/xray/models/SAGAN200.pth' # - model = torch.load(path_to_model, map_location='cpu') model.eval().to('cpu') model.device = 'cpu' with torch.no_grad(): # Forward pass z, _, _ = model.encoder(inp_image.view(1, *inp_image.size())) if len(z.size()) == 1: z = z.view(1, z.size(0)) x_rec, _, _ = model.generator(z) output_img = x_rec.numpy()[0] fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) ax[0].imshow(inp_image_np[0], cmap='gray', vmin=0, vmax=1) ax[1].imshow(output_img[0], cmap='gray', vmin=0, vmax=1) plt.savefig('bi_gan_recon.png', dpi=300) with torch.no_grad(): # Forward pass z, _, _ = model.encoder(inp_image.view(1, *inp_image.size())) if len(z.size()) == 1: z = z.view(1, z.size(0)) x_rec, _, _ = model.generator(z) p, x5, x4, x3, out_z, att2, att1 = model.discriminator(inp_image.view(1, *inp_image.size()), z) # + run_params = { 'image_resolution': (128, 128), 'pipeline': { 'hist_equalisation': False, 'data_source': 'XR_HAND_PHOTOSHOP', } } augmentation_seq = iaa.Sequential([iaa.PadToFixedSize(*run_params['image_resolution'], position='center')]) composed_transforms = Compose([GrayScale(), HistEqualisation(active=run_params['pipeline']['hist_equalisation']), Resize(run_params['image_resolution'], keep_aspect_ratio=True), Augmentation(augmentation_seq), MinMaxNormalization(), ToTensor()]) test = MURASubset(filenames=splitter.data_test.path, true_labels=splitter.data_test.label, patients=splitter.data_test.patient, transform=composed_transforms_val) test_loader = DataLoader(test, batch_size=20, shuffle=True, num_workers=5) path_to_model = '/home/ubuntu/xray/models/SAGAN200.pth' # - with torch.no_grad(): scores_mse = [] scores_proba = [] true_labels = [] for batch_data in tqdm(test_loader, total=len(test_loader)): # Format input batch inp = batch_data['image'].to(model.device) mask = batch_data['mask'].to(model.device) # Forward pass # Forward pass real_z, _, _ = model.encoder(inp) if len(real_z.size()) == 1: real_z = real_z.view(1, real_z.size(0)) reconstructed_img, _, _ = model.generator(real_z) loss = model.outer_loss(reconstructed_img, inp, mask) if model.masked_loss_on_val \ else model.outer_loss(reconstructed_img, inp) # Scores, based on output of discriminator - Higher score must correspond to positive labeled images proba = model.discriminator(inp, real_z)[0].to('cpu').numpy().reshape(-1) # Scores, based on MSE - higher MSE correspond to abnormal image if model.masked_loss_on_val: sum_loss = loss.to('cpu').numpy().sum(axis=(1, 2, 3)) sum_mask = mask.to('cpu').numpy().sum(axis=(1, 2, 3)) score = sum_loss / sum_mask else: score = loss.to('cpu').numpy().mean(axis=(1, 2, 3)) scores_mse.extend(score) scores_proba.extend(proba) true_labels.extend(batch_data['label'].numpy()) scores_mse = np.array(scores_mse) scores_proba = np.array(scores_proba) true_labels = np.array(true_labels) # + # ROC-AUC and APS roc_auc = roc_auc_score(true_labels, -scores_proba) aps = average_precision_score(true_labels, -scores_proba) print(f'ROC-AUC on test: {roc_auc}') print(f'APS on test: {aps}') # - # ## Alpha Gan path_to_model = '/home/ubuntu/xray/models/AlphaGan300_best.pth' model = torch.load(path_to_model, map_location='cpu') model.eval().to('cpu') model.device = 'cpu' with torch.no_grad(): # Forward pass z_mean, _, _, _ = model.encoder(inp_image.view(1, *inp_image.size())) # z_hat = z_mean + z_logvar * torch.randn(z_mean.size()).to(self.device) if len(z_mean.size()) == 1: z_mean = z_mean.view(1, z_mean.size(0)) x_rec, _, _ = model.generator(z_mean) output_img = x_rec.numpy()[0] fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) ax[0].imshow(inp_image_np[0], cmap='gray', vmin=0, vmax=1) ax[1].imshow(output_img[0], cmap='gray', vmin=0, vmax=1) plt.savefig('alpha_gan_recon.png', dpi=300) # + data_path = f'{DATA_PATH}/{run_params["pipeline"]["data_source"]}' splitter = TrainValTestSplitter(path_to_data=data_path) composed_transforms_val = Compose([GrayScale(), HistEqualisation(active=run_params['pipeline']['hist_equalisation']), Resize(run_params['image_resolution'], keep_aspect_ratio=True), Augmentation(iaa.Sequential( [iaa.PadToFixedSize(*run_params['image_resolution'], position='center')])), # Padding(max_shape=run_params['image_resolution']), # max_shape - max size of image after augmentation MinMaxNormalization(), ToTensor()]) test = MURASubset(filenames=splitter.data_test.path, true_labels=splitter.data_test.label, patients=splitter.data_test.patient, transform=composed_transforms_val) test_loader = DataLoader(test, batch_size=18, shuffle=True, num_workers=5) # - with torch.no_grad(): scores_mse = [] scores_proba = [] true_labels = [] for batch_data in tqdm(test_loader, total=len(test_loader)): # Format input batch inp = batch_data['image'].to(model.device) mask = batch_data['mask'].to(model.device) # Forward pass z_mean, z_logvar, _, _ = model.encoder(inp) # z_hat = z_mean + z_logvar * torch.randn(z_mean.size()).to(model.device) if len(z_mean.size()) == 1: z_mean = z_mean.view(1, z_mean.size(0)) # Decoder (generator) x_rec, _, _ = model.generator(z_mean) loss = model.outer_loss(x_rec, inp, mask) if model.masked_loss_on_val \ else model.outer_loss(x_rec, inp) # Scores, based on output of discriminator - Higher score must correspond to positive labeled images proba = model.discriminator(inp)[0].to('cpu').numpy().reshape(-1) # Scores, based on MSE - higher MSE correspond to abnormal image if model.masked_loss_on_val: sum_loss = loss.to('cpu').numpy().sum(axis=(1, 2, 3)) sum_mask = mask.to('cpu').numpy().sum(axis=(1, 2, 3)) score = sum_loss / sum_mask else: score = loss.to('cpu').numpy().mean(axis=(1, 2, 3)) scores_mse.extend(score) scores_proba.extend(proba) true_labels.extend(batch_data['label'].numpy()) scores_mse = np.array(scores_mse) scores_proba = np.array(scores_proba) true_labels = np.array(true_labels) # + roc_auc = roc_auc_score(true_labels, -scores_proba) aps = average_precision_score(true_labels, -scores_proba) print(f'ROC-AUC on test: {roc_auc}') print(f'APS on test: {aps}') # + import seaborn as sns from scipy.stats import norm fit=norm colors = ["green","orange"] color_palette = sns.color_palette(colors) sns.set_palette(color_palette) plt.figure(figsize=(8, 4)) sns.distplot(scores_proba[true_labels==1], hist=True, norm_hist=True, label='negative', kde_kws={"lw": 3, "clip": [0, 1]}, bins=15) sns.distplot(scores_proba[true_labels==0], hist=True, norm_hist=True, label='positive', kde_kws={"lw": 3, "clip": [0, 1]}, bins=15) plt.xlabel('Discriminator output probability') plt.ylabel('Density') plt.legend() plt.savefig('alpha_gan_distribution.png', dpi=300) # -
notebooks/models/2_Model vizualizations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] tags=[] # # AI solving a puzzle # # ## we are writing an algorithm to give birth to this AI, we will teach it how to solve puzzles using hints. And just like humans we will try to teach AI to learn information from the given problem, how to make smart choices. # # # ## Phase 1 # # ### Requirements : # 1. There's a puzzle board of m rows and n columns # 2. There's going to be say a bag of pieces in the form of list given to the AI # 3. We are going to give no/some inteligent information to the AI # # example : # As an input we are going to give a shuffled list of pieces # # list_pieces = [4, 5, 1, 2, 3, 8, 9 , 6, 7] # # size of list_pieces = m * n # # This is how it looks after putting it together # # | 1 | 2 | 3 | # # | 4 | 5 | 6 | # # | 7 | 8 | 9 |....[3 x 3] # # # ### Rules # 1. Sorting algorithms are strictly not allowed for directly placing pieces together # 2. [A1] : only piece around neighbours can be added # 3. # # # ### Additional info / heuristic function : # Like humans we are going to teach the AI how to find information from whatever is the input # 1. is given piece a corner piece, edge piece # -> we usually start or identify a piece as corner piece or an edge piece which helps us identify if # # # # ### Algorithm # 1. takes hint and learns how to solve puzzle using BFS and DFS separately # # # ## Phase 2 # # ### Goals - # - Instead of a numeric puzzle, use actual pictorial puzzle. # - using image processing and recognition find neighbouring puzzle pieces to complete the puzzle # # + from copy import deepcopy import random import numpy as np from random import uniform import time from IPython.display import display, clear_output # + [markdown] jp-MarkdownHeadingCollapsed=true tags=[] # # INPUTS # # m x n puzzle # - m = 4 n = 3 # + [markdown] tags=[] # # Algorithm Phase 1 # + [markdown] tags=[] # ## Requirements gathering from input # - elements = m*n elements pieces = [ x for x in range(1,elements+1)] true_pieces = deepcopy(pieces) true_pieces pieces # + # heuristic information : corner pieces dict_corner_pieces = {} corner_pieces = [ 1, n , elements, elements - (n-1)] dict_corner_pieces[corner_pieces[0]] = 'TOP_LEFT' dict_corner_pieces[corner_pieces[1]] = 'TOP_RIGHT' dict_corner_pieces[corner_pieces[2]] = 'BOTTOM_RIGHT' dict_corner_pieces[corner_pieces[3]] = 'BOTTOM_LEFT' print(f'{corner_pieces=}') h = {} for piece in true_pieces: if dict_corner_pieces.get(piece)!=None : h[piece] = dict_corner_pieces.get(piece) else : h[piece] = dict_corner_pieces.get(piece) # heuristic information : edge pieces # find top edges | b/w corner_pieces for top_edge_pieces in range(2,n): h[top_edge_pieces]='TOP' # print(top_edge_pieces) # find right edges for right_edge_pieces in range(2*n,elements,n): h[right_edge_pieces]='RIGHT' # print(right_edge_pieces) # find bottom edges for bottom_edge_pieces in range(corner_pieces[-1]+1,elements,1): h[bottom_edge_pieces]='BOTTOM' # print(bottom_edge_pieces) # find left edges for left_edge_pieces in range(1+n,corner_pieces[3],n): h[left_edge_pieces]='LEFT' # print(left_edge_pieces) h # + [markdown] tags=[] # ## Pre-requisites # - # check if goal reached def goal_test(array_2d): # print(f'{len(array_2d)== elements}') return len(array_2d)== elements # + # empty place to put in puzzle # puzzle=None puzzle = np.ndarray(shape=(m,n), dtype=float, order='F') for _m in range(0,m): for _n in range(0,n): puzzle[_m][_n]=None puzzle # - # shuffle pieces random.shuffle(pieces) pieces neighbours_index = [-n , 1 , n , -1 ] nrighbour_position = [ 'TOP', 'RIGHT', 'BOTTOM', 'LEFT'] positioning_map = { neighbour : position for neighbour, position in zip(nrighbour_position , neighbours_index)} # + print(positioning_map) def get_neighbours(piece : int): neighbours = [ x+piece for x in neighbours_index ] if ( h[piece] != None): if h[piece] == 'TOP_LEFT': neighbours[0] = None neighbours[-1] = None elif h[piece] == 'TOP': neighbours[0] = None elif h[piece] == 'TOP_RIGHT': neighbours[0] = None neighbours[1] = None elif h[piece] == 'RIGHT': neighbours[1] = None elif h[piece] == 'BOTTOM_RIGHT': neighbours[1] = None neighbours[2] = None elif h[piece] == 'BOTTOM': neighbours[2] = None elif h[piece] == 'BOTTOM_LEFT': neighbours[2] = None neighbours[-1] = None elif h[piece] == 'LEFT': neighbours[-1] = None new_dict = {position : neighbour for neighbour, position in zip(neighbours,nrighbour_position )} return new_dict get_neighbours(2) # + def aleady_placed_or_in_queue(piece_to_place:list, pieces_placed : list, piece): # print(f'check if {piece} in lists') for l_pieces in piece_to_place: l_piece = l_pieces[0] if(l_piece==piece): # print(f'{l_piece=}=={piece=} is{True}') return True for l_pieces in pieces_placed: l_piece = l_pieces[0] if(l_piece==piece): # print(f'{l_piece=}=={piece=} is{True}') return True # print(f'{piece=} Not found ') return False # + [markdown] tags=[] # ## solves using BFS search # + # pick a start node current_node = true_pieces[0] # start node pieces_placed = [] # closed list piece_to_place = [ ( current_node , None, None ) ] # open list print(f'{pieces_placed=}') print(f'{piece_to_place=}') puzzle[0][0] = current_node itr =1 while goal_test(pieces_placed)==False: clear_output(wait=True) # display(f'') # display(f'\n{itr=}') # display(f'{pieces_placed=}') # display(f'{piece_to_place=}') current_node = piece_to_place[0] current_piece = int(current_node[0]) parent = current_node[1] position_wrt_parent = current_node[2] # pieces placed if( parent ): # find location of parent # find location to place using position wrt parent for row in range(0,m): for column in range(0,n): if( puzzle[row][column] == parent ): if position_wrt_parent == 'TOP': puzzle[row-1][column] = current_piece elif position_wrt_parent == 'RIGHT': puzzle[row][column+1] = current_piece elif position_wrt_parent == 'BOTTOM': puzzle[row+1][column] = current_piece elif position_wrt_parent == 'LEFT': puzzle[row][column-1] = current_piece pieces_placed.append(current_node) display(puzzle) neighbours = get_neighbours(current_piece) for k,v in neighbours.items(): if v : neighbour = v if ( aleady_placed_or_in_queue(piece_to_place, pieces_placed,neighbour )==False ): # print(f'adding {neighbour}') piece_to_place.append( (neighbour, current_piece , k) ) piece_to_place.remove(current_node) itr+=1 time.sleep(0.5) # print(f'\n\n{pieces_placed=}') # + [markdown] tags=[] # ## solves using DFS search # + # empty place to put in puzzle # puzzle=None puzzle = np.ndarray(shape=(m,n), dtype=float, order='F') for _m in range(0,m): for _n in range(0,n): puzzle[_m][_n]=None puzzle # + # pick a start node current_node = true_pieces[0] # start node pieces_placed = [] # closed list piece_to_place = [ ( current_node , None, None ) ] # open list print(f'{pieces_placed=}') print(f'{piece_to_place=}') puzzle[0][0] = current_node itr =1 while goal_test(pieces_placed)==False: clear_output(wait=True) # display(f'') # display(f'\n{itr=}') # display(f'{pieces_placed=}') # display(f'{piece_to_place=}') current_node = piece_to_place.pop(0) current_piece = int(current_node[0]) parent = current_node[1] position_wrt_parent = current_node[2] # pieces placed if( parent ): # find location of parent # find location to place using position wrt parent for row in range(0,m): for column in range(0,n): if( puzzle[row][column] == parent ): if position_wrt_parent == 'TOP': puzzle[row-1][column] = current_piece elif position_wrt_parent == 'RIGHT': puzzle[row][column+1] = current_piece elif position_wrt_parent == 'BOTTOM': puzzle[row+1][column] = current_piece elif position_wrt_parent == 'LEFT': puzzle[row][column-1] = current_piece pieces_placed.append(current_node) display(puzzle) neighbours = get_neighbours(current_piece) for k,v in neighbours.items(): if v : neighbour = v if ( aleady_placed_or_in_queue(piece_to_place, pieces_placed,neighbour )==False ): # print(f'adding {neighbour}') piece_to_place.insert(0, (neighbour, current_piece , k) ) itr+=1 time.sleep(0.5) # print(f'\n\n{pieces_placed=}') # -
AI_solves_puzzle.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # # Spatial interpolation of point data using Inverse Distance Weighting (IDW) # ##### Author: <NAME>, August 2020 # ### Description # # We are interested in performing a basic spatial analysis on our soil pH data points within our area of interest, the Rothamsted Research campus. In this example, we will use the Inverse Distance Weighting (IDW) method to convert our data points into a continuous raster layer. # ### Importing requirements # + options("Ncpus" = parallel::detectCores()) packages <- c("gstat", "httr", "jsonlite", "lubridate", "raster", "rgdal", "sp","tidyverse") if (length(setdiff(packages, rownames(installed.packages()))) > 0) { install.packages(setdiff(packages, rownames(installed.packages())), Ncpus=getOption("Ncpus", 1L), INSTALL_opts = '--no-lock', clean = TRUE) } library(gstat) library(httr) library(jsonlite) library(lubridate) library(raster) library(rgdal) library(sp) library(tidyverse) # - # ### Accessing the data from your geospatial GraphQL query # # First, we will require a successful GraphQL query __[here](https://app.agrimetrics.co.uk/graph-explorer # )__ that includes the following: # * A bounding box for the area of interest to be used as our ***geoFilter*** # * For our geospatial query to work, we must have selected ***location*** options in our GraphQL query # * In this case, we have selected to retrieve the ***centroid*** values for each of the geospatialMeasure grid values as observed in the payload shown below # * An ***api-key*** of our own # * Depending on your subscription (trial vs. paid) amount of data available in this demo may vary # + options(stringsAsFactors = FALSE) url = "https://api.agrimetrics.co.uk/graphql" API_KEY <- Sys.getenv("API_KEY", "API_KEY") # our query searches for soilPH and invertebrate count for area within defined polygon geospatial filter # below we copy the payload from our GraphQL query using the Rothamsted bounding box for our geoFilter # note the use added quotations used around the copied GraphQL query for reading into R payload = '{"query":"query getFieldIdsNearLocation { geospatialMeasures(geoFilter: {location: {type: Polygon, coordinates: [[[-0.401073,51.80076],[-0.356222,51.80076],[-0.356222,51.819771],[-0.401073,51.819771],[-0.401073,51.80076]]]}}) { soilPH { unit value location { centroid } } soilTotalAbundanceOfInvertebrates { unit value location { centroid } } } } "}' # you will need a subscription key first # replace "api-key" with your own r<-POST(url, body = payload, add_headers(.headers = c('Accept'="application/json",'Ocp-Apim-Subscription-Key'= API_KEY,'Content-Type'="application/json",'Accept-Encoding'="gzip, deflate, br"))) # reviewing the contents of the above query # if it has worked correctly you should see our two requested geospatialMeasures (soil PH and invertebrate abundance) below str(httr::content(r, as = "parsed", type = "application/json"), max.level = 3) # - # ### Converting our query output into a data frame # + # output of request into flattened json get_data_text <- content(r, "text") get_data_json <- jsonlite::fromJSON(get_data_text, flatten = TRUE) # converting json to data frame get_data_df <- as.data.frame(get_data_json) # to examine a sample of our data frame head(get_data_df) # - # ### Converting our geospatialMeasure (soil pH) into a spatial points data frame # # Our data frame consists of two geospatialMeasures (soil pH and soil invertebrate abundance), each of which may have their own different spatial resolutions (and corresponding coordinates). Therefore, we must treat each geospatialMeasure separately. This means we will deal with each data frame one at a time. # # In this example, we will focus on the soil pH data set only. Here we convert the data set into a ***SpatialPointsDataFrames***. We will use this output to produce our interpolated data layer. # + # we must extract the soil PH data from our dataframe, to do so we need to know which columns correspond # Using the section above to examine our headers, we subset the first four columns to focus on soil PH soilph_data <-get_data_df[, 1:4] # r has a problem with unseparated coordinates, so we fix it here, by separating them soilph_data <- soilph_data %>% mutate(point_lat = unlist(map(soilph_data$data.geospatialMeasures.soilPH.location.centroid.coordinates,2)), point_long = unlist(map(soilph_data$data.geospatialMeasures.soilPH.location.centroid.coordinates,1))) # dropping coordinates column as it will cause confusion downstream soilph_data$data.geospatialMeasures.soilPH.location.centroid.coordinates <- NULL # we assign an EPSG string for coordinates system latitude and longitude latlong = "+init=epsg:4326" # making a SpatialPointsDataFrame (spdf) object soilph_spdf <- sp::SpatialPointsDataFrame(coords=soilph_data[, c("point_long", "point_lat")], data = soilph_data, proj4string=CRS(as.character(latlong))) # To produce a .shp file that can be used across a number of GIS platforms we convert the spdf object to a .shp file # but ESRI shapefiles limit headers to 10 characters, so we must rename them here using our knowledge of the column headers # using spdf 'data' slot we rename the column headers where required colnames(soilph_spdf@data)[2] = "value" colnames(soilph_spdf@data)[1] = "unit" colnames(soilph_spdf@data)[3] = "type" # - # ### Plotting our soil pH spatial points data frame # # By plotting our soil pH data points, we are able to understand the distribution of the data we have available. Using the **extent function**, we can determine the bounding box for our interpolated raster layer. # + plot(soilph_spdf, main = "Rothamsted Research - Soil pH") extent(soilph_spdf) # - # ### Spatial Interpolation # # In the step below, we will set up an **empty grid** using the bounding box we identified above to develop a reasonable area to perform our interpolation. # # Next, We will then plot our soil pH values over the empty grid. # # And finally, we will use the **Inverse Distance Weighting (IDW) method** to populate the empty grid with our new interpolated values. This final step will produce our soil pH raster layer. # # + # creating an empty grid upon which to perform # Inverse Distance Interpolation (IDW) # using a logical bounding box for area x_range <- as.numeric(c(-0.40, -0.35 )) # min/max longitude of the interpolation area y_range <- as.numeric(c(51.79, 51.82)) # min/max latitude of the interpolation area # create an empty grid of values ranging from the xmin-xmax, ymin-ymax # we use a 0.01 degree spatial resolution to build a grid that is approximately 1 km grd <- expand.grid(x = seq(from = x_range[1], to = x_range[2], by = 0.01), y = seq(from = y_range[1], to = y_range[2], by = 0.01)) # expand points to grid # - # examining our spatial points data frame head(soilph_spdf) str(soilph_spdf) # + # Convert grd object to a matrix and then turn into a spatial points object coordinates(grd) <- ~x + y # turn into a spatial pixels object gridded(grd) <- TRUE # checking projection of our grid str(grd) # + # assiging a formal coordinate reference system (CRS) as we were missing it in step above # this is important, as it needs to match the CRS assigned to the data point values we will use for interpolation # in this example we use the same CRS definition as was identified within the soilph_spdf proj4string(grd) <- CRS("+proj=longlat +datum=WGS84 +no_defs") # verifying the CRS definition is now the same as used in soilph_spdf str(grd) # - # view our empty grid plot(grd, cex = 1.5, col = "grey") # view our empty grid with our data points added plot(grd, cex = 1.5, col = "grey") plot(soilph_spdf, pch = 15, col = "red", cex = 1, add = TRUE) # Below, we perform the IDW interpolation of our soil pH data points to the empty grid. Using the idw() function, # we tell the formula "soilph_spdf ~ 1" to use the latitude and longitude coordinates and soil pH values from our spatial points data frame to perform our interpolated data layer. # # The **location** argument are the spatial points that you want to interpolate onto the grid. # The **newdata** argument is the empty grid onto which we will insert out soil pH values. # The **idp** argument is the power value used for interpolation and it controls the significance of the surrounding points on the interpolated value. Power values generally range from 0.5 to 3. The higher the power, the lesser the influence from more distance points, and the truer the surface will be to the actual data points. The lower the value, the smoother the interpolated surface will be. # + # ensure the CRS for the soilph_spdf are the same as grd crs(soilph_spdf) <- crs(grd) # interpolate the our soil pH data at the Rothamsted Research site, using a power of 1 idw_power1 <- gstat::idw(formula = value ~ 1, locations = soilph_spdf, newdata = grd, idp = 1) ## verifying the class of our interpolated data # notice that the output data is now a SpatialPixelsDataFrame class(idw_power1) # - # plotting the data, we get an plot(idw_power1, col = terrain.colors(55)) # ### Conclusion # # In this example, we have successfully performed a simple spatial interpolation on the soil pH data points derived from our GraphQL query. To do this, we converted our point data to raster format using the IDW method for spatial interpolation.
geospatial-workflow-examples/Geospatial_analysis_demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Esse script é o produto do REO2 - Lista de exercícios - da disciplina de Avanços em Genética e Melhoramento de Plantas (PGM848) do Período letivo 2020/1. Para mais informações, acesse: https://github.com/VQCarneiro/Visao-Computacional-no-Melhoramento-de-Plantas # UNIVERSIDADE FEDERAL DE LAVRAS - UFLA # DEPARTAMENTO DE BIOLOGIA - DBI # PROGRAMA DE PÓS-GRADUÇÃO EM GENÉTICA E MELHORAMENTO DE PLANTAS # DISCIPLINA PGM848 - AVANÇOS CIENTÍFICOS EM GENÉTICA E MELHORAMENTO DE PLANTAS # DOCENTE DSc. VINÍCIUS Q<NAME> # DISCENTE ERIK MICAEL DA SILVA SOUZA # REO2 - PROCESSAMENTO DE IMAGENS EM PYTHON 3 # # LISTA DE EXERCÍCIOS # Obs.: Importar as bibliotecas necessárias para resolução desta lista de exercícios: numpy, opencv (cv2) & matplotlib. import cv2 import numpy as np from matplotlib import pyplot as plt # **EXERCÍCIO 01:** # # **Selecione uma imagem a ser utilizada no trabalho prático e realize os seguintes processos utilizando # o pacote OPENCV do Python:** arquivo = "abobrinhas.png" imagem = cv2.imread(arquivo,1) imagem = cv2.cvtColor(imagem,cv2.COLOR_BGR2RGB) # **a) Apresente a imagem e as informações de número de linhas e colunas; número de canais e número total de pixels;** # - Apresentação da imagem a ser trabalhada: plt.figure('Exercício 1 - letra a') plt.imshow(imagem) plt.title("Abobrinhas") plt.show() # - Informações da imagem: lin, col, canais = np.shape(imagem) print('Número de linhas: {} '.format(lin)) print('Número de colunas: {}'.format(col)) print('Número de canais: {} ' .format(canais)) print('Número total de pixel: {}x{} ' .format(lin, col)) # **b) Faça um recorte da imagem para obter somente a área de interesse.Utilize esta imagem para a solução das próximas alternativas;** # - Recortar e salvar imagem: imagem = cv2.imread('abobrinhas.png') recorte = imagem[100:650, 120:700] cv2.imwrite("recorte.jpg", recorte) # - Converter imagem em RGB e plotar figura: img_rc = 'recorte.jpg' img_bgr = cv2.imread(img_rc,1) img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB) plt.figure('Exercício 1 - letra b') plt.imshow(img_rgb) plt.title("Recorte") plt.show() # - Informações da imagem: lin2, col2, canais2 = np.shape(img_rgb) print('Número de linhas: {}' .format(lin2)) print('Número de colunas: {}'.format(col2)) print('Número de canais: {}'.format(canais2)) print('Número total de pixel: {}x{}'.format(lin2, col2)) # **c) Converta a imagem colorida para uma de escala de cinza (intensidade) e a apresente utilizando os mapas de cores # “Escala de Cinza” e “JET”;** # - Converter imagem colorida em escala cinza: img_rc = 'recorte.jpg' img_bgr = cv2.imread(img_rc,1) img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB) img_cinza = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # - Mapas de cores: plt.figure('Exercício 1 - letra c') plt.subplot(1,2,1) plt.imshow(img_cinza, cmap = 'gray') plt.title("Escala cinza") plt.xticks([]) # Eliminar o eixo X plt.yticks([]) # #liminar o eixo y plt.colorbar(orientation = 'horizontal') plt.subplot(1,2,2) plt.imshow(img_cinza, cmap = 'jet') plt.title("JET") plt.xticks([]) # Eliminar o eixo X plt.yticks([]) # #liminar o eixo y plt.colorbar(orientation = 'horizontal') plt.show() # **d) Apresente a imagem em escala de cinza e o seu respectivo histograma; Relacione o histograma e a imagem.** # - Histograma da imagem: histograma = cv2.calcHist([img_cinza],[0],None,[256],[0,256]) #[img_cinza]: img em escala cinza; [0]: um unico canal (uma matriz); None: mascara (usada p/ selecionar um regiao da # img); 256 = n. de pontos (0-255); [0,256] = intervalo bits # - Dimensão: dim = len(histograma) print('Dimensão do Histograma: {}'.format(dim)) # - Plotar figuras: # + plt.figure('Exercício 1 - letra d') plt.subplot(1,2,1) plt.imshow(img_cinza,cmap="gray") plt.xticks([]) plt.yticks([]) plt.title("Escala cinza") plt.subplot(1,2,2) plt.plot(histograma,color = 'black') plt.title("Histograma cinza") plt.xlim([0,256]) plt.xlabel("Valores pixels") plt.ylabel("Número pixels") plt.show() # - # **e) Utilizando a imagem em escala de cinza (intensidade) realize a segmentação da imagem de # modo a remover o fundo da imagem utilizando um limiar manual e o limiar obtido pela técnica # de Otsu. Nesta questão apresente o histograma com marcação dos limiares utilizados, a # imagem limiarizada (binarizada) e a imagem colorida final obtida da segmentação. Explique # os resultados.** # - Limiarização - Thresholding: # - Limiar manual: # + limiar_cinza = 130 (L, img_limiar) = cv2.threshold(img_cinza,limiar_cinza,255,cv2.THRESH_BINARY) (L, img_limiar_inv) = cv2.threshold(img_cinza,limiar_cinza,255,cv2.THRESH_BINARY_INV) print('Limiar: {}'.format(L)) # - # - Plotar figuras - Limiar Manual: # + plt.figure('Limiar') plt.subplot(1,4,1) plt.imshow(img_cinza,cmap='gray') plt.title('Escala cinza') plt.subplot(1,4,2) plt.imshow(img_limiar,cmap='gray') plt.title('Binário - L: {} '.format(limiar_cinza)) plt.subplot(1,4,3) plt.imshow(img_limiar_inv,cmap='gray') plt.title('Binário Invertido: L: {}'.format(limiar_cinza)) plt.subplot(1,4,4) plt.plot(histograma,color = 'black') plt.axvline(x=limiar_cinza,color = 'r') plt.title("Histograma") plt.xlim([0,256]) plt.xlabel("Valores pixels") plt.ylabel("Número pixels") plt.show() # - # - Limiar técnica de Otsu: (L,img_otsu) = cv2.threshold(img_cinza,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) (L, img_otsu_inv) = cv2.threshold(img_cinza,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) print('Limiar: {}'.format(L)) # - Plotar figuras - OTSU: # + plt.figure('Limiar_Otsu') plt.subplot(1,4,1) plt.imshow(img_cinza,cmap='gray') plt.title('Escala cinza') plt.subplot(1,4,2) plt.imshow(img_otsu,cmap='gray') plt.title('OTSU - L: ' + str(L)) plt.subplot(1,4,3) plt.imshow(img_otsu_inv,cmap='gray') plt.title('OTSU Invertido: L: {}'.format(L)) plt.subplot(1,4,4) plt.plot(histograma,color = 'black') plt.axvline(x=L,color = 'r') plt.title("Histograma") plt.xlim([0,256]) plt.xlabel("Valores de pixels") plt.show() # - # - Obtendo imagem colorida segmentada: img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB) img_segmentada = cv2.bitwise_and(img_rgb,img_rgb,mask=img_limiar) # - Plotar figuras: # + plt.figure('Exercício 1 - letra e') plt.subplot(1,2,1) plt.imshow(img_cinza,cmap='gray') plt.title('Escala cinza') plt.subplot(1,2,2) plt.imshow(img_segmentada) plt.title('Segmentada - RGB') plt.show() # - # **f) Apresente uma figura contento a imagem selecionada nos sistemas RGB, Lab, HSV e YCrCb.** # - Imagem RGB: plt.figure('Exercício 1 - letra f') plt.subplot(1,4,1) plt.imshow(img_rgb) plt.title("RGB") plt.colorbar(orientation = 'horizontal') # - Imagem Lab: # + img_Lab = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2Lab) plt.subplot(1,4,2) plt.imshow(img_Lab) plt.title("Lab") plt.colorbar(orientation = 'horizontal') # - # - Imagem HSV: img_HSV = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2HSV) plt.subplot(1,4,3) plt.imshow(img_HSV) plt.title("HSV") plt.colorbar(orientation = 'horizontal') # - Imagem YCrCb: img_YCRCB = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2YCR_CB) plt.subplot(1,4,4) plt.imshow(img_YCRCB) plt.title("YCrCb") plt.colorbar(orientation = 'horizontal') plt.show() # **g) Apresente uma figura para cada um dos sistemas de cores (RGB, HSV, Lab e YCrCb) contendo a imagem de cada um dos canais e seus respectivos histogramas.** # - Imagem RGB: plt.figure('Exercício 1 - letra g') plt.subplot(2,4,1) plt.imshow(img_rgb) plt.title("RGB") # - Histograma RGB: hist_RGB = cv2.calcHist([img_rgb],[0],None,[256],[0,256]) plt.subplot(2,4,2) plt.plot(hist_RGB,color = 'black') plt.title("Histograma RGB") plt.xlim([0,256]) plt.ylabel("Número de pixels") # - Imagem Lab: img_Lab = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2Lab) plt.subplot(2,4,5) plt.imshow(img_Lab) plt.title("Lab") # - Histograma Lab: hist_Lab = cv2.calcHist([img_Lab],[0],None,[256],[0,256]) plt.subplot(2,4,6) plt.plot(hist_Lab,color = 'black') plt.title("Histograma Lab") plt.xlim([0,256]) plt.xlabel("Valores de pixels") plt.ylabel("Número de pixels") # - Imagem HSV: img_HSV = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2HSV) plt.subplot(2,4,3) plt.imshow(img_HSV) plt.title("HSV") # - Histograma HSV: hist_HSV = cv2.calcHist([img_HSV],[0],None,[256],[0,256]) plt.subplot(2,4,4) plt.plot(hist_HSV,color = 'black') plt.title("Histograma HSV") plt.xlim([0,256]) plt.ylabel("Número de pixels") # - Imagem YCrCb: img_YCRCB = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2YCR_CB) plt.subplot(2,4,7) plt.imshow(img_YCRCB) plt.title("YCrCb") # - Histograma YCrCb: # + hist_YCrCb = cv2.calcHist([img_YCRCB],[0],None,[256],[0,256]) plt.subplot(2,4,8) plt.plot(hist_YCrCb,color = 'black') plt.title("Histograma YCrCb") plt.xlim([0,256]) plt.xlabel("Valores de pixels") plt.ylabel("Número de pixels") plt.show() # - # **h) Encontre o sistema de cor e o respectivo canal que propicie melhor segmentação da imagem # de modo a remover o fundo da imagem utilizando limiar manual e limiar obtido pela técnica # de Otsu. Nesta questão apresente o histograma com marcação dos limiares utilizados, a # imagem limiarizada (binarizada) e a imagem colorida final obtida da segmentação. Explique # os resultados e sua escolha pelo sistema de cor e canal utilizado na segmentação. Nesta # questão apresente a imagem limiarizada (binarizada) e a imagem colorida final obtida da # segmentação.** # - Leitura da imagem: img_rc = 'recorte.jpg' img_bgr = cv2.imread(img_rc,1) img_HSV = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2HSV) img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB) H,S,V = cv2.split(img_HSV) # - Histograma de imagem: hist_H = cv2.calcHist([img_HSV],[0],None,[256],[0,256]) hist_S = cv2.calcHist([img_HSV],[1],None,[256],[0,256]) hist_V = cv2.calcHist([img_HSV],[2],None,[256],[0,256]) # - Limiar manual: limiar_H = 80 (L_H, img_limiar_H) = cv2.threshold(H,limiar_H,255,cv2.THRESH_BINARY) limiar_S = 90 (L_S, img_limiar_S) = cv2.threshold(S,limiar_S,255,cv2.THRESH_BINARY_INV) limiar_V = 180 (L_V, img_limiar_V) = cv2.threshold(V,limiar_V,255,cv2.THRESH_BINARY_INV) # - Limiarização - Thresholding - OTSU: (L_H, img_limiar_H) = cv2.threshold(H,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) (L_S, img_limiar_S) = cv2.threshold(S,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) (L_V, img_limiar_V) = cv2.threshold(V,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # - Plotar imagens - Limiar manual: # + plt.figure('Exercício 1 - letra h.1') plt.subplot(3,4,1) plt.imshow(img_HSV[:,:,0],cmap='gray') plt.title("H") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,2) plt.plot(hist_H,color = 'black') plt.axvline(x=limiar_H, color = 'blue') plt.title("Histograma - H") plt.xlim([0,256]) plt.ylabel("Número pixels") plt.xticks([]) plt.subplot(3,4,5) plt.imshow(img_HSV[:,:,1],cmap='gray') plt.title("S") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,6) plt.plot(hist_S,color = 'black') plt.axvline(x=limiar_S,color = 'red') plt.title("Histograma - S") plt.xlim([0,256]) plt.ylabel("Número pixels") plt.xticks([]) plt.subplot(3,4,9) plt.imshow(img_HSV[:,:,2],cmap='gray') plt.title("V") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,10) plt.plot(hist_V,color = 'black') plt.axvline(x=limiar_V,color = 'green') plt.title("Histograma - V ") plt.xlim([0,256]) plt.xlabel("Valores Pixels") plt.ylabel("Número de Pixels") # - # - Plotar Imagens - <NAME>: # + plt.subplot(3,4,3) plt.imshow(img_HSV[:,:,0],cmap='gray') plt.title("H") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,4) plt.plot(hist_H,color = 'black') plt.axvline(x=L_H, color = 'blue') plt.title("Histograma - H (Otsu)") plt.xlim([0,256]) plt.ylabel("Número pixels") plt.xticks([]) plt.subplot(3,4,7) plt.imshow(img_HSV[:,:,1],cmap='gray') plt.title("S") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,8) plt.plot(hist_S,color = 'black') plt.axvline(x=L_S,color = 'red') plt.title("Histograma - S (Otsu)") plt.xlim([0,256]) plt.ylabel("Número pixels") plt.xticks([]) plt.subplot(3,4,11) plt.imshow(img_HSV[:,:,2],cmap='gray') plt.title("V") plt.xticks([]) plt.yticks([]) plt.subplot(3,4,12) plt.plot(hist_V,color = 'black') plt.axvline(x=L_V,color = 'green') plt.title("Histograma - V (Otsu)") plt.xlim([0,256]) plt.xlabel("Valores Pixels") plt.ylabel("Número de Pixels") plt.show() # - # - Obter imagem colorida segmentada: img_segm = cv2.bitwise_and(img_HSV,img_HSV,mask=img_limiar_S) # - Plotar imagem colorida segmentada: # + plt.figure('Exercício 1 - letra h.2') plt.subplot(1,3,1) plt.imshow(img_rgb,cmap="gray") plt.title("Original") plt.subplot(1,3,2) plt.imshow(img_HSV,cmap="gray") plt.title("HSV") plt.subplot(1,3,3) plt.imshow(img_segm) plt.title('Segmentada') plt.show() # - # **i) Obtenha o histograma de cada um dos canais da imagem em RGB, utilizando como mascara a imagem limiarizada (binarizada) da letra h.** # - Histograma de imagem: (L_S, img_limiar_S) = cv2.threshold(S,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) hist_r = cv2.calcHist([img_rgb],[0],img_limiar_S,[256],[0,256]) hist_g = cv2.calcHist([img_rgb],[1],img_limiar_S,[256],[0,256]) hist_b = cv2.calcHist([img_rgb],[2],img_limiar_S,[256],[0,256]) # - Plotar Imagem RGB: # + plt.figure('Exercício 1 - letra i') plt.subplot(2,3,1) plt.imshow(img_rgb[:,:,0],cmap='gray') plt.title("R") plt.subplot(2,3,4) plt.plot(hist_r) plt.axvline(x=L_S, color='black') plt.title("Histograma - R") plt.xlim([0,256]) plt.xlabel("Valores Pixels") plt.ylabel("Número de Pixels") plt.subplot(2,3,2) plt.imshow(img_rgb[:,:,1],cmap='gray') plt.title("G") plt.subplot(2,3,5) plt.plot(hist_g,color = 'red') plt.axvline(x=L_S, color='black') plt.title("Histograma - G") plt.xlim([0,256]) plt.xlabel("Valores Pixels") plt.ylabel("Número de Pixels") plt.subplot(2,3,3) plt.imshow(img_rgb[:,:,2],cmap='gray') plt.title("B") plt.subplot(2,3,6) plt.plot(hist_b,color = 'green') plt.axvline(x=L_S, color='black') plt.title("Histograma - B") plt.xlim([0,256]) plt.xlabel("Valores Pixels") plt.ylabel("Número de Pixels") plt.show() # - # **j) Realize operações aritméticas na imagem em RGB de modo a realçar os aspectos de seu interesse. Exemplo (2*R-0.5*G). Explique a sua escolha pelas operações aritméticas. Segue abaixo algumas sugestões.** # - Operação aritmética na imagem RGB (-0.5*B)/R : # + operacao_img = -0.5*img_rgb[:,:,2] / img_rgb[:,:,0] print(operacao_img) print(' ') plt.figure('Exercício 1 - letra j') plt.subplot(1,3,1) plt.imshow(img_rgb,cmap='gray') plt.title("RGB") plt.subplot(1,3,2) plt.imshow(operacao_img,cmap='gray') plt.title("(-0.5*B)/R - Cinza") plt.colorbar(orientation = 'horizontal') plt.subplot(1,3,3) plt.imshow(operacao_img,cmap='jet') plt.title("(-0.5*B)/R - JET") plt.colorbar(orientation = 'horizontal') plt.show() # -
REO2 - PROCESSAMENTO DE IMAGENS EM PYTHON 3/REO2-ErikSouza.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] papermill={"duration": 0.038653, "end_time": "2020-12-22T13:22:05.527315", "exception": false, "start_time": "2020-12-22T13:22:05.488662", "status": "completed"} tags=[] # # Titanic - Solution - Easiest Way # # # ### I used following techniques in this notebook # 1. Loading Data using Pandas # 2. Checking varible type for each column # 3. Checking number of nulls in each column # 4. Finding column in Dataset # 5. Drop useless columns # 6. Handling Missing value with Median and Mode # 7. Checking occurance of each category # 8. Data Visualiztion using Matplotlib # 9. Checking Ouliers # 10. Handling Categorical Data using Get_Dummies() # 11. Concatenating the Original Dataset & the One after creating Dummies # 12. Seggregating X & y. # 13. Preprocessing Numeric Data using StandardScaler # 14. Dropping useless columns after we get_dummies() # 15. Splitting using train_test_split # 16. Using Random Forest as ML model # 17. Predicting & Scoring the Trained Model # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" papermill={"duration": 0.049761, "end_time": "2020-12-22T13:22:05.614206", "exception": false, "start_time": "2020-12-22T13:22:05.564445", "status": "completed"} tags=[] # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session # + papermill={"duration": 1.115228, "end_time": "2020-12-22T13:22:06.767819", "exception": false, "start_time": "2020-12-22T13:22:05.652591", "status": "completed"} tags=[] import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # + [markdown] papermill={"duration": 0.03845, "end_time": "2020-12-22T13:22:06.844383", "exception": false, "start_time": "2020-12-22T13:22:06.805933", "status": "completed"} tags=[] # ### **1. Loading Data using Pandas** # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" papermill={"duration": 0.100921, "end_time": "2020-12-22T13:22:06.983438", "exception": false, "start_time": "2020-12-22T13:22:06.882517", "status": "completed"} tags=[] train=pd.read_csv('/kaggle/input/titanic/train.csv') test=pd.read_csv('/kaggle/input/titanic/test.csv') # train.head() test.head() # + [markdown] papermill={"duration": 0.038107, "end_time": "2020-12-22T13:22:07.060211", "exception": false, "start_time": "2020-12-22T13:22:07.022104", "status": "completed"} tags=[] # ### 2. Checking varible type for each column # + papermill={"duration": 0.059715, "end_time": "2020-12-22T13:22:07.158385", "exception": false, "start_time": "2020-12-22T13:22:07.09867", "status": "completed"} tags=[] train.info() # + [markdown] papermill={"duration": 0.038884, "end_time": "2020-12-22T13:22:07.237253", "exception": false, "start_time": "2020-12-22T13:22:07.198369", "status": "completed"} tags=[] # ### 3. Checking number of nulls in each column # + papermill={"duration": 0.052309, "end_time": "2020-12-22T13:22:07.329838", "exception": false, "start_time": "2020-12-22T13:22:07.277529", "status": "completed"} tags=[] train.isnull().sum() # + [markdown] papermill={"duration": 0.03935, "end_time": "2020-12-22T13:22:07.408888", "exception": false, "start_time": "2020-12-22T13:22:07.369538", "status": "completed"} tags=[] # ### 4. Finding column in Dataset # + papermill={"duration": 0.04947, "end_time": "2020-12-22T13:22:07.498111", "exception": false, "start_time": "2020-12-22T13:22:07.448641", "status": "completed"} tags=[] train.columns # + papermill={"duration": 0.050748, "end_time": "2020-12-22T13:22:07.58923", "exception": false, "start_time": "2020-12-22T13:22:07.538482", "status": "completed"} tags=[] test.columns # + [markdown] papermill={"duration": 0.040607, "end_time": "2020-12-22T13:22:07.670837", "exception": false, "start_time": "2020-12-22T13:22:07.63023", "status": "completed"} tags=[] # ### 5. Drop useless columns # + papermill={"duration": 0.06659, "end_time": "2020-12-22T13:22:07.779557", "exception": false, "start_time": "2020-12-22T13:22:07.712967", "status": "completed"} tags=[] train.drop(columns=['Name', 'Ticket', 'Cabin'], axis=1, inplace=True) test.drop(columns= ['Name', 'Ticket', 'Cabin'], axis=1, inplace= True) # train.head() test.head() # + [markdown] papermill={"duration": 0.041744, "end_time": "2020-12-22T13:22:07.863309", "exception": false, "start_time": "2020-12-22T13:22:07.821565", "status": "completed"} tags=[] # ### 6. Handling Missing value with Median and Mode # # + papermill={"duration": 0.057761, "end_time": "2020-12-22T13:22:07.963506", "exception": false, "start_time": "2020-12-22T13:22:07.905745", "status": "completed"} tags=[] train['Age'].fillna(train['Age'].median(), inplace=True) train['Embarked'].fillna(train['Embarked'].mode()[0], inplace=True) train.isnull().sum() # + papermill={"duration": 0.059803, "end_time": "2020-12-22T13:22:08.065674", "exception": false, "start_time": "2020-12-22T13:22:08.005871", "status": "completed"} tags=[] test['Age'].fillna(test['Age'].median(), inplace=True) test['Fare'].fillna(test['Fare'].mean(), inplace=True) test['Embarked'].fillna(test['Embarked'].mode()[0], inplace=True) test.isnull().sum() # + [markdown] papermill={"duration": 0.043766, "end_time": "2020-12-22T13:22:08.152357", "exception": false, "start_time": "2020-12-22T13:22:08.108591", "status": "completed"} tags=[] # ### 7. Checking occurance of each category # + papermill={"duration": 0.055006, "end_time": "2020-12-22T13:22:08.250411", "exception": false, "start_time": "2020-12-22T13:22:08.195405", "status": "completed"} tags=[] train['Survived'].value_counts() # + papermill={"duration": 0.057072, "end_time": "2020-12-22T13:22:08.351892", "exception": false, "start_time": "2020-12-22T13:22:08.29482", "status": "completed"} tags=[] train['Pclass'].value_counts() # + papermill={"duration": 0.057222, "end_time": "2020-12-22T13:22:08.453657", "exception": false, "start_time": "2020-12-22T13:22:08.396435", "status": "completed"} tags=[] train['Sex'].value_counts() # + papermill={"duration": 0.056867, "end_time": "2020-12-22T13:22:08.555477", "exception": false, "start_time": "2020-12-22T13:22:08.49861", "status": "completed"} tags=[] train['SibSp'].value_counts() # + papermill={"duration": 0.057497, "end_time": "2020-12-22T13:22:08.658221", "exception": false, "start_time": "2020-12-22T13:22:08.600724", "status": "completed"} tags=[] train['Parch'].value_counts() # + papermill={"duration": 0.079347, "end_time": "2020-12-22T13:22:08.791469", "exception": false, "start_time": "2020-12-22T13:22:08.712122", "status": "completed"} tags=[] train['Embarked'].value_counts() # + [markdown] papermill={"duration": 0.050998, "end_time": "2020-12-22T13:22:08.895935", "exception": false, "start_time": "2020-12-22T13:22:08.844937", "status": "completed"} tags=[] # ### 8. Data Visualiztion using Matplotlib # + papermill={"duration": 0.22348, "end_time": "2020-12-22T13:22:09.166059", "exception": false, "start_time": "2020-12-22T13:22:08.942579", "status": "completed"} tags=[] sns.countplot(x='Survived', data= train) # + papermill={"duration": 0.17903, "end_time": "2020-12-22T13:22:09.393246", "exception": false, "start_time": "2020-12-22T13:22:09.214216", "status": "completed"} tags=[] sns.countplot(x='Sex', data= train) # + papermill={"duration": 0.210427, "end_time": "2020-12-22T13:22:09.653311", "exception": false, "start_time": "2020-12-22T13:22:09.442884", "status": "completed"} tags=[] sns.countplot(x='Survived', hue='Sex', data= train) # + papermill={"duration": 0.250441, "end_time": "2020-12-22T13:22:09.955066", "exception": false, "start_time": "2020-12-22T13:22:09.704625", "status": "completed"} tags=[] sns.countplot(x='Survived', hue='Pclass', data= train) # + papermill={"duration": 0.296428, "end_time": "2020-12-22T13:22:10.304238", "exception": false, "start_time": "2020-12-22T13:22:10.00781", "status": "completed"} tags=[] sns.boxplot(x='Survived', y= 'Age', hue='Sex', data= train) # + papermill={"duration": 0.30521, "end_time": "2020-12-22T13:22:10.663772", "exception": false, "start_time": "2020-12-22T13:22:10.358562", "status": "completed"} tags=[] sns.boxplot(x='Pclass', y= 'Fare', data= train) # + [markdown] papermill={"duration": 0.055297, "end_time": "2020-12-22T13:22:10.774018", "exception": false, "start_time": "2020-12-22T13:22:10.718721", "status": "completed"} tags=[] # ### 9. Checking Ouliers # + papermill={"duration": 0.2942, "end_time": "2020-12-22T13:22:11.12318", "exception": false, "start_time": "2020-12-22T13:22:10.82898", "status": "completed"} tags=[] train.plot(kind='box') # + papermill={"duration": 0.297691, "end_time": "2020-12-22T13:22:11.479212", "exception": false, "start_time": "2020-12-22T13:22:11.181521", "status": "completed"} tags=[] cols= ['Age', 'SibSp', 'Parch', 'Fare'] train[cols]= train[cols].clip(lower= train[cols].quantile(0.15), upper= train[cols].quantile(0.85), axis=1) train.drop(columns=['Parch'], axis=1, inplace=True) train.plot(kind='box', figsize= (10,8)) # no outliers # + papermill={"duration": 0.290928, "end_time": "2020-12-22T13:22:11.828444", "exception": false, "start_time": "2020-12-22T13:22:11.537516", "status": "completed"} tags=[] test.plot(kind='box', figsize= (10,8)) # there are outliers # + papermill={"duration": 0.29852, "end_time": "2020-12-22T13:22:12.186735", "exception": false, "start_time": "2020-12-22T13:22:11.888215", "status": "completed"} tags=[] test[cols]= test[cols].clip(lower= test[cols].quantile(0.15), upper= test[cols].quantile(0.85), axis=1) test.drop(columns=['Parch'], axis=1, inplace=True) test.plot(kind='box', figsize= (10,8)) # no outliers # + [markdown] papermill={"duration": 0.07006, "end_time": "2020-12-22T13:22:12.318118", "exception": false, "start_time": "2020-12-22T13:22:12.248058", "status": "completed"} tags=[] # ### 10. Handling Categorical Data using Get_Dummies() # #### We use *'drop_first'* to avoid **Dummy Trap** # + papermill={"duration": 0.092901, "end_time": "2020-12-22T13:22:12.483298", "exception": false, "start_time": "2020-12-22T13:22:12.390397", "status": "completed"} tags=[] train1= pd.get_dummies(train, columns=['Pclass', 'Sex', 'Embarked' ], drop_first= True) test1= pd.get_dummies(test, columns=['Pclass', 'Sex', 'Embarked' ], drop_first= True) # + [markdown] papermill={"duration": 0.074403, "end_time": "2020-12-22T13:22:12.619145", "exception": false, "start_time": "2020-12-22T13:22:12.544742", "status": "completed"} tags=[] # ### 11. Concatenating the Original Dataset & the One after creating Dummies*(get_dummies() creates a new DF containing JUST the dummies, MOST People get wrong here)* # + papermill={"duration": 0.078556, "end_time": "2020-12-22T13:22:12.760754", "exception": false, "start_time": "2020-12-22T13:22:12.682198", "status": "completed"} tags=[] train2=pd.concat([train,train1],axis=1) test2=pd.concat([test,test1],axis=1) # + [markdown] papermill={"duration": 0.062233, "end_time": "2020-12-22T13:22:12.884897", "exception": false, "start_time": "2020-12-22T13:22:12.822664", "status": "completed"} tags=[] # ### 12. Splitting X & y # + papermill={"duration": 0.076024, "end_time": "2020-12-22T13:22:13.022351", "exception": false, "start_time": "2020-12-22T13:22:12.946327", "status": "completed"} tags=[] y_train= train2['Survived'] X_train= train2.drop(['PassengerId','Survived'],axis=1) # y_test= test2['Survived'] #X_test=test2.drop(['PassengerId','Survived'],axis=1) # + [markdown] papermill={"duration": 0.061281, "end_time": "2020-12-22T13:22:13.150012", "exception": false, "start_time": "2020-12-22T13:22:13.088731", "status": "completed"} tags=[] # ### 13. Preprocessing Numeric Data using StandardScaler # + papermill={"duration": 0.164693, "end_time": "2020-12-22T13:22:13.375756", "exception": false, "start_time": "2020-12-22T13:22:13.211063", "status": "completed"} tags=[] from sklearn.preprocessing import StandardScaler ss= StandardScaler() features= ['Age', 'SibSp', 'Fare'] X_train[features]= ss.fit_transform(X_train[features]) X_test[features]= ss.fit_transform(X_test[features]) # X_train.head() # X_test.head() # + [markdown] papermill={"duration": 0.062153, "end_time": "2020-12-22T13:22:13.50034", "exception": false, "start_time": "2020-12-22T13:22:13.438187", "status": "completed"} tags=[] # ### 14. Dropping useless columns after we get_dummies() # + papermill={"duration": 0.072945, "end_time": "2020-12-22T13:22:13.635557", "exception": false, "start_time": "2020-12-22T13:22:13.562612", "status": "completed"} tags=[] # X_train=X_train.drop(['Pclass','Sex','Embarked'],axis=1) X_test=X_test.drop(['Pclass','Sex','Embarked'],axis=1) # X_train X_test # + [markdown] papermill={"duration": 0.061971, "end_time": "2020-12-22T13:22:13.76096", "exception": false, "start_time": "2020-12-22T13:22:13.698989", "status": "completed"} tags=[] # ### 15. Splitting using train_test_split # + papermill={"duration": 0.136244, "end_time": "2020-12-22T13:22:13.959567", "exception": false, "start_time": "2020-12-22T13:22:13.823323", "status": "completed"} tags=[] # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) # + [markdown] papermill={"duration": 0.063481, "end_time": "2020-12-22T13:22:14.086071", "exception": false, "start_time": "2020-12-22T13:22:14.02259", "status": "completed"} tags=[] # ### 16. Using Random Forest as ML model # + papermill={"duration": 1.629307, "end_time": "2020-12-22T13:22:15.778443", "exception": false, "start_time": "2020-12-22T13:22:14.149136", "status": "completed"} tags=[] #Using little bit of Hyperparameter Tuning from sklearn.ensemble import RandomForestClassifier clf=RandomForestClassifier(n_estimators=500) clf.fit(X_train,y_train) # + [markdown] papermill={"duration": 0.0634, "end_time": "2020-12-22T13:22:15.905545", "exception": false, "start_time": "2020-12-22T13:22:15.842145", "status": "completed"} tags=[] # ### 17. Predicting & Scoring the Trained Model # + papermill={"duration": 0.261393, "end_time": "2020-12-22T13:22:16.23025", "exception": false, "start_time": "2020-12-22T13:22:15.968857", "status": "completed"} tags=[] predictions= clf.predict(X_test) clf.score(X_test, y_test) # + [markdown] papermill={"duration": 0.06412, "end_time": "2020-12-22T13:22:16.360349", "exception": false, "start_time": "2020-12-22T13:22:16.296229", "status": "completed"} tags=[] # ### 18. Saving the output in a file # + papermill={"duration": 0.520732, "end_time": "2020-12-22T13:22:16.945613", "exception": false, "start_time": "2020-12-22T13:22:16.424881", "status": "completed"} tags=[] submission= pd.DataFrame(data=predictions) print(submission.head()) filename= 'titanic_prediction1.csv' submission.to_csv(filename,index=False) # + [markdown] papermill={"duration": 0.064108, "end_time": "2020-12-22T13:22:17.07454", "exception": false, "start_time": "2020-12-22T13:22:17.010432", "status": "completed"} tags=[] # #### If you like this notebook, give an upvote. Any suggestions or comments are appreciated.
Soln.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="XZo7OdQ16Axh" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}} # %matplotlib inline import datetime import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import seaborn as sns sns.set() sns.set(font_scale=1.5) def get_minutes(start_date, end_date): date_delta = end_date - start_date return divmod(date_delta.days * 86400 + date_delta.seconds, 60)[0] def millions(x, pos): return '%1.0fM' % (x*1e-6) formatter = FuncFormatter(millions) # + id="nJ1mJsAG6WI_" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}} # Funds to distribute COINS = 40000000 # Reference Dates START_DATE = datetime.datetime(2018, 4, 1, 0, 0, 0) # Example start date. END_DATE = datetime.datetime(2218, 4, 1, 0, 0, 0) # Example end date. # + id="qIilfGsZFYmj" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}, "output_extras": [{"item_id": 1}], "base_uri": "https://localhost:8080/", "height": 51} outputId="0aaeb9f2-d805-4bc5-dcd4-def64e047717" executionInfo={"status": "ok", "timestamp": 1519035663049, "user_tz": -60, "elapsed": 572, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-xMs-waRqjDU/AAAAAAAAAAI/AAAAAAAANcw/nIsP9G7H0rg/s50-c-k-no/photo.jpg", "userId": "113812738982213408956"}} TOTAL_MINUTES = get_minutes(START_DATE, END_DATE) print("Total Minutes between {} and {} = {}".format(START_DATE, END_DATE ,TOTAL_MINUTES)) # Exponential decay. Lambda # ln(N) = -lt + C # N(t) = e**C * e**(-lt) = N0 * e**(-lt) # # ln[N200]= -l(t200) + ln[N0] # l = -( ln[N200] - ln[N0] ) / (t200) # N200=1 # ln[N200] = 0 l = np.log(COINS) / TOTAL_MINUTES print("Lambda = {}".format(l)) # + id="PeSisWKAIYTy" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}} def remaining_funds_shor(X): Y = COINS * np.exp(-l*X) * 10**9 return Y def emission_shor(X): Y = remaining_funds_shor(X-1) - remaining_funds_shor(X) return Y # + id="crllYQpm6ChL" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}, "output_extras": [{"item_id": 1}, {"item_id": 2}], "base_uri": "https://localhost:8080/", "height": 815} outputId="b31ec4f6-7c40-4511-9521-806757f011f4" executionInfo={"status": "ok", "timestamp": 1519035664655, "user_tz": -60, "elapsed": 861, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-xMs-waRqjDU/<KEY>nIsP9G7H0rg/s50-c-k-no/photo.jpg", "userId": "113812738982213408956"}} def PlotCharts(X, title, use_millions=True): # Plot results Y = remaining_funds_shor(X) * 10**-9 fig = plt.figure(figsize=(12, 6)) plt.plot(X, Y, 'b.') plt.title(title) if use_millions: ax = plt.gca().yaxis.set_major_formatter(formatter) ax = plt.gca().xaxis.set_major_formatter(formatter) plt.xlabel(r'block number') plt.ylabel(r'Remaining Funds (Quanta)') plt.show() dY = emission_shor(X) * 10**-9 fig = plt.figure(figsize=(12, 6)) plt.plot(X, dY, 'b.') plt.title(title) ax = plt.gca().xaxis.set_major_formatter(formatter) plt.xlabel(r'block number') plt.ylabel(r'Emission (Quanta)') plt.show() X = np.linspace(0., TOTAL_MINUTES/200*20, 400) PlotCharts(X, "First 20 Years") # + id="sWcwB-w4MCwu" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}, "output_extras": [{"item_id": 1}, {"item_id": 2}], "base_uri": "https://localhost:8080/", "height": 815} outputId="6ffa2b62-ae10-49ce-c68c-194a9c6c8464" executionInfo={"status": "ok", "timestamp": 1519035665453, "user_tz": -60, "elapsed": 772, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-xMs-waRqjDU/AAAAAAAAAAI/AAAAAAAANcw/nIsP9G7H0rg/s50-c-k-no/photo.jpg", "userId": "113812738982213408956"}} X = np.linspace(0., TOTAL_MINUTES, 400) PlotCharts(X, "All 200 Years") # + id="2hgY8eKhYx7g" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}, "output_extras": [{"item_id": 1}, {"item_id": 2}], "base_uri": "https://localhost:8080/", "height": 815} outputId="392dd8e7-3889-4246-d8c8-8de7ef4c0488" executionInfo={"status": "ok", "timestamp": 1519035666265, "user_tz": -60, "elapsed": 741, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-xMs-waRqjDU/AAAAAAAAAAI/AAAAAAAANcw/nIsP9G7H0rg/s50-c-k-no/photo.jpg", "userId": "113812738982213408956"}} X = np.linspace(TOTAL_MINUTES - TOTAL_MINUTES/200*150, TOTAL_MINUTES, 400) PlotCharts(X, "Last 150 Years", use_millions=False) # + id="eVSEqpDCYyhx" colab_type="code" colab={"autoexec": {"startup": false, "wait_interval": 0}}
src/xrd/tools/EmissionModel.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # In the README of this package I demonstrated how to use the multisnpnet-Cox-tv package to fit a Cox model with user-provided regularization parameters and with the time-varying covariates provided in the form of an operation time. Here I will show how to use this package to fit a Cox-Lasso path using BASIL to screen the SNPs. # + library(coxtv) library(pgenlibr) library(data.table) library(tidyverse) phe.file = "@@@/phenotypedata/master_phe/cox/phenotypefiles/f.131298.0.0.phe" death.file = "@@@/ukbb-phenotyping/20200404_icd_death/ukb41413_icd_death.tsv" masterphe.file = "@@@/phenotypedata/master_phe/master.phe" genotype.pfile = "@@@/array_combined/pgen/ukb24983_cal_hla_cnv" psamid = data.table::fread(paste0(genotype.pfile, '.psam'),colClasses = list(character=c("IID")), select = c("IID")) psamid = psamid$IID covs = c("sex", "age", "PC1", "PC2", "PC3", "PC4", "PC5", "PC6", "PC7", "PC8", "PC9", "PC10") train_ratio = 0.8 configs = list() configs[['gcount.full.prefix']] = '@@/ruilinli/tvtest/gcount/test' configs[['plink2.path']] = "@@/ruilinli/prox_grad_cox_block/plink2" configs[['nCores']] = 6 configs[['mem']] = 60000 configs[['vzs']] = TRUE configs[['save']] =TRUE configs[['zstdcat.path']] = "zstdcat" configs[['save.computeProduct']] = TRUE configs[['results.dir']] = "@@/ruilinli/tvtest/result/" configs[['save.dir']] = "@@/ruilinli/tvtest/save" configs[['KKT.verbose']] = TRUE configs[['endian']]="little" configs[["standardize.variant"]] = FALSE configs[['missing.rate']] = 0.1 configs[['MAF.thresh']] = 0.001 # + # Some preprocessing phe = data.table::fread(phe.file, colClasses = list(character=c("FID"), numeric=c("coxnet_y_f.131298.0.0", "coxnet_status_f.131298.0.0")), select = c("FID", "coxnet_y_f.131298.0.0", "coxnet_status_f.131298.0.0")) names(phe) = c("ID", "t0", "MI") phe = filter(phe, ID %in% psamid) event = data.table::fread(death.file, colClasses = list(character=c("#IID"), numeric=c("val")), select = c("#IID", "val")) names(event) = c("ID", "val") masterphe = data.table::fread(masterphe.file, colClasses = list(character=c("FID"), numeric=covs), select = c("FID", covs)) names(masterphe) = c("ID", covs) # + phe = filter(phe, MI == 1) # people with MI phe = select(phe, -MI) # Don't need the MI indicator anymore, since every in the dataset had MI phe$status = 0 eID = which(phe$ID %in% event$ID) # people with MI that also had event = death phe$status[eID] = 1 phe$t1 = NA # The event time phe$t1[eID] = event$val[match(phe$ID[eID], event$ID)] phe$t1[-eID] = masterphe$age[match(phe$ID[-eID], masterphe$ID)] + 1.1219 # last followup time for people who did not have the event # - # add covariates to the phe file covs = covs[covs!="age"] for (cov in covs){ phe[,cov] <- masterphe[match(phe$ID, masterphe$ID), ..cov] } phe$y = phe$t1 - phe$t0 phe = filter(phe, t1 > 0) phe = phe[complete.cases(phe),] min_event_time = min(phe$y[as.logical(phe$status)]) phe = filter(phe, y>= max(0, min_event_time)) # non-events before the first event will never be used # + # Now we get the time-varying covariates into the format we need tv_files = c("@@@/primary_care/gp_clinical/example_phenotypes/final/LDL.tsv", "@@@/primary_care/gp_clinical/example_phenotypes/final/Weight.tsv") tv_list = list() i = 1 for(tvfile in tv_files){ tv = data.table::fread(tvfile, colClasses = list(character=c("id"), numeric=c("age", "value")), select = c("id", "age", "value")) names(tv) = c("ID", "time", "value") tv = filter(tv, !is.na(value)) bounds = quantile(tv$value, c(0.002, 0.999)) # remove extreme observations print(bounds) tv = filter(tv, (value > bounds[1]) & (value < bounds[2])) # take the intersection phe = filter(phe, ID %in% tv$ID) tv = filter(tv, ID %in% phe$ID) tv$time = tv$time - phe$t0[match(tv$ID, phe$ID)] tv_list[[i]] = tv i = i + 1 } # + # We split the data into training and validation set, the original split column may not be appropriate here # since we are using a small subset of founders (because only a small number of people had MI) total_events = sum(phe$status) non_events = nrow(phe) - total_events train_id = sample(phe$ID[as.logical(phe$status)], round(total_events*train_ratio)) train_id = c(train_id, sample(phe$ID[!as.logical(phe$status)], round(non_events*train_ratio))) val_id = filter(phe, ! ID %in% train_id)$ID phe$split = 'train' phe$split[phe$ID %in% val_id] = 'val' phe_val = as.data.table(filter(phe, split=='val')) phe_train = as.data.table(filter(phe, split=='train')) tv_train = list() tv_val = list() for(i in (1:length(tv_list))){ tv_train[[i]] = filter(tv_list[[i]], ID %in% phe_train$ID) tv_val[[i]] = filter(tv_list[[i]], ID %in% phe_val$ID) } info_train = coxtv::get_info(phe_train, tv_train) info_val = coxtv::get_info(phe_val, tv_val) rm(tv_list) rm(phe) # - # Now we have the data in the right format to be fed to the coxtv functions. To summarize, we need # - A dataframe (here phe_train and phe_val) that has columns: # - y that contains the time-to-event response # - status, a binary vector that represents whether event has occured # - ID, which will be used to identify each person in this dataframe # - some covariates columns that are time independent # - A list that contains the time-varying covariates (here tv_train and tv_val). Each element of the list corresponds to one time-varying covariate and must have the columns: # - ID, same set of IDs as used in the phe data frame # - time, the time at which the measurement was taken (relative to each person's t0) # - value, the value of the measurements at the corresponding time # - A set of time-independent covariates names that will be used to fit a Cox model, these names must be available in the phe dataframet # - (Optional, to save some compute) A list info that is obtained using coxtv::get_info(phe, tv_list). This list contains information about the time-varying covariates in the form that coxtv can readily use to fit a model. Keep info can save some computation, especially when n or the number of events is large. For now the user needs to make sure that when fitting a Cox model, info must correspond to phe and tv_list. Otherwise a segmentation fault might happen. In future version I might encapsulate BASIL into a package to solve this problem. # # ##### It is important that the users make sure that each person must have at least one measurement before the first event time, for each of the time-varying covariate! If this is not satisfied, a warning will be thrown and the most recent measurement after the event will be used. # # ##### Now let's fit the first iteration, which is supposed to be unpenalized: covs = c("t0", covs) result = coxtv(phe_train, NULL, covs, c(0.0), info=info_train) #lambda is the last argument, if info is provided then the second parameter is not needed as.matrix(result[[1]]) # Now let's fit a Lasso path using BASIL to screen the SNPs. First we compute the residual: # + source("@@@/ruilinli/prox_grad_cox_block/snpnet/R/functions.R") # Need to use some snpnet helper functions residuals = cox_residual(phe_train, covs, info_train, result[[1]]) # 1/n already multiplied in this residual # to compute the gradient (with respect to the SNP coefficients) let's first load the genotype files # code copied from snpnet vars <- dplyr::mutate(dplyr::rename(data.table::fread(cmd=paste0(configs[['zstdcat.path']], ' ', paste0(genotype.pfile, '.pvar.zst'))), 'CHROM'='#CHROM'), VAR_ID=paste(ID, ALT, sep='_'))$VAR_ID pvar <- pgenlibr::NewPvar(paste0(genotype.pfile, '.pvar.zst')) pgen_train = pgenlibr::NewPgen(paste0(genotype.pfile, '.pgen'), pvar=pvar, sample_subset=match(phe_train$ID, psamid)) pgen_val = pgenlibr::NewPgen(paste0(genotype.pfile, '.pgen'), pvar=pvar, sample_subset=match(phe_val$ID, psamid)) pgenlibr::ClosePvar(pvar) stats <- computeStats(genotype.pfile, paste(phe_train$ID, phe_train$ID, sep="_"), configs = configs) # - residuals = matrix(residuals,nrow = length(phe_train$ID), ncol = 1, dimnames = list(paste(phe_train$ID, phe_train$ID, sep='_'), c("0"))) gradient =computeProduct(residuals, genotype.pfile, vars, stats, configs, iter=0) # + # Now we can generate a lambda sequence nlambda = 100 lambda.min.ratio = 0.01 lambda_max = max(abs(gradient), na.rm = NA) lambda_min = lambda_max * lambda.min.ratio lambda_seq = exp(seq(from = log(lambda_max), to = log(lambda_min), length.out = nlambda)) # The first lambda solution is already obtained max_valid_index = 1 prev_valid_index = 0 # Use validation C-index to determine early stop max_cindex = 0 cindex = numeric(nlambda) out = list() out[[1]] = result[[1]] features.to.discard = NULL # - score = abs(gradient[,1]) iter = 1 ever.active = covs print(ever.active) current_B = result[[1]] # + while(max_valid_index < nlambda){ if(max_valid_index > prev_valid_index){ for(i in (prev_valid_index + 1):max_valid_index){ cindex[i] = cindex_tv(phe_val, NULL, covs, out[[i]], info=info_val) } cindex_this_iter = cindex[(prev_valid_index + 1):max_valid_index] max_cindex_this_iter = max(cindex_this_iter) if(max_cindex_this_iter >= max_cindex){ max_cindex = max_cindex_this_iter } else { print("early stop reached") break } if(which.max(cindex_this_iter) != length(cindex_this_iter)){ print("early stop reached") break } } prev_valid_index = max_valid_index print(paste("current maximum valid index is:",max_valid_index )) print("Current C-Indices are:") print(cindex[1:max_valid_index]) if(length(features.to.discard) > 0){ phe_train[, (features.to.discard) := NULL] phe_val[, (features.to.discard) := NULL] covs = covs[!covs %in% features.to.discard] # the name is a bit confusing, maybe change it to ti_names? } which.in.model <- which(names(score) %in% covs) score[which.in.model] <- NA sorted.score <- sort(score, decreasing = T, na.last = NA) features.to.add <- names(sorted.score)[1:min(1000, length(sorted.score))] covs = c(covs, features.to.add) B_init = c(current_B, rep(0.0, length(features.to.add))) tmp.features.add <- prepareFeatures(pgen_train, vars, features.to.add, stats) phe_train[, colnames(tmp.features.add) := tmp.features.add] tmp.features.add <- prepareFeatures(pgen_val, vars, features.to.add, stats) phe_val[, colnames(tmp.features.add) := tmp.features.add] rm(tmp.features.add) # Not fit a regularized Cox model for the next 10 lambdas lambda_seq_local = lambda_seq[(max_valid_index + 1):min(max_valid_index + 10, length(lambda_seq))] # Need better ways to set p.fac p.fac = rep(1, length(B_init)) p.fac[1:14] = 0.0 print(paste("Number of variables to be fitted is:",length(B_init))) result = coxtv(phe_train, NULL, covs, lambda_seq_local, B0 = B_init, p.fac = p.fac, info=info_train) residuals = matrix(nrow = length(phe_train$ID), ncol = length(lambda_seq_local), dimnames = list(paste(phe_train$ID, phe_train$ID, sep='_'), signif(lambda_seq_local, 3))) for(i in 1:length(result)){ residuals[,i] = cox_residual(phe_train, covs, info_train, result[[i]]) } new_score = abs(computeProduct(residuals, genotype.pfile, vars, stats, configs, iter=iter)) max_score = apply(new_score, 2, function(x){max(x[!names(x) %in% covs], na.rm=NA)}) print(max_score) # if all failed if(all(max_score > lambda_seq_local)){ features.to.discard = NULL current_B = result[[1]] score = new_score[, 1] } else { local_valid = which.min(c(max_score <= lambda_seq_local, FALSE)) - 1 # number of valid this iteration for(j in 1:local_valid){ out[[max_valid_index+j]] = result[[j]] } max_valid_index = max_valid_index + local_valid ever.active <- union(ever.active, names(which(apply(sapply(result[1:local_valid, drop=F], function(x){x!=0}), 1, any)))) features.to.discard = setdiff(covs, ever.active) score = new_score[, local_valid] current_B = result[[local_valid]] current_B = current_B[!names(current_B) %in% features.to.discard] print(paste("Number of features discarded in this iteration is", length(features.to.discard))) } iter = iter + 1 }
Basil_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # ### Master Telefónica Big Data & Analytics # # **Prueba de Evaluación del Tema 4:** # ## **Topic Modelling.** # Date: 2016/04/10 # Para realizar esta prueba es necesario tener actualizada la máquina virtual con la versión más reciente de MLlib. # # Para la actualización, debe seguir los pasos que se indican a continuación: # ### Pasos para actualizar MLlib: # # 1. Entrar en la vm como root: # # `vagrant ssh` # # `sudo bash` # # Ir a `/usr/local/bin` # # 2. Descargar la última versión de spark desde la vm mediante # # `wget http://www-eu.apache.org/dist/spark/spark-1.6.1/spark-1.6.1-bin-hadoop2.6.tgz` # # 3. Desempaquetar: # # `tar xvf spark-1.6.1-bin-hadoop2.6.tgz` (y borrar el tgz) # # 4. Lo siguiente es un parche, pero suficiente para que funcione: # # Guardar copia de `spark-1.3: mv spark-1.3.1-bin-hadoop2.6/ spark-1.3.1-bin-hadoop2.6_old` # # Crear enlace a `spark-1.6: ln -s spark-1.6.1-bin-hadoop2.6/ spark-1.3.1-bin-hadoop2.6` # # ## Librerías # # Puede utilizar este espacio para importar todas las librerías que necesite para realizar el examen. # + # %matplotlib inline import nltk import time import matplotlib.pyplot as plt import pylab # import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords #from test_helper import Test import collections from pyspark.mllib.clustering import LDA, LDAModel from pyspark.mllib.linalg import Vectors # import gensim # import numpy as np # - # ## 0. Adquisición de un corpus. # # Descargue el contenido del corpus `reuters` de `nltk`. # # import nltk # nltk.download() # # Selecciona el identificador `reuters`. #nltk.download() mycorpus = nltk.corpus.reuters # Para evitar problemas de sobrecarga de memoria, o de tiempo de procesado, puede reducir el tamaño el corpus, modificando el valor de la variable n_docs a continuación. # + n_docs = 500000 filenames = mycorpus.fileids() fn_train = [f for f in filenames if f[0:5]=='train'] corpus_text = [mycorpus.raw(f) for f in fn_train] # Reduced dataset: n_docs = min(n_docs, len(corpus_text)) corpus_text = [corpus_text[n] for n in range(n_docs)] print 'Loaded {0} files'.format(len(corpus_text)) # - # A continuación cargaremos los datos en un RDD corpusRDD = sc.parallelize(corpus_text, 4) print "\nRDD created with {0} elements".format(corpusRDD.count()) # ## 1. Ejercicios # #### **Ejercicio 1**: Preprocesamiento de datos. # # Prepare los datos para aplicar un algoritmo de modelado de tópicos en `pyspark`. Para ello, aplique los pasos siguientes: # # 1. *Tokenización*: convierta cada texto a utf-8, y transforme la cadena en una lista de tokens. # 2. Homogeneización: pase todas las palabras a minúsculas y elimine todos los tokens no alfanuméricos. # 3. Limpieza: Elimine todas las stopwords utilizando el fichero de stopwords disponible en NLTK para el idioma inglés. # # Guarde el resultado en la variable `corpus_tokensRDD` # + def getTokenList(doc, stopwords_en): # scode: tokens = <FILL IN> # Tokenize docs tokens = word_tokenize(doc.decode('utf-8')) # scode: tokens = <FILL IN> # Remove non-alphanumeric tokens and normalize to lowercase tokens = [t.lower() for t in tokens if t.isalnum()] # scode: tokens = <FILL IN> # Remove stopwords tokens = [t for t in tokens if t not in stopwords_en] return tokens stopwords_en = stopwords.words('english') corpus_tokensRDD = (corpusRDD .map(lambda x: getTokenList(x, stopwords_en)) .cache()) # print "\n Let's check tokens after cleaning:" print corpus_tokensRDD.take(1)[0][0:30] # - # #### **Ejercicio 2**: Stemming # # Aplique un procedimiento de *stemming* al corpus, utilizando el `SnowballStemmer` de NLTK. Guarde el resultado en `corpus_stemRDD`. # + # Select stemmer. stemmer = nltk.stem.SnowballStemmer('english') # scode: corpus_stemRDD = <FILL IN> corpus_stemRDD = corpus_tokensRDD.map(lambda x: [stemmer.stem(token) for token in x]) print "\nLet's check the first tokens from document 0 after stemming:" print corpus_stemRDD.take(1)[0][0:30] # - # #### **Ejercicio 3**: Vectorización # # En este punto cada documento del corpus es una lista de tokens. # # Calcule un nuevo RDD que contenga, para cada documento, una lista de tuplas. La clave (*key*) de cada lista será un token y su valor el número de repeticiones del mismo en el documento. # # Imprima una muestra de 20 tuplas uno de los documentos del corpus. # + # corpus_wcRDD = <FILL IN> corpus_wcRDD = (corpus_stemRDD .map(collections.Counter) .map(lambda x: [(t, x[t]) for t in x])) print corpus_wcRDD.take(1)[0][0:20] # - # #### **Ejercicio 4**: Cálculo del diccionario de tokens # # Construya, a partir de `corpus_wcRDD`, un nuevo diccionario con todos los tokens del corpus. El resultado será un diccionario python de nombre `wcDict`, cuyas entradas serán los tokens y sus valores el número de repeticiones del token en todo el corpus. # # `wcDict = {token1: valor1, token2, valor2, ...}` # # Imprima el número de repeticiones del token `interpret` # + # scode: wcRDD = < FILL IN > wcRDD = (corpus_wcRDD .flatMap(lambda x: x) .reduceByKey(lambda x, y: x + y)) wcDict = dict(wcRDD.collect()) print wcDict['interpret'] # - # #### **Ejercicio 5**: Número de tokens. # # Determine el número total de tokens en el diccionario. Imprima el resultado. print wcRDD.count() # #### **Ejercicio 6**: Términos demasiado frecuentes: # # Determine los 5 tokens más frecuentes del corpus. Imprima el resultado. print wcRDD.takeOrdered(5, lambda x: -x[1]) # #### **Ejercicio 7**: Número de documentos del token más frecuente. # # Determine en qué porcentaje de documentos aparece el token más frecuente. # # + tokenmasf = 'said' ndocs = corpus_stemRDD.filter(lambda x: tokenmasf in x).count() print 'El numerod de documentos es {0}, es decir, el {1} % del total de documentos'.format( ndocs, float(ndocs)/corpus_stemRDD.count()*100) # - # #### **Ejercicio 8**: Filtrado de términos. # # Elimine del corpus los dós términos más frecuentes. Guarde el resultado en un nuevo RDD denominado corpus_wcRDD2, con la misma estructura que corpus_wcRDD (es decir, cada documento una lista de tuplas). # + corpus_wcRDD2 = corpus_wcRDD.map(lambda x: [tupla for tupla in x if tupla[0] not in ['said', 'mln']]) print corpus_wcRDD2.take(1) # - # #### **Ejercicio 9**: Lista de tokens y diccionario inverso. # # Determine la lista de topicos de todo el corpus, y construya un dictionario inverso, cuyas entradas sean los números consecutivos de 0 al número total de tokens, y sus salidas cada uno de los tokens, es decir # # invD = {0: token0, 1: token1, 2: token2, ...} # + # scode: wcRDD = < FILL IN > wcRDD2 = (corpus_wcRDD2 .flatMap(lambda x: x) .reduceByKey(lambda x, y: x + y) .sortBy(lambda x: -x[1])) # Token Dictionary: n_tokens = wcRDD2.count() TD = wcRDD2.takeOrdered(n_tokens, lambda x: -x[1]) D = map(lambda x: x[0], TD) token_count = map(lambda x: x[1], TD) # Compute inverse dictionary invD = dict(zip(D, xrange(n_tokens))) print invD # - # #### **Ejercicio 10**: Algoritmo LDA. # # Para aplicar el algoritmo LDA, es necesario reemplazar las tuplas `(token, valor)` de `wcRDD` por tuplas del tipo `(token_id, value)`, sustituyendo cada token por un identificador entero. # # El código siguiente se encarga de completar este proceso: # + # Compute RDD replacing tokens by token_ids corpus_sparseRDD = corpus_wcRDD2.map(lambda x: [(invD[t[0]], t[1]) for t in x]) # Convert list of tuplas into Vectors.sparse object. corpus_sparseRDD = corpus_sparseRDD.map(lambda x: Vectors.sparse(n_tokens, x)) corpus4lda = corpus_sparseRDD.zipWithIndex().map(lambda x: [x[1], x[0]]).cache() print corpus4lda.take(1) # - # Aplique el algoritmo LDA con 4 tópicos sobre el corpus obtenido en `corpus4lda`, para un valor de `topicConcentration = 2.0` y `docConcentration = 3.0`. (Tenga en cuenta que estos parámetros de entrada deben de ser tipo float). print "Training LDA: this might take a while..." start = time.time() n_topics = 4 ldaModel = LDA.train(corpus4lda, k=n_topics, topicConcentration=2.0, docConcentration=3.0) print "Modelo LDA entrenado en: {0} segundos".format(time.time()-start) # #### **Ejercicio 11**: Tokens principales. # # Imprima los dos tokens de mayor peso de cada tópico. (Debe imprimir el texto del token, no su índice). n_topics = 4 ldatopics = ldaModel.describeTopics(maxTermsPerTopic=2) ldatopicnames = map(lambda x: x[0], ldatopics) print ldatopicnames for i in range(n_topics): print "Topic {0}: {1}, {2}".format(i, D[ldatopicnames[i][0]], D[ldatopicnames[i][1]]) print ldatopics # #### **Ejercicio 12**: Pesos de un token. # # Imprima el peso del token `bank` en cada tópico. # Output topics. Each is a distribution over words (matching word count vectors) iBank = invD['bank'] topicMatrix = ldaModel.topicsMatrix() print topicMatrix[iBank] # #### **Test 13**: Indique cuáles de las siguientes afirmaciones se puede asegurar que son verdaderas: # # 1. En LSI, cada documento se asigna a un sólo tópico. # 2. De acuerdo con el modelo LDA, todos los tokens de un documento han sido generados por el mismo tópico # 3. LSI descompone la matriz de datos de entrada en el producto de 3 matrices cuadradas. # 4. Si el rango de la matriz de entrada a un modelo LSI es igual al número de tópicos. La descomposición SVD del modelo LSI es exacta (no es una aproximación). # # FFFV # #### **Test 14**: Indique cuáles de las siguientes afirmaciones se puede asegurar que son verdaderas: # # 1. En un modelo LDA, la distribución de Dirichlet se utiliza para generar distribuciones de probabilidad de tokens. # 2. Si una palabra aparece en pocos documentos del corpus, su IDF es mayor. # 3. El resultado de la lematización de una palabra es una palabra # 4. El resultado del stemming de una palabra es una palabra # VVVF
TM3.Topic_Models_with_MLlib/ExB3_TopicModels/TM_Exam_Solution.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/Leyliiii/Elective-1-3/blob/main/Operations_and_Expressions_in_Python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="fm2gTwIr0Dnq" # ##Boolean Operators # + colab={"base_uri": "https://localhost:8080/"} id="ItsKQukT0JR5" outputId="886f62a6-1451-45df-debc-1162ef7abcf0" x = 10 y = 9 #Returns boolean value of either True or False print(x>y) print(x==y) # + colab={"base_uri": "https://localhost:8080/"} id="c6EDnJTA1SNM" outputId="b8d670c3-b483-47bc-a8ff-45ceb8fb3b67" #bool() function allows to evaluate any value, and return True or False #Almost any value is returned as True if it has some sort of context print(bool("<NAME>")) print(bool(25)) #None,empty, 0, and [] returns as False print(bool(None)) print(bool()) print(bool(0)) print(bool([])) # + [markdown] id="z6njSeXO2UTa" # ##Defining Function # + colab={"base_uri": "https://localhost:8080/"} id="n_2F7Lvw2Oy3" outputId="4e59be13-f510-42c9-b68b-dcdd4d970717" #Functions can return a boolean: "def myFunction():" def myFunction(): return True print(myFunction()) # + colab={"base_uri": "https://localhost:8080/"} id="ua_ESub522D5" outputId="17d88a44-cf59-4fec-9836-17d67b0f8fd4" def myFunction(): return False if myFunction(): #Will return the value based on the declaration of myFunction print("YES!") else: print("NO!") # + [markdown] id="88xB9O253UvQ" # ## Application 1 # + colab={"base_uri": "https://localhost:8080/"} id="vcl_pFar3WVX" outputId="c8399c7b-8943-49b8-dd82-2c066bc73517" print(10>9) a=6 b=7 print(a==b) print(a!=a) # + [markdown] id="YjuM2tO04tm4" # ##Arithmetic Operations # # + colab={"base_uri": "https://localhost:8080/"} id="boGKXlLD4yvX" outputId="ef46888a-800a-4d47-b56a-873bd9536b78" #Python Operators are used to perform operations on variables and values #// - floor division ; ** - power #recent values from PREVIOUS cell can be used print(a+b) print(a-b) print(a*b) print(a**b) # + [markdown] id="xeP10ZbS5j-w" # ##Bitwise Operators # + colab={"base_uri": "https://localhost:8080/"} id="6CCtKKWV5mBv" outputId="d3f84d41-830d-4589-f666-c9767d06d661" #Python Bitwise Operators works on bit-by-bit operations c=60 d=13 print(c & d) print(c | d) print(c ^ d) print(c << 1) #Shifts the binary sequence to the left print(c << 2) print(c >> 1) #Shifts the binary sequence to the right # + [markdown] id="TyKusfF-746_" # ##Assignment *Operators* # + colab={"base_uri": "https://localhost:8080/"} id="6uCtAhka77yW" outputId="b962b25c-7096-4176-d2d7-5e1e7ac5bea3" # c+=3 is the same as c = c+3 c+=3 c%=3 print(c) # + [markdown] id="jkfLyGod8y1Y" # ##Logical Operators # + colab={"base_uri": "https://localhost:8080/"} id="PiErSYCn80TN" outputId="da3443a7-437e-4cec-9c81-8004dbc00403" c = True d = True print(c and d) not(c and d) # + [markdown] id="WkRfQC1v9TX2" # ##Identity # + colab={"base_uri": "https://localhost:8080/"} id="6r06h_f19Ui1" outputId="6e955f07-6c8c-4780-de3b-490fd12badd5" print(c is d) c is not d # + [markdown] id="tO2tENCD9gLO" # ## Application 2 # + colab={"base_uri": "https://localhost:8080/"} id="Zkv5Dx3o9h0X" outputId="3044d9be-b411-434c-ad46-3db1b7f7e55c" e = 10 f = 5 #Implement the operations + , // , and bit shift right >> print(e + f) print(e // f) print(e>>2) #1010 >> 0101 >> 0010 print(f>>2) #0101 >> 0010 >> 0001
Operations_and_Expressions_in_Python.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: python-env # language: python # name: python-env # --- from matplotlib.pyplot import show from cv2 import cv2 import itertools import numpy as np import matplotlib.pyplot as plt from PIL import Image import time from IPython.display import clear_output import sys def show_img(img, colormode='gray'): dim = img.shape colormap = 'gray' if len(dim) < 3 else None colormode = 'L' if len(dim) < 3 else 'RGB' img = Image.fromarray(np.uint8(img), colormode) plt.imshow(img, colormap) plt.axis('off') plt.show() def open_img(path): img_bgr2 = cv2.imread(path) img_rgb = cv2.cvtColor(img_bgr2, cv2.COLOR_BGR2RGB) return img_rgb def kmean_segmentation(img, k): # SEGMENTACION criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2) pixel_values = reduced.reshape((-1, 3)) pixel_values = np.float32(pixel_values) _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # RECONSTRUCCION CON SEGMENTACION centers = np.uint8(centers) centers_og = centers.copy() sorted_idx = np.argsort(centers.sum(axis = 1)) for i in range(len(centers)): if i < (k // 2): if i == 0: centers[sorted_idx[i]] = [255, 255, 255] else: centers[sorted_idx[i]] = [0, 0, 255] # centers[sorted_idx[0]] = [255, 255, 255] # centers[sorted_idx[1]] = [0, 0, 255] # centers[sorted_idx[2]] = [0, 0, 255] labels = labels.flatten() segmented_image = centers[labels.flatten()] # reshape back to the original image dimension segmented_image = segmented_image.reshape(reduced.shape) # show_img(segmented_image, 'L') return segmented_image, centers, centers_og # + # ABRIR IMAGEN path = 'orange_blasco.png' k = 10 img = open_img(path) # SUAVIZADO dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 5, 12, 12) # Reduccion de colores div = 32 reduced = dst // div * div + div // 2 seg3, centers, centers_og = kmean_segmentation(reduced, 3) seg5, centers, centers_og = kmean_segmentation(reduced, 5) seg10, centers, centers_og = kmean_segmentation(reduced, 10) # mostrar procesamiento fig = plt.figure(constrained_layout=True, figsize = (15,6)) fig.suptitle('PROCESO DE SEGMENTACIÓN (Blasco 2006)\nLas secciones azules representan los defectos detectados', color = 'blue') gs = fig.add_gridspec(10, (6 * 3) + 1) # Original f1 = fig.add_subplot(gs[:, 0:3]) f1.imshow(img) f1.set_title("Original") f1.axis('off') # Suavizado f2 = fig.add_subplot(gs[:,3:6]) f2.imshow(dst) f2.set_title('Suavizado') f2.axis('off') # Reduced f11 = fig.add_subplot(gs[:, 6:9]) f11.imshow(reduced) f11.set_title('32 colores') f11.axis('off') grid_semillas = [] for i in range(len(centers_og)): grid_semillas.append(fig.add_subplot(gs[i, 9])) grid_semillas[i].imshow([[centers_og[i]]]) grid_semillas[i].set_title('Colores semillas') if i == 0 else None grid_semillas[i].axis('off') f3 = fig.add_subplot(gs[:, 10:13]) f3.imshow(seg3) f3.set_title(f'k={3}') f3.axis('off') f4 = fig.add_subplot(gs[:, 13:16]) f4.imshow(seg5) f4.set_title(f'k={5}') f4.axis('off') f5 = fig.add_subplot(gs[:, 16:19]) f5.imshow(seg10) f5.set_title(f'k={10}') f5.axis('off') # -
PIA/segmentacion_blasco.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/sriksmachi/aimriscan/blob/main/style_transfer_using_cyclegan_brainmri.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="eVD7RHDJvEzm" outputId="1da2f451-a0db-4e8f-ae08-4d9adb061894" from google.colab import drive drive.mount('/content/drive') # + [markdown] id="w7tqD8Bmdij9" # # Style Transfer using GANs # + [markdown] id="48HA1P9ddoDO" # ## Problem Statement # + [markdown] id="xEuNFcVfg1Kr" # # MRI(Magnetic Resonance Imaging) brain has a number of uses in medical diagnostic. Due to its accuracy, cost advantage and availability, it has become very common and popular. Purpose of MRI brain can be very different and depends on problem or patient’s complaint. # The help in detecting a varitey of problems like Stroke (like clots, hemorrhagic), Structural defects (like birth defects), tumors related to cancer etc. # # ### MRI Machines # # MRI machines were invented in 1977. Before inventing MRI surgery was the only way to treat the pateients with above mentioned problems. # # MRI scanner is a long cylindrical machine which is open at both the ends. The patient is slid into this opening on the scanner bed. A radio frequency wave is used to process the hydrogen atoms alignment under the influence of magnetic field. These signals are then processed in very powerful computers to generate images of Brain. # # # Shown below is an MRI machine. # # ![image.png](https://bookmerilab.com/blog/wp-content/uploads/2018/02/mri-brain-scan.jpg) # # MRI scanner generates a strong magnetic field which is 60K times stronger than the magentic field of earth. # # # ### T1 and T2 Images # # MRI can be used to scan different parts of the body like chest, abdomen, Bladder etc. A brain MRI is an MRI done to the brain area. Every biological molecule has two protons, which by virtue of their positive charge act as small magnets on a subatomic scale. The MRI machine helps in creating a magnetic vector and align the protons to the axis of the magnetic field created by the machine. An additional enery in the form of radio wave is added to the magentic field which helps in studying how each tissue reacts. When the RF source is switched on/off the protons return to the previous state aligining to the magnetci field, during this process they emit radio waves which are collected by receiver coils and converted to images. The time taken for the protons to fully relax is measured in two ways. The first is the time taken for the magnetic vector to return to its resting state and the second is the time needed for the axial spin to return to its resting state. The first is called T1 relaxation, the second is called T2 relaxation. # # The below image shows a sample T1 and T2 Brain MRI Image. # #### T1 Image # ![image.png](https://my-ms.org/images/mri_scan0_16.jpg) # # #### T2 Image # ![image.png](https://my-ms.org/images/mri_scan6_12.jpg) # # # The below table shows differences highlight by the MRI image based on the type of the image. # # |Type |T1 Highlight Style |T2 Highlight Style| # |--|--|--| # |Water |Dark |Very Bright # |Fat |Very |Bright Dark # |Bone |Dark |Dark # |Muscle |Intermediate |Dark # |Tumours |Intermediate |Bright # |Air | Dark | Dark # # # ## What are we solving? # # One of the complicated tasks in medical imaging is to diagnose MRI. Sometimes to interpret the scan, the radiologist needs different variations of the imaging which can drastically enhance the accuracy of diagnosis by providing practitioners with a more comprehensive understanding. # But to have access to different imaging is difficult and expensive (the cost of brain MRI in India varies from 5000-20K) dependening on various factors like type of machine quality, type of study, locality, region etc. ). # # The intent of this project is to reduce the cost of different imaging in Brain MRI scans by building a model which can convert T1 type MRI images into T2 type MRI images. This way we can create a revolutionary impact in the healthcare sector. # # To solve this we will be using Cycle GANs which allows to convert images from one domain to another conditionally. # # + id="g1iQFQqlFznc" # This is the location of the training data, this might change dependeing on where the data is stored. data = "/content/drive/MyDrive/ml_projects/style-transfer-using-gans/data" # + id="cYIQJ6fJGj-t" import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from keras.utils.vis_utils import plot_model import imageio import glob import os import pathlib from skimage import io from skimage.transform import resize import tqdm import keras.backend as K from IPython.display import clear_output # + [markdown] id="cwoHN5S7odnl" # ## Data Preparation # + id="<KEY>" t1_images_path = data + "/Tr1/TrainT1/*.png" t2_images_path = data + "/Tr2/TrainT2/*.png" # + colab={"base_uri": "https://localhost:8080/", "height": 314} id="OzrpZRljKNNc" outputId="1f9463f5-3553-4fc4-cf05-35186934ea3c" # Lets print a t1 image t1_image_paths = glob.glob(t1_images_path) io.imshow(str(t1_image_paths[0])) print("T1 image") # + colab={"base_uri": "https://localhost:8080/", "height": 314} id="j0jllS_cKQ3r" outputId="ab927951-0e57-45a9-9f55-7017cb18c44b" # Lets print a t2 image t2_image_paths =glob.glob(t2_images_path) io.imshow(str(t2_image_paths[0])) print("T2 image") # + colab={"base_uri": "https://localhost:8080/"} id="dGEjrYfpHoOb" outputId="64dac8ae-0512-4f24-9af1-ef59743b68bf" # reading all images from PIL import Image t1_images= np.array([np.array(Image.open(fname)) for fname in tqdm.tqdm(t1_image_paths)]) t2_images = np.array([np.array(Image.open(fname)) for fname in tqdm.tqdm(t2_image_paths)]) # + colab={"base_uri": "https://localhost:8080/"} id="PbhzEq6nIiD_" outputId="22c4a89b-dc71-4a2b-dd2d-3897223e8cc6" # Normalizing images to [-1,1] to aid in computation. t1_images = (t1_images/127.5)-1.0 print(t1_images.shape) t2_images = (t2_images/127.5)-1.0 print(t2_images.shape) # + colab={"base_uri": "https://localhost:8080/"} id="myeZB8KtWFxC" outputId="fe9cfb40-d8b3-46da-b0ba-537d630fd516" # training parameters # as explained in the cycle gan paper https://arxiv.org/pdf/1703.10593.pdf batch_size of 1 produced good results BATCH_SIZE = 4 # since the images are related to medical domain, higher image size is choosen for clarity. img_size = 512 #resizing the images t1_data = np.zeros((t1_images.shape[0], img_size, img_size)) for index, img in enumerate(t1_images): t1_data[index, :, :] = resize(img, (img_size, img_size)) print(t1_data.shape) t2_data = np.zeros((t2_images.shape[0], img_size, img_size)) for index, img in enumerate(t2_images): t2_data[index, :, :] = resize(img, (img_size, img_size)) print(t2_data.shape) t1_data = t1_data.reshape(t1_data.shape[0], img_size, img_size, 1).astype('float32') t2_data = t2_data.reshape(t2_data.shape[0], img_size, img_size, 1).astype('float32') t1_data = tf.data.Dataset.from_tensor_slices(t1_data).shuffle(t1_images.shape[0], seed=42).batch(BATCH_SIZE) t2_data = tf.data.Dataset.from_tensor_slices(t2_data).shuffle(t2_images.shape[0], seed=42).batch(BATCH_SIZE) # + colab={"base_uri": "https://localhost:8080/", "height": 263} id="S7Ck73iXXcu7" outputId="1c546570-c615-42f6-ad8c-f8666445ea5b" def print_sample(dataset): sample_data = next(iter(dataset)) plt.figure(figsize=(2, 2)) plt.imshow(sample_data[0].numpy()[:, :, 0], cmap='gray') plt.axis('off') plt.show() print_sample(t1_data) print_sample(t2_data) # + [markdown] id="RC78ObMvolaQ" # ## Re-usable functions. # + id="8WwijNJ6Xvba" class InstanceNormalization(tf.keras.layers.Layer): # Initialization of Objects def __init__(self, epsilon=1e-5): # calling parent's init super(InstanceNormalization, self).__init__() self.epsilon = epsilon def build(self, input_shape): self.scale = self.add_weight( name='scale', shape=input_shape[-1:], initializer=tf.random_normal_initializer(1., 0.02), trainable=True) self.offset = self.add_weight( name='offset', shape=input_shape[-1:], initializer='zeros', trainable=True) def call(self, x): # Compute Mean and Variance, Axes=[1,2] ensures Instance Normalization mean, variance = tf.nn.moments(x, axes=[1, 2], keepdims=True) inv = tf.math.rsqrt(variance + self.epsilon) normalized = (x - mean) * inv return self.scale * normalized + self.offset # + id="zBSj7XRDX6Za" def downsample(filters, size, apply_norm=True): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() # Add Conv2d layer result.add(tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) # Add Normalization layer if apply_norm: result.add(InstanceNormalization()) # Add Leaky Relu Activation result.add(tf.keras.layers.LeakyReLU()) return result # + id="HBK4_-VUX78N" def upsample(filters, size, apply_dropout=False): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() # Add Transposed Conv2d layer result.add(tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) # Add Normalization Layer result.add(InstanceNormalization()) # Conditionally add Dropout layer if apply_dropout: result.add(tf.keras.layers.Dropout(0.5)) # Add Relu Activation Layer result.add(tf.keras.layers.ReLU()) return result # + id="HhdNZ9vXX9Ti" # Unet Generator is a combination of Convolution + Transposed Convolution Layers def unet_generator(): down_stack = [ downsample(64, 4, False), # (bs, 256, 256, 64) downsample(128, 4), # (bs, 128, 128, 128) downsample(128, 4), # (bs, 64, 8, 128) downsample(128, 4), # (bs, 32, 32, 128) downsample(128, 4), # (bs, 16, 16, 128) downsample(128, 4), # (bs, 8, 8, 128) downsample(128, 4), # (bs, 4, 4, 128) downsample(128, 4), # (bs, 2, 2, 128) downsample(128, 4) # (bs, 1, 1, 128) ] up_stack = [ upsample(128, 4, True), # (bs, 4, 2, 256) upsample(128, 4, True), # (bs, 8, 2, 256) upsample(128, 4, True), # (bs, 16, 2, 256) upsample(128, 4, True), # (bs, 32, 2, 256) upsample(128, 4, True), # (bs, 64, 2, 256) upsample(128, 4, True), # (bs, 128, 2, 256) upsample(128, 4, True), # (bs, 256, 4, 256) upsample(128, 4), # (bs, 8, 8, 256) upsample(64, 4) # (bs, 16, 16, 128) ] initializer = tf.random_normal_initializer(0., 0.02) last = tf.keras.layers.Conv2DTranspose(1, 4, strides=2, padding='same', kernel_initializer=initializer, activation='tanh') # (bs, 32, 32, 1) concat = tf.keras.layers.Concatenate() inputs = tf.keras.layers.Input(shape=[img_size, img_size, 1]) x = inputs # Downsampling through the model skips = [] for down in down_stack: x = down(x) skips.append(x) skips = reversed(skips[:-1]) # Upsampling and establishing the skip connections for up, skip in zip(up_stack, skips): x = up(x) x = concat([x, skip]) x = last(x) return tf.keras.Model(inputs=inputs, outputs=x) # + [markdown] id="ULHcsiu8otZU" # ## Genertor G & F # # * G converts T1 -> T2 # * F converts T2 -> T1 # # # # + id="NXLWBxe5YB2y" generator_g = unet_generator() generator_f = unet_generator() # + colab={"base_uri": "https://localhost:8080/"} id="R_gzzmaWYEoT" outputId="8e49b71a-b138-4332-815b-b9889acf0485" generator_g.summary() # + id="JMhJhClTYGvq" # Discriminators only contain Convolutional Layers and no Transposed Convolution is not used def discriminator(): initializer = tf.random_normal_initializer(0., 0.02) # image size is defined above. inp = tf.keras.layers.Input(shape=[img_size, img_size, 1], name='input_image') x = inp # add downsampling step here down1 = downsample(64, 4, False)(x) down2 = downsample(128, 4)(down1) down3 = downsample(128, 4)(down2) down4 = downsample(128, 4)(down3) down5 = downsample(128, 4)(down4) down6 = downsample(128, 4)(down5) # add a padding layer here zero_pad1 = tf.keras.layers.ZeroPadding2D()(down6) # implement a concrete downsampling layer here conv = tf.keras.layers.Conv2D(256, 4, strides=1, kernel_initializer=initializer, use_bias=False)(zero_pad1) norm1 = InstanceNormalization()(conv) leaky_relu = tf.keras.layers.LeakyReLU()(norm1) # apply zero padding layer zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) # (bs, 9, 9, 256) # add a last pure 2D Convolution layer last = tf.keras.layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(zero_pad2) # (bs, 6, 6, 1) return tf.keras.Model(inputs=inp, outputs=last) # + [markdown] id="x_4CG0vEo7eF" # ## Discrimnator X and Y # # * Discriminator X validates T1 Images # * Discriminator Y validates T2 images. # + id="8HQ6VTmlYI0J" discriminator_x = discriminator() discriminator_y = discriminator() # + id="OvhCA0aJYKLj" colab={"base_uri": "https://localhost:8080/"} outputId="855c0ba1-ad9f-4cb2-cb52-23ae87c9b23a" discriminator_x.summary() # + [markdown] id="Az62kX9WpKtp" # ## Loss Functions # + id="pPkzCcm5Yrnb" loss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True) # + id="fHXKagZNY2GS" def discriminator_loss(real, generated): real_loss = loss_obj(tf.ones_like(real), real) generated_loss = loss_obj(tf.zeros_like(generated), generated) total_disc_loss = real_loss + generated_loss return total_disc_loss * 0.5 # mean of losses # + id="ZSJR38SxY3mS" def generator_loss(generated): return loss_obj(tf.ones_like(generated), generated) # + id="4zBgACUpY46q" def calc_cycle_loss(real_image, cycled_image): loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image)) return 10.0 * loss1 # + id="gak1WYEZZxV5" def identity_loss(real_image, same_image): loss = tf.reduce_mean(tf.abs(real_image - same_image)) return 5 * loss # + colab={"base_uri": "https://localhost:8080/", "height": 264} id="F5n6xo-FYMMD" outputId="9694844b-f293-444e-b18c-80f381e19620" sample_t1_data = next(iter(t1_data)) sample_t2_data = next(iter(t2_data)) to_t1_data = generator_g(sample_t1_data) to_t2_data = generator_f(sample_t2_data) plt.figure(figsize=(4, 4)) imgs = [sample_t1_data, to_t1_data, sample_t2_data, to_t2_data] title = ['t1_data', 'To t1_data', 't2_data', 'To t2_data'] for i in range(len(imgs)): plt.subplot(2, 2, i+1) plt.title(title[i]) plt.imshow(imgs[i][0].numpy()[:, :, 0], cmap='gray') plt.axis('off') plt.show() # + id="OUWkuxBdY7dC" generator_g_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5) generator_f_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5) discriminator_x_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5) discriminator_y_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5) # + colab={"base_uri": "https://localhost:8080/"} id="nodnY3iiZHmy" outputId="c1be560c-815f-42d7-ffad-a3ee4d9d25d1" # Setting the path for saving the model. # %cd /content/drive/MyDrive/ml_projects/style-transfer-using-gans # + id="QJQgmFf2XDcz" # deleting saved model and images if any. # !rm -r ./Trained_Model # !rm -r *.png # + [markdown] id="jPfrn6Z8pke-" # ## Orchestration of training steps # + id="kajOP7sFY_XC" checkpoint_path = "./Trained_Model" ckpt = tf.train.Checkpoint(generator_g=generator_g, generator_f=generator_f, discriminator_x=discriminator_x, discriminator_y=discriminator_y, generator_g_optimizer=generator_g_optimizer, generator_f_optimizer=generator_f_optimizer, discriminator_x_optimizer=discriminator_x_optimizer, discriminator_y_optimizer=discriminator_y_optimizer) ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=3) # if a checkpoint exists, restore the latest checkpoint. if ckpt_manager.latest_checkpoint: ckpt.restore(ckpt_manager.latest_checkpoint) print ('Latest checkpoint restored!!') # + id="PfiYm7erZEYy" def generate_images(model1, test_input1, model2, test_input2): prediction1 = model1(test_input1) prediction2 = model2(test_input2) plt.figure(figsize=(24, 12)) display_list = [test_input1[0], prediction1[0], test_input2[0], prediction2[0]] title = ['Input Image', 'Predicted Image', 'Input Image', 'Predicted Image'] images = [] for i in range(4): plt.subplot(1, 4, i+1) plt.title(title[i]) img = plt.imshow(display_list[i].numpy()[:, :, 0], cmap='gray') images.append(img) plt.axis('off') plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() # + id="d6eAiMvZZORS" @tf.function def train_step(real_x, real_y): # persistent is set to True because the tape is used more than # once to calculate the gradients. with tf.GradientTape(persistent=True) as tape: # Generator G translates X -> Y # Generator F translates Y -> X fake_y = generator_g(real_x, training=True) cycled_x = generator_f(fake_y, training=True) fake_x = generator_f(real_y, training=True) cycled_y = generator_g(fake_x, training=True) # same_x and same_y are used for identity loss. same_x = generator_f(real_x, training=True) same_y = generator_g(real_y, training=True) disc_real_x = discriminator_x(real_x, training=True) disc_real_y = discriminator_y(real_y, training=True) disc_fake_x = discriminator_x(fake_x, training=True) disc_fake_y = discriminator_y(fake_y, training=True) # calculate the loss gen_g_loss = generator_loss(disc_fake_y) gen_f_loss = generator_loss(disc_fake_x) total_cycle_loss = (calc_cycle_loss(real_x, cycled_x) + calc_cycle_loss(real_y, cycled_y)) # Total generator loss = BCE loss + cycle loss + identity loss total_gen_g_loss = gen_g_loss + total_cycle_loss + identity_loss(real_y, same_y) total_gen_f_loss = gen_f_loss + total_cycle_loss + identity_loss(real_x, same_x) # tf.print(disc_fake_x) # Discriminator's loss disc_x_loss = discriminator_loss(disc_real_x, disc_fake_x) disc_y_loss = discriminator_loss(disc_real_y, disc_fake_y) # Calculate the gradients for generator and discriminator generator_g_gradients = tape.gradient(total_gen_g_loss, generator_g.trainable_variables) generator_f_gradients = tape.gradient(total_gen_f_loss, generator_f.trainable_variables) discriminator_x_gradients = tape.gradient(disc_x_loss, discriminator_x.trainable_variables) discriminator_y_gradients = tape.gradient(disc_y_loss, discriminator_y.trainable_variables) # Apply the gradients to the optimizer generator_g_optimizer.apply_gradients(zip(generator_g_gradients, generator_g.trainable_variables)) generator_f_optimizer.apply_gradients(zip(generator_f_gradients, generator_f.trainable_variables)) discriminator_x_optimizer.apply_gradients(zip(discriminator_x_gradients, discriminator_x.trainable_variables)) discriminator_y_optimizer.apply_gradients(zip(discriminator_y_gradients, discriminator_y.trainable_variables)) return (total_gen_g_loss, total_gen_f_loss, disc_x_loss, disc_y_loss, total_cycle_loss) # + [markdown] id="Eg5o9pcodEMH" # ## Training # + colab={"base_uri": "https://localhost:8080/", "height": 355} id="vE50FDouZRRy" outputId="c80a14a5-da45-4993-b1fa-47f0bcd69bab" # ETA : 45 minutes approx on Google Colab Pro. EPOCHS = 250 eval_metrics = [] for epoch in tqdm.tqdm(range(1, EPOCHS+1)): for image_x, image_y in tf.data.Dataset.zip((t1_data, t2_data)): total_gen_g_loss, total_gen_f_loss, disc_x_loss, disc_y_loss, cycle_loss = train_step(image_x, image_y) # for higher file size 512*512 px the notebook crashes due to high memory usage hence clearing the prev output. # the images are saved to disk to analyze the progress. clear_output(wait=True) # save every few epochs if epoch % 20 == 0: ckpt_save_path = ckpt_manager.save() print('Saving checkpoint for epoch', epoch, 'at', ckpt_save_path) generate_images(generator_g, sample_t1_data, generator_f, sample_t2_data) eval_metrics.append({"total_gen_g_loss": total_gen_g_loss.numpy(), "total_gen_f_loss": total_gen_f_loss.numpy(), "disc_x_loss": disc_x_loss.numpy(), "disc_y_loss": disc_y_loss.numpy(), 'cycle_loss': cycle_loss.numpy()}) # + [markdown] id="KO-37CzYd01m" # ## Evaluation # + [markdown] id="mbLCV48RpsHg" # # # Below are some of the ways GANs can be evaluated. # 1. Visual Inspection. # 2. Fréchet inception distance # # Note: The FID is calculated by running images through an Inception network. In practice, we compare the intermediate representations—feature maps or layers—rather than the final output (in other words, we embed them). More concretely, we evaluate the distance of the embedded means, the variances, and the covariances of the two distributions—the real and the generated one. # # For this project FID cannot be used because # 1. Availability of pre-training inception model for T1/t2 brain images. # 2. Data Availability - min a 10k images are required (https://wandb.ai/ayush-thakur/gan-evaluation/reports/How-to-Evaluate-GANs-using-Frechet-Inception-Distance-FID---Vmlldzo0MTAxOTI) # # Hence we will be using visual inspection for evaluating the results. # + id="k32Dgid_SWab" colab={"base_uri": "https://localhost:8080/"} outputId="ece9a960-c982-4f93-ab08-4670a98a03d3" from PIL import Image anim_file = 'cyclegan.gif' frames = [] with imageio.get_writer(anim_file, mode='I') as writer: filenames = glob.glob('image*.png') filenames = sorted(filenames) for filename in tqdm.tqdm(filenames): new_frame = Image.open(filename) frames.append(new_frame) frames[0].save(anim_file, format='GIF', append_images=frames[1:], save_all=True, duration=300, loop=0) # + [markdown] id="kL2Td9KVaHE6" # #### Visual Inspection. # # # Due to the large size of the image (40mb), it cannot be embedded into the notebook. The below image shows how the network was able to learn the conversion process. The image can be downloaded from [here](https://drive.google.com/uc?id=14YT-0AWuoE86iIXypGOGk7PKjGt76UNp). If you run the notebook a file by name **cyclegan.gif** will be created in the current folder. # # As you may notice, through visual inspection it is clear that models are able to convert t1->t2 (1st and 2nd) and t2->t1 (3rd and 4th) images respectively. # This proves that the latent space is learnt by the models F & G which can now be used independently to generate t2/t1 images. # # Iterating the use cases # - Reduce the cost of MRI scans for different types of images. T2-weighted / T1-weighted, the cost reduction ranges from 5k - 20k as explained above. # - the images can be used to improve the classification accuracies of existing models by producing more synthetic data which are of higher quality and varied than regular data augmentation techniques. # # <img src="https://drive.google.com/uc?id=14YT-0AWuoE86iIXypGOGk7PKjGt76UNp"/> # + id="AGZr7aYRjXBj" colab={"base_uri": "https://localhost:8080/", "height": 361} outputId="07bb58f1-9388-4779-9c45-c64d2d1e05f5" # converting metrics to dataframe. import pandas as pd import seaborn as sns metrics = pd.DataFrame.from_records([m for m in eval_metrics]) metrics.head(10) # + id="YEpDVCYGzZbY" def draw_metrics_chart(cols, title, ytitle): sns.set_style("darkgrid") plt.figure(figsize=(12,4)) ax = sns.lineplot(data=metrics[cols]) plt.title(title) plt.xlabel("Epoch") plt.ylabel(ytitle) plt.show() # + id="Zd0-NSKMlYOA" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="cc048b11-c3ae-4f7f-989c-a41aeaa51f72" draw_metrics_chart(['total_gen_g_loss', 'total_gen_f_loss'], "Generator Losses per Epoch", "Generator Loss") # + id="xFi-fSpUvzNR" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="fdfdcdf8-9aa7-4f93-d656-3ce7716fb498" draw_metrics_chart(['disc_x_loss', 'disc_y_loss'], "Discriminator Loss per Epoch", "Discriminator Loss") # + id="aS-qJ4FTwUij" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="793d0e00-eaae-455b-8d65-010a40caf05d" draw_metrics_chart(['cycle_loss'], "Cycle Loss per epoch", "Cycle Loss") # + [markdown] id="mbvu879xa7Pp" # ### Summary # - Although the graphs alone are not reliable we can notice the loss coming down per epoch. # - Through visual inspection it is clear that the images are converted to alternate domain correctly. # - Further the evaluation can be improved if we can calculate the Frenchet Inception score using a pre-training inception model which is good at classifying T1/T2 Brain MRI images.
style_transfer_using_cyclegan_brainmri.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] nbgrader={"grade": false, "grade_id": "cellc-a00", "locked": true, "schema_version": 1, "solution": false} # # Lista 01 - EDA + Visualização # + nbgrader={"grade": false, "grade_id": "cell-20fe39048e63375d", "locked": true, "schema_version": 1, "solution": false} # -*- coding: utf 8 from matplotlib import pyplot as plt import pandas as pd import numpy as np plt.style.use('seaborn-colorblind') plt.ion() # + [markdown] nbgrader={"grade": false, "grade_id": "cell-9d1ad29e35bed9f4", "locked": true, "schema_version": 1, "solution": false} # # Exercício 01: # Em determinadas épocas do ano a venda de certos produtos sofre um aumento significativo. Um exemplo disso, são as vendas de sorvete que aumentam bastante no verão. Além do sorvete, outros itens como protetor solar e vestuário de banho podem ganhar maior atenção durante essa época do ano enquanto outros produtos podem não ser tão valorizados. Neste primeiro exercício, implemente a função abaixo que recebe quatro listas e cria um dataframe das quatro. A primeira lista será o índice do seu dataframe. A última, o nome das colunas. # # # Por exemplo, ao passar: # # ```python # ice_cream = [3000, 2600, 1400, 1500, 1200, 500, 300, 400, 700, 600, 800, 1900] # sunglasses = [1000, 800, 100, 70, 50, 190, 60, 50, 100, 120, 130, 900] # coats = [10, 20, 80, 120, 100, 500, 900, 780, 360, 100, 120, 20] # labels = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] # # names = ["icecream", "sunglasses", "coats"] # # cria_df(labels, ice_cream, sunglasses, coats, names) # ``` # # A tabela deve ser da forma: # # ``` # icecream sunglasses coats # ------------------------------------ # Jan 3000 1000 10 # Fev 2600 800 20 # ... ... ... ... # Dez 1900 900 20 # ``` # # __Dica__ # # Usar `list(zip(colunas))`. Ou, montar um dicionário na mão. # + nbgrader={"grade": false, "grade_id": "cell-3f60daae27375779", "locked": false, "schema_version": 1, "solution": true} def cria_df(labels, coluna1, coluna2, coluna3, names): ### BEGIN SOLUTION return pd.DataFrame(list(zip(coluna1, coluna2, coluna3)), columns=names, index=labels) ### END SOLUTION # + nbgrader={"grade": true, "grade_id": "cell-7ffe28105370b669", "locked": true, "points": 0, "schema_version": 1, "solution": false} ice_cream = [3000, 2600, 1400, 1500, 1200, 500, 300, 400, 700, 600, 800, 1900] sunglasses = [1000, 800, 100, 70, 50, 190, 60, 50, 100, 120, 130, 900] coats = [10, 20, 80, 120, 100, 500, 900, 780, 360, 100, 120, 20] labels = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] names = ["icecream", "sunglasses", "coats"] df = cria_df(labels, ice_cream, sunglasses, coats, names) df # + nbgrader={"grade": true, "grade_id": "cell-b2303ad17830c747", "locked": true, "points": 1, "schema_version": 1, "solution": false} ### BEGIN HIDDEN TESTS from numpy.testing import assert_array_equal for _ in range(100): k = np.random.randint(1, 10) ice_cream = np.array([3000, 2600, 1400, 1500, 1200, 500, 300, 400, 700, 600, 800, 1900]) + k sunglasses = np.array([1000, 800, 100, 70, 50, 190, 60, 50, 100, 120, 130, 900]) + k coats = np.array([10, 20, 80, 120, 100, 500, 900, 780, 360, 100, 120, 20]) + k labels = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] names = ["icecream", "sunglasses", "coats"] df = cria_df(labels, ice_cream, sunglasses, coats, names) assert_array_equal(df['icecream'].values, ice_cream) assert_array_equal(df['sunglasses'].values, sunglasses) assert_array_equal(df['coats'].values, coats) ### END HIDDEN TESTS # + [markdown] nbgrader={"grade": false, "grade_id": "cell1c-a00", "locked": true, "schema_version": 1, "solution": false} # # Exercício 02: # # Agora, crie uma função que recebe seu dataframe e crie um gráfico de linhas mostrando a evolução das vendas dos produtos ao longo dos meses em porcentagem. Ou seja, um gráfico relacionando a porcentagem de produtos vendidos naquele mês em relação ao ano como um todo para as vendas de sorvetes, óculos de sol e casacos. # # Seu gráfico deve parecer com o plot abaixo: # + nbgrader={"grade": true, "grade_id": "cell-d0a2391bf51eef6f", "locked": true, "points": 0, "schema_version": 1, "solution": false} # Note as duas linhas de código abaixo não é a resposta!!! Estou apenas mostrando a imagem que espero! from IPython.display import Image Image('plot1.png') # + nbgrader={"grade": true, "grade_id": "cell1-a00", "locked": false, "points": 1, "schema_version": 1, "solution": true} ### BEGIN SOLUTION def bar_or_lines(list1, list2, list3): plt.plot(labels, [float(ice_cream[i])/sum(ice_cream) for i in range (len(ice_cream))], lw=3, label="Ice cream") plt.plot(labels, [float(sunglasses[i])/sum(sunglasses) for i in range (len(sunglasses))], lw=3, label="Sunglasses") plt.plot(labels, [float(coats[i])/sum(coats) for i in range (len(coats))], lw=3, label="Coats") plt.legend(loc='best') plt.ylabel("% sold") plt.title("Sales") plt.show() bar_or_lines(ice_cream, sunglasses, coats) ### END SOLUTION # + [markdown] nbgrader={"grade": false, "grade_id": "cell2c-a00", "locked": true, "schema_version": 1, "solution": false} # # Exercício 03: # # Utilizando os mesmos dados do exercício anterior, crie uma função que faz um scatter plot entre **icecream** e as outras duas colunas.. # # # __Dicas:__ # 1. "_Correlação não é o mesmo que causalidade!_" # 1. Abaixo novamente mostramos exemplos de figuras que você pode gerar. # + nbgrader={"grade": true, "grade_id": "cell-2ea1076a0d7e730e", "locked": true, "points": 0, "schema_version": 1, "solution": false} Image('plot2.png') # + nbgrader={"grade": true, "grade_id": "cell-e5e14252545fafb6", "locked": true, "points": 0, "schema_version": 1, "solution": false} Image('plot3.png') # + nbgrader={"grade": true, "grade_id": "cell2-a00", "locked": false, "points": 1, "schema_version": 1, "solution": true} #Exemplo: ice_cream = [3000, 2600, 1400, 1500, 1200, 500, 300, 400, 700, 600, 800, 1900] sunglasses = [1000, 800, 100, 70, 50, 190, 60, 50, 100, 120, 130, 900] coats = [10, 20, 80, 120, 100, 500, 900, 780, 360, 100, 120, 20] labels = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] def scatter(df): ### BEGIN SOLUTION x = df['icecream'] for col in df.columns: if col == 'icecream': continue plt.scatter(x, df[col]) plt.xlabel('icecream') plt.ylabel(col) plt.show() ### END SOLUTION scatter(df) # + [markdown] nbgrader={"grade": false, "grade_id": "cell3c-a00", "locked": true, "schema_version": 1, "solution": false} # # Exercício 04: # # # Agora vamos trabalhar com dados reais. Na mesma pasta deste notebook, encontra-se um `json` com os dados do site http://www.capitaldoscandidatos.info/. Sua tarefa será usar funções como `groupby` e `hist` para analisar tais dados. Diferente das perguntas anteriores, não vamos mais pedir para que você implemente funções. Ou seja, pode trabalhar diretamente nas células do Jupyter estilo um cientista de dados. # # Sua primeira tarefa será indicar os 10 partidos que em média mais lucraram depois da primeira eleição. Ou seja, a diferença de patrimônio entre 2014 (eleição 1) e 2018 (eleição 2). Assim, a célula de solução (abaixo, depois da célula que carrega os dados), deve criar uma variável `resposta`. A mesma é uma série pandas com os top 10 partidos que mais lucraram em média. **A resposta tem que ser um pd.Series, ou seja, uma única coluna!** # # __Dicas__ # # Não necessariamente para este trabalho, mas é sempre bom lembrar: # # 1. Você já aprendeu a programar e quando estiver repetindo muito chamadas, é um bom sinal que deve criar um função. # 2. Notebooks não são IDEs, use para trabalho exploratório. # + nbgrader={"grade": true, "grade_id": "cell-472cc848aa90ff95", "locked": true, "points": 0, "schema_version": 1, "solution": false} df = pd.read_json('capital.json') # + nbgrader={"grade": true, "grade_id": "cell3-a00", "locked": false, "points": 0, "schema_version": 1, "solution": true} ### BEGIN SOLUTION cols = ['patrimonio_eleicao_1', 'patrimonio_eleicao_2', 'sigla_partido'] mean = df[cols].groupby('sigla_partido').mean() resposta = mean['patrimonio_eleicao_1'] - mean['patrimonio_eleicao_2'] resposta = resposta.sort_values()[::-1][:10] resposta.sort_values() ### END SOLUTION # + nbgrader={"grade": true, "grade_id": "cell-13f6632aa690a965", "locked": true, "points": 1, "schema_version": 1, "solution": false} ### BEGIN HIDDEN TESTS df_original = pd.read_json('capital.json') cols = ['patrimonio_eleicao_1', 'patrimonio_eleicao_2', 'sigla_partido'] mean = df_original[cols].groupby('sigla_partido').mean() esperado = mean['patrimonio_eleicao_1'] - mean['patrimonio_eleicao_2'] esperado = resposta.sort_values()[::-1][:10] assert_array_equal(esperado.values, resposta.values) ### END HIDDEN TESTS # + [markdown] nbgrader={"grade": false, "grade_id": "cell-071ef711e4113451", "locked": true, "schema_version": 1, "solution": false} # Plote sua resposta abaixo! # + nbgrader={"grade": false, "grade_id": "cell-4d69e53a37d18ea7", "locked": false, "schema_version": 1, "solution": true} resposta.plot.bar() # + [markdown] nbgrader={"grade": false, "grade_id": "cell-1008ccfd6983120f", "locked": true, "schema_version": 1, "solution": false} # # Exercício 05: # # # Por fim, plote o histograma dos valores acima (lucro entre eleições) para todos os partidos. Brinque com valores diferentes do número de bins e interprete os dados. Para que a correção funcione, use a chamada da seguinte forma: `plt.hist()`. Brinque também com variações de histograma normalizado ou não. # + nbgrader={"grade": false, "grade_id": "cell-76b661e17e7fb310", "locked": false, "schema_version": 1, "solution": true} df = pd.read_json('capital.json') # carregando os dados +1 vez, caso tenha alterado. ### BEGIN SOLUTION cols = ['patrimonio_eleicao_1', 'patrimonio_eleicao_2', 'sigla_partido'] mean = df[cols].groupby('sigla_partido').mean() resposta = mean['patrimonio_eleicao_1'] - mean['patrimonio_eleicao_2'] resposta = resposta.sort_values() plt.hist(resposta, bins=20, density=True) ### END SOLUTION
listas/icd-lista-01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="wVoWWP2TkfpH" # # Protein Classifier using AWD-LSTM # + id="05m_tDaZkfpQ" import torch import torch.nn as nn from pathlib import Path import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import time import sklearn.metrics as metrics from IPython.display import HTML, display from torch.nn.utils.rnn import pad_sequence # + id="mp69KYdNkfpS" if torch.cuda.is_available(): dev = "cuda:0" else: dev = "cpu" # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="56HVWDq5kfpU" outputId="034e4862-f298-4b3f-e3be-b653ffaac8e3" dev # + colab={"base_uri": "https://localhost:8080/"} id="0frf8WW_kfpW" outputId="e8496ecc-dc07-43da-a355-0b2fd1a85b0f" torch.manual_seed(42) # + colab={"base_uri": "https://localhost:8080/", "height": 17} id="Q-6XVNYTkfpX" outputId="d567d9d9-1fb1-4dd3-8565-feeb354188de" HTML(""" <style> table, th, td { border: 1px solid black; } </style> """) # + [markdown] id="Qq9C8202kfpZ" # ## Usefull Functions # + id="V7-BmN0zkfpb" # Plot the training and validation loss using matplotlib def show_losses(training_loss, validation_loss): r"""Plot graphs with on x-axis epochs and y-axis the loss. This graph contains both the `training_loss` and `validation_loss` for each epoch. Parameters ---------- training_loss : array Containing the training loss for each epoch. validation_loss : array Containing the validation loss for each epoch Returns ------- Plot of the two graphs. """ np_loss = np.asarray(training_loss) np_val_loss = np.asarray(validation_loss) plt.plot(np_loss, label='Train loss') plt.plot(np_val_loss, label='Validation loss') plt.legend() plt.ylabel('Cross Entropy Loss') plt.xlabel('Epochs') plt.show() # + id="dX9RNmgTkfpZ" def train_model(epochs, model, train_loader, test_loader, optimizer, criterion): r"""Train the resnet18 model. Train the resnet18 model for `epochs`. Using the `optimizer` and the loss function in `criterion`. Parameters ---------- epochs : int Number of epochs to train the model. model : torch Model Model that is being trained. train_loader : torch Dataloader Dataloader containing the train data to train the model. test_loader : torch Dataloader Dataloader containing the test data to validate the model. optimizer : torch Optimizer Optimizer used to optimize the model. criterion : torch.nn Lossfunction Loss function used. This loss function has to be minimilized by the model. Returns ------- torch Model The trained model. loss_history : array Training loss for each epoch. val_loss_history : array Validation loss for each epoch. """ loss_history = [] val_loss_history = [] for epoch in range(epochs): # Inititiate loss variables epoch_loss = 0.0 epoch_val_loss = 0.0 train_correct_pred = 0 train_total = 0 test_correct_pred = 0 test_total = 0 print(f'Epoch: {str(epoch + 1)}') start_time = time.time() # Alterate between train and validaton phase for phase in ['train', 'val']: if phase == 'train': model.train(True) # Set model to training mode data_loader = train_loader else: model.train(False) # Set model to evaluate mode data_loader = test_loader # Loop over the data in batch sizes. for i, data in enumerate(data_loader, 0): # get the inputs; data is a one input (batch size), and y xs, ys = data[0], data[1] if ys.size(0) == batch_size: outputs = model(xs) # Flatten the label ys = ys.view(-1) _, predicted = torch.max(outputs.data, 1) loss = criterion(outputs, ys) total = ys.size(0) # Add loss to each epoch if phase == 'train': loss.backward() optimizer.step() epoch_loss += loss.item() train_total += total train_correct_pred += (predicted == ys).sum().item() else: epoch_val_loss += loss.item() test_total += total test_correct_pred += (predicted == ys).sum().item() train_accuracy = np.round((train_correct_pred / train_total * 100), 2) test_accuracy = np.round((test_correct_pred / test_total * 100), 2) epoch_loss /= len(train_loader) epoch_val_loss /= len(test_loader) loss_history.append(epoch_loss) val_loss_history.append(epoch_val_loss) print(f'Epoch {str(epoch)} Cross entropy Train Loss: {str(epoch_loss)} ; Validation Loss: {str(epoch_val_loss)}.; Train Accuracy: {str(train_accuracy)}%; Test Accuracy: {str(test_accuracy)}% ') end_time = time.time() epoch_time_minutes = (end_time - start_time) / 60 print(f'Epoch duration {str(epoch_time_minutes)} minutes.') print('Finished Training') return model, loss_history, val_loss_history # + id="dObmbgbvkfpc" # Tokenize the protein sequence (or any sequence) in kmers. def tokenize(df, protein_seqs_column, kmer_sz, premade_vocab=False): if not premade_vocab: kmers = set() # Loop over protein sequences for protein_seq in df[protein_seqs_column]: # Loop over the whole sequence for i in range(len(protein_seq) - (kmer_sz - 1)): # Add kmers to the set, thus only unique kmers will remain kmers.add(protein_seq[i: i + kmer_sz]) # Map kmers for one hot-encoding kmer_to_id = dict() id_to_kmer = dict() for ind, kmer in enumerate(kmers): kmer_to_id[kmer] = ind id_to_kmer[ind] = kmer vocab_sz = len(kmers) assert vocab_sz == len(kmer_to_id.keys()) else: kmer_to_id, id_to_kmer = premade_vocab vocab_sz = len(kmer_to_id) # Tokenize the protein sequence to integers tokenized = [] for i, protein_seq in enumerate(df[protein_seqs_column], 0): sequence = [] # If the kmer can't be found these indexes should be deleted remove_idxs = [] for i in range(len(protein_seq) - (kmer_sz -1)): # Convert kmer to integer kmer = protein_seq[i: i + kmer_sz] # For some reason, some kmers miss. Thus these sequences have to be removed try: sequence.append(kmer_to_id[kmer]) except: remove_idxs.append(i) tokenized.append(sequence) df['tokenized_seqs'] = tokenized df.drop(remove_idxs, inplace=True) return df, vocab_sz, kmer_to_id, id_to_kmer # + id="b0Sufgyqkfpc" # Function to show the accuracy of the model. def accuracy(model, data_loader): r"""Calculate accuracy of the model. Calculates the accuracy of the trained `model` for the `data_loader` in the input. Parameters ---------- model : torch Model The trained model. data_loader : torch Dataloader Torch dataloader containing the samples you want to test the accuracy for. Returns ------- Prints the accurucy of the `model` for the samples in the `data_loader` """ correct = 0 total = 0 with torch.no_grad(): for ind, data in enumerate(data_loader, 0): x, y = data x = x.squeeze(0) # Squeeze x in the correct shape y = y.squeeze(0) # Squeeze y in the correct shape output = model(x) output = output.unsqueeze(0) _, predicted = torch.max(output.data, 1) total += y.size(0) correct += (predicted == y).sum().item() accuracy = np.round((correct / total * 100), 2) print(f'Accuracy of the network is {str(accuracy)}%.') # + [markdown] id="VcW0LHbzkfpe" # ## Load the data # + from google.colab import drive from pathlib import Path drive.mount('content/', force_remount=True) base = Path('/content/content/My Drive/') # + # Google drive #file_paths = Path('/content/content/MyDrive/subcellular-location/v2/') # Linux path file_paths = Path('/home/mees/Desktop/Machine_Learning/subcellular_location/') # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="tbRFWsBukfpe" outputId="2290f72f-7005-49f3-f695-ea688643ffb6" data_file = Path('data/processed/protein_data_2021-04-04.csv') data_file = file_paths / data_file df = pd.read_csv(data_file, sep=';') df.head() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="sNGEB5i4kfpf" outputId="4a0f1948-d4c9-4891-df86-74d7100fa941" df.drop(columns=['Subcellular location [CC]'], inplace=True) df.head() # + [markdown] id="LNktYsKWkfpf" # ### Tokenize the Data # # The data has to be tokenized according to the Language Model trained before, therefore, we have to load in that dictionary. # + id="vJwNg0L9kfpg" # Set-up numpy generator for random numbers random_number_generator = np.random.default_rng(seed=42) KMER_SIZE = 3 # + id="j3QzdCOfkfpg" # Load the vocabolary from the Language Model vocab_save_file = Path('data/interim/LM_vocab.pkl') vocab_save_file = file_paths / vocab_save_file vocab = pickle.load(open(vocab_save_file, 'rb')) # + id="AtZA6bQ5kfpg" # Tokenize the protein sequence df, vocab_sz, kmer_to_id, id_to_kmer = tokenize(df, 'Sequence', KMER_SIZE, vocab) # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="v-GIN4-rkfph" outputId="30a21a4d-c729-406c-9eb4-feecbdf60810" df.head() # + colab={"base_uri": "https://localhost:8080/"} id="MZGZZKjMkfph" outputId="c32523a2-881e-42f9-a52e-50f143d7c48f" len(df) # + [markdown] id="p_s83p4ekfpi" # ### Numericalize the label data # + colab={"base_uri": "https://localhost:8080/"} id="6RnA7Ahwkfpi" outputId="21fbf819-505f-455f-dbd5-49004a725221" # Some fields are NaN, remove these df.dropna(inplace=True) len(df) # + [markdown] id="KqwWz9y7kfpi" # Create a dictionary to numericalize the labels. # + id="rVTVFS09kfpj" label_dict = {} for i, label in enumerate(df['Location'].unique(), 0): label_dict[label] = i # + id="GSU8mia8kfpj" def numericalizeClass(df, class_column, label_dict, label_column='Label'): df[label_column] = df[class_column].map(label_dict) return df # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="q-gQqK4Zkfpk" outputId="888c57aa-9f2f-4a3c-c3ea-65d897189647" df = numericalizeClass(df, 'Location', label_dict) df.head() # + colab={"base_uri": "https://localhost:8080/"} id="JGmFcAjJkfpk" outputId="c8a3c476-176a-44a9-edb3-40dbd8b5fecb" label_dict # + colab={"base_uri": "https://localhost:8080/", "height": 334} id="wlpBWvdWkfpl" outputId="30c5f808-392a-43fd-e799-742ca4ef9fa5" plt.hist(df['Label']) # + [markdown] id="AAnUfQNPkfpl" # # # ! It might help to rebalance the classes since classes 0, 3 and 4 are now over represented. Therefore, the model can just default to class 4. Since, if the model predicts class 4 for every sequence it will have an accuracy of around 34% already. # + [markdown] id="5jSGjtNVkfpm" # An other point is that the sequence should have some information to work with, according to this paper: # > https://www.nature.com/articles/s41598-019-38746-w # # A motif can be in between 3-20 amino acids, thus 1-6/7 kmers. I chose 5 kmers. However training time took way longer in that way. Therefore, I know choose another seqeunce length to reduce training time. # + id="hV_YQwZCkfpm" df['Length'] = df['tokenized_seqs'].str.len() # + colab={"base_uri": "https://localhost:8080/", "height": 317} id="M1Uk4Cffkfpm" outputId="45aa26d8-3bba-4630-dafb-b4318e382baa" plt.hist(df['Length'], range=(0, 100)) # + [markdown] id="HoMVJdmwkfpn" # Based on this, and reduce training time. I now choose a sequence length of 50 # + colab={"base_uri": "https://localhost:8080/"} id="F2SGZXjgkfpn" outputId="2c59f273-d341-40e0-8242-a8f76a04d6ae" df = df[df['Length'] >= 50] len(df) # + [markdown] id="Se0r2uHnkfpo" # This only removed about 60 entries. # Now, to address class imbalance. Create a weighted sampler. However, the current weight labels are not correct. For each entry there should be a weight attached. # # Unfortunately, adding weight labeling to the cross entropy loss doesn't work. So, for each label we are selecteing 100 randomly. # + total_of_labels = dict(df['Label'].value_counts(sort=False)) weight_labels = [] print(total_of_labels) for total_of_label in total_of_labels.values(): weight = 1 / (total_of_label / len(df)) weight_labels.append(weight) weight_labels # + data_total = len(df) threshold = 100 for label, amount in total_of_labels.items(): if amount > threshold: keep_fraction = (threshold / (amount / 100) / 100) del_fraction = 1 - keep_fraction label = str(label) df = df.drop(df.query('Label == ' + label).sample(frac=del_fraction).index) # - plt.hist(df['Label']) # + [markdown] id="4aMErvL7kfpo" # ## Dataset class # + id="ZdainIjGkfpp" class AminoClassifierDataset(torch.utils.data.Dataset): def __init__(self, df, num_classes, bs=1): self.df = df self.num_classes = num_classes self.batch_sz = bs def __len__(self): return len(self.df) def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() x = torch.LongTensor(self.df.iloc[idx]['tokenized_seqs']) x = x.to(dev) y = torch.LongTensor([self.df.iloc[idx]['Label']]) y = y.to(dev) return x, y # + [markdown] id="BTJPhWeQkfpp" # ## The Protein Classifier # # Creating the complete protein from its parts # + [markdown] id="tS3F6Jmkkfpp" # ### AWD-LSTM # Start with the AWD-LSTM, which encodes the protein sequence and is already trained. # # I can add more dropout and I should add including the last hidden layers (cell and hidden states). # - class EmbeddingDropout(torch.nn.Module): "Apply dropout to an Embedding with probability emp_p" def __init__(self, emb_p=0): super(EmbeddingDropout, self).__init__() self.emb_p = emb_p def forward(self, inp): drop = torch.nn.Dropout(self.emb_p) placeholder = torch.ones((inp.size(0), 1)).to(dev) mask = drop(placeholder) out = inp * mask return out # + id="8-QAxw1zkfpp" class WeightDropout(torch.nn.Module): "Apply dropout to LSTM's hidden-hidden weights" def __init__(self, module, weight_p): super(WeightDropout, self).__init__() self.module = module self.weight_p = weight_p # Save the name of the layer weights in a list num_layers = module.num_layers layer_base_name = 'weight_hh_l' self.layer_weights = [layer_base_name + str(i) for i in range(num_layers)] # Make a copy of the weights in weightname_raw for weight in self.layer_weights: w = getattr(self.module, weight) del module._parameters[weight] self.module.register_parameter(f'{weight}_raw', torch.nn.Parameter(w)) def _setweights(self): "Apply dropout to the raw weights" for weight in self.layer_weights: raw_w = getattr(self.module, f'{weight}_raw') if self.training: w = torch.nn.functional.dropout(raw_w, p=self.weight_p) else: w = raw_w.clone() setattr(self.module, weight, w) def forward(self, *args): self._setweights() return self.module(*args) # + id="l91JM4j3kfpq" class AWD_LSTM(torch.nn.Module): def __init__(self, num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, batch_sz = 1, pad_token=False): super(AWD_LSTM, self).__init__() if pad_token: vocab_sz += 2 else: vocab_sz += 1 # Embedding with droput self.encoder = torch.nn.Embedding(vocab_sz, emb_dim) self.emb_drop = EmbeddingDropout(emb_p=embed_p) # Dropouts on the inputs and the hidden layers self.input_dp = torch.nn.Dropout(p=input_p) self.hid_dp = torch.nn.Dropout(p=hidden_p) # Create a list of lstm layers with wieghtdropout self.lstms = [] for i in range(num_layers): self.lstms.append( WeightDropout(nn.LSTM(input_size=emb_dim, hidden_size=hid_sz, num_layers=1), weight_p)) self.lstms = nn.ModuleList(self.lstms) # Save all variables self.num_layers = num_layers self.vocab_sz = vocab_sz self.emb_dim = emb_dim self.hid_sz = hid_sz self.hidden_p = hidden_p self.embed_p = embed_p self.input_p = input_p self.weight_p = weight_p self.batch_sz = batch_sz # Initialize hidden layers self.reset_hidden() self.last_hiddens = (self.hidden_state, self.cell_state) def forward(self, xs): """Forward pass AWD-LSTM""" bs, sl = xs.shape # Because sequences consisting of only padding are removed from the mini-batch, the mini-batch alters # Therefore we have to adjust the hidden state for that if bs != self.last_hiddens[0].shape[1]: self._change_bs_hidden(bs) ys = [] hiddens = self.last_hiddens hidden_states = [hiddens] for i, lstm in enumerate(self.lstms): # Embed the input and add dropout to it x = xs[:, i] embed = self.encoder(x) embed_dp = self.emb_drop(embed) # Again add dropout, this feels like doing dropout on dropout, I dont know if it is worth input_dp = self.input_dp(embed_dp) # Dropout on the hidden states hiddens_dp = [] for hidden_state in hidden_states[i]: hiddens_dp.append(self.hid_dp(hidden_state)) hiddens_dp = tuple(hiddens_dp) # Go trough one LSTM layer output, hiddens = lstm(input_dp.view(1, bs, -1), hiddens_dp) # Detach hidden states det_hiddens = [] for hidden in hiddens: det_hiddens.append(hidden.detach()) det_hiddens = tuple(det_hiddens) hidden_states.append(det_hiddens) y = output.view(bs, 1, -1) ys.append(y) y = torch.stack(ys, dim=0) y = y.view(bs, sl, -1) self.last_hiddens = hidden_states[-1] return y, hidden_states def reset_hidden(self): self.hidden_state = torch.zeros((1, self.batch_sz, self.hid_sz)).to(dev) self.cell_state = torch.zeros((1, self.batch_sz, self.hid_sz)).to(dev) self.last_hiddens = (self.hidden_state, self.cell_state) def _change_bs_hidden(self, bs): hidden_state = self.last_hiddens[0] cell_state = self.last_hiddens[1] if bs > hidden_state.shape[1]: self.reset_hidden() else: corr_hidden_state = hidden_state[:,:bs,:] corr_cell_state = cell_state[:,:bs,:] self.last_hiddens = (corr_hidden_state, corr_cell_state) def freeze_to(self , n): params_to_freeze = n * 4 + 1 # Since each LSTM layer has 4 parameters plus 1 to also freeze the encoder total_params = len(list(self.parameters())) for i, parameter in enumerate(self.parameters()): parameter.requires_grad = True if i < params_to_freeze: parameter.requires_grad = False for name, parameter in self.named_parameters(): print(name) print(parameter.requires_grad) # + [markdown] id="5gr8AWMzkfpq" # ### SentenceEncoder # # This part encodes the whole sequences in seq_lenghts using the pretrained AWD-LSTM language model. # # We use the Identity class to replace the decoder in the original AWD-LSTM. # # Finally, the model should not be updated. Therefore, the forward pass is in torch.no_grad(). # + id="jlFVmQtqkfpr" class Identity(torch.nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x # + id="cA2cTY_Ekfpr" class SentenceEncoder(torch.nn.Module): def __init__(self, seq_len, model, pad_token): super(SentenceEncoder, self).__init__() self.seq_len = seq_len self.model = model self.pad_token = pad_token def forward(self, inp): with torch.no_grad(): # First element is batch size, second element is the sequence inp_size = inp.shape[1] bs = inp.shape[0] # Padded parts should not be taken into account and these padded sequences cannot go trough the embedding padded = inp == self.pad_token # It is nicer to add padding max_iterations = int(inp_size / self.seq_len) hidden_state_outputs = [] cell_state_outputs = [] # Save masked output for the pooling calculations masked_outputs = [] corr_size = 0 for i in range(0, self.seq_len * max_iterations, self.seq_len): # Calculate the corrected batch size, meaning that a sequence only consisting of # the padding_token will be not put in the LSTM total_padded = padded[:,i : i + self.seq_len].sum(dim = 1) == self.seq_len corr_bs = (total_padded == False).sum() _, hidden = self.model(inp[:corr_bs, i: i + self.seq_len]) for states in hidden: hidden_state_output = states[0] cell_state_output = states[1] # In order to concate the hidden outputs we have to correct for the decrease in batch size if corr_bs != bs: corr_size = bs - corr_bs corr_hidden = torch.zeros(1, corr_size, hidden_state_output.shape[2]) corr_mask = torch.zeros(1, corr_size) hidden_state_output = torch.cat([hidden_state_output, corr_hidden], dim = 1) cell_state_output = torch.cat([cell_state_output, corr_hidden], dim = 1) # If no corrections for sequence length is made the mask will be one (there is no mask) if corr_size == 0: mask = torch.ones(1, bs) # If there are corrections made, mask will be a combination of ones for the sequence in the batch # that is not corrected and zeros for the sequence that is corrected else: unmasked = bs - corr_size mask = torch.ones(1, unmasked) mask = torch.cat([mask, corr_mask], dim = 1) masked_outputs.append(mask) hidden_state_outputs.append(hidden_state_output) cell_state_outputs.append(cell_state_output) hidden_state_outputs = torch.cat(hidden_state_outputs, dim = 0) cell_state_outputs = torch.cat(cell_state_outputs, dim = 0) masked_outputs = torch.cat(masked_outputs, dim = 0) return (hidden_state_outputs, cell_state_outputs), masked_outputs # + [markdown] id="IeO_z7m-kfpr" # ### PoolingLinearClassifier # # The encoded sequence is needed to be pooled, otherwise the model can not use the information for classification. # # Then, the data is normalized using batchnorm. # Dropout is applied to prevent overfitting. # And linear layers with a ReLU activiation are used to classify the pooled protein data. # + id="w28cdQdpkfpr" def pool_encoded_sequence(output, masked): r"""Pool the encoded AA sequence and return one vector with the max_pool and avg_pool concatenated""" hidden_states = output[0] #cell_states = output[1] mask = masked == 0 sl, bs = hidden_states.shape[:2] lens = hidden_states.shape[0] - mask.long().sum(dim = 0) last_lens = mask[-sl:,:].long().sum(dim = 0).max() - 1 print('Last Lens in pooling function') print(last_lens) last_hidden_state = hidden_states[-last_lens, :, :] #last_cell_state = cell_states[-1, :, :] hidden_state_avg = hidden_states.masked_fill_(mask[:, :, None], 0).sum(dim = 0) hidden_state_avg.div_(lens[:, None]) #cell_state_avg = cell_states.sum(dim=0) / sl hidden_state_max = hidden_states.masked_fill_(mask[:, :, None], -float('inf')).max(dim = 0)[0] #cell_state_max = hidden_states.max(dim=0)[0] #x = torch.cat([last_hidden_state, last_cell_state, hidden_state_avg, cell_state_avg, \ # hidden_state_max, cell_state_max], 0) x = torch.cat([last_hidden_state, hidden_state_avg, hidden_state_max], 1) x = x.view(bs, -1) return x # + id="nCOiXkDUkfpr" class PoolingLinearClassifier(torch.nn.Module): r"""Pool the outputs from the encoder and classify it.""" def __init__(self, num_classes, batch_sz): super(PoolingLinearClassifier, self).__init__() self.num_classes = num_classes self.batch_sz = batch_sz if batch_sz > 1: self.layers = nn.Sequential( nn.BatchNorm1d(1150 * 3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.Dropout(p=0.2, inplace=False), nn.Linear(in_features=1150 * 3, out_features=50, bias=True), nn.ReLU(inplace=True), nn.BatchNorm1d(50, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.Dropout(p=0.1, inplace=False), nn.Linear(in_features=50, out_features=num_classes, bias=True) ) else: self.layers = nn.Sequential( nn.Dropout(p=0.2, inplace=False), nn.Linear(in_features=1150 * 3, out_features=50, bias=True), nn.ReLU(inplace=True), nn.Dropout(p=0.1, inplace=False), nn.Linear(in_features=50, out_features=num_classes, bias=True) ) def forward(self, inp): output_encoder, padded = inp pooled_output = pool_encoded_sequence(output_encoder, padded) y = self.layers(pooled_output) return y # + colab={"base_uri": "https://localhost:8080/"} id="aW7z7yI-kfpu" outputId="62562bb1-aa62-444f-e180-8d93ff377aaa" num_classes = len(label_dict) num_classes # + [markdown] id="eZmt9xEekfpr" # ### Combine everything in the protein classifier # # Combine every class and part in the protein classifier # + id="KPF-qx-lkfpr" class proteinClassifier(torch.nn.Module): r"""The complete protein classifier""" def __init__(self, num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, seq_len, num_classes, batch_size, pretrained_file=False): super(proteinClassifier, self).__init__() self.num_layers = num_layers self.vocab_sz = vocab_sz self.emb_dim = emb_dim self.hid_sz = hid_sz self.hidden_p = hidden_p self.embed_p = embed_p self.input_p = input_p self.seq_len = seq_len self.num_classes = num_classes self.batch_size = batch_size pad_token = vocab_sz + 1 if pad_token: language_model = AWD_LSTM(num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, batch_sz=batch_size, pad_token=True) else: language_model = AWD_LSTM(num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, batch_sz=batch_size) if pretrained_file: language_mode = torch.load(pretrained_file, map_location=torch.device(dev)) encoder = SentenceEncoder(seq_len, language_model, pad_token) classifier = PoolingLinearClassifier(num_classes, self.batch_size) self.layers = nn.Sequential(encoder, classifier) def forward(self, inp): y = self.layers(inp) return y # + [markdown] id="OSUp6mZHkfps" # ## Model hyperparameters and train the data # + id="Rf1MiKM_kfps" # Hyperparameters emb_dim = 400 # Embeddding dimension hid_sz = 1150 # Hidden size num_layers = 3 # Number of LSTM layers stacked together seq_len = 50 # Based on paper mentioned above batch_size = 2 # Dropout parameters embed_p = 0.1 # Dropout probability on the embedding hidden_p = 0.3 # Dropout probability on hidden-to-hidden weight matrices input_p = 0.3 # Dropout probablity on the LSTM input between LSTMS weight_p = 0.5 # Dropout probability on LSTM-to-LSTM weight matrices # + [markdown] id="cMaUgLbpkfpu" # ### Load in the pretrained model # + id="-RhParSjkfpu" pretrained_model = Path('models/AA_LM_v3_ph2.pt') pretrained_model = file_paths / pretrained_model # + colab={"base_uri": "https://localhost:8080/"} id="uJuNCOxskfpu" outputId="1a6f8ffc-4452-4d83-f3cc-d21bf831e1c1" model = proteinClassifier(num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, seq_len, num_classes, batch_size, pretrained_model) model.to(dev) # + [markdown] id="TYwstDEKkfpv" # ## Learning hyperparameters # + id="FmSpwoR7kfpv" # Hyperparameters learning_rate = 0.001 epochs = 5 adam_betas = (0.7, 0.99) # + id="Ajfvm-krkfpv" # Costfunction and optimize algorithm #criterion = torch.nn.CrossEntropyLoss(weight=torch.FloatTensor(weight_labels)) criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, betas=adam_betas) # + [markdown] id="NXkpsc7hkfpv" # ## Train the model # - # Since the data has different length, therefore I use the pack_sequence in the collate fn. # https://discuss.pytorch.org/t/dataloader-for-various-length-of-data/6418/12 # + # Deze functie voegt padding toe zodat ik een batch kan runnen want een batch moet gelijke grote hebben. # En sorteert ook op grote def collate_fn_padd(batch): padding_value = vocab_sz seqs = [] ys = [] for seq in batch: seqs.append(seq[0]) ys.append(seq[1]) # Add padding to the sequences padded = pad_sequence(seqs, batch_first=True, padding_value=padding_value) ys = torch.stack(ys, dim=0) # Calculate the real size so that the padded sequences can be sorted masked = padded == padding_value real_seq_size = padded.size(1) - masked.sum(dim=1) _, indices = torch.sort(real_seq_size, descending=True) sorted_masked = torch.zeros_like(masked) sorted_padded_sequences = torch.zeros_like(padded) for i, ind in enumerate(indices, 0): sorted_padded_sequences[i] = padded[ind] sorted_masked[i] = masked[ind] """ # It is nicer to add padding max_iterations = int(sorted_padded_sequences.size(1) / 50) # Testen hoe ik uit kan vogelen hoe die batch sizes kunnen worden aangepast for i in range(0, max_iterations * 50, 50): print('Possible input') inp = sorted_padded_sequences[:, i:i + 50] total_mask = sorted_masked[:, i:i+50].sum(dim=1) == 50 true_bs = (total_mask == False).sum() print(total_mask) print(true_bs) """ return sorted_padded_sequences, ys # + id="uDa2Eq40kfpv" # Load the data in the DataSet AADataset = AminoClassifierDataset(df, num_classes) # + id="GHShLf7Lkfpw" # Split the data in an 80/20% split for training and testing data_len = len(AADataset) train_part = int(0.8 * data_len) test_part = data_len - train_part train_set, test_set = torch.utils.data.random_split(AADataset, [train_part, test_part]) # + id="fbs-M47qkfpw" # Load the data into data loader train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, collate_fn=collate_fn_padd) test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True, collate_fn=collate_fn_padd) # - # Test for the real work for i, entry in enumerate(train_loader, 0): xs, ys = entry[0], entry[1] #print(xs.shape) #print(ys.shape) outputs = model(xs) # Flatten the label ys = ys.view(-1) #print(outputs.shape) #print(outputs) # print(ys.shape) #print(ys) loss = criterion(outputs, ys) #print(loss) # + colab={"base_uri": "https://localhost:8080/"} id="GKsYU03Nkfpw" outputId="a6006639-7874-4394-ccc1-b58cd88af89d" model, loss_history, val_loss_history = train_model(epochs, model, train_loader, test_loader, optimizer, criterion) # + colab={"base_uri": "https://localhost:8080/", "height": 279} id="keinNjOmkfpx" outputId="76b14142-0506-4857-80dc-1227d8c617fd" show_losses(loss_history, val_loss_history) # + id="99DY1ETOkfpx" save_model_file = '/home/mees/Desktop/Machine_Learning/subcellular_location/models/trained_protein_classifier_part2.pt' torch.save(model.state_dict, save_model_file) # - # Ik ga de outputs controleren van de verschillende layers of die hetzelfde zijn als Fastai outputs # + colab={"base_uri": "https://localhost:8080/"} id="zLlLv3BVkfpx" outputId="a9d34cdd-4d40-4753-afb2-3b8f7c60df15" # Show the accuracy on test data accuracy(trained_model, test_loader) # + colab={"base_uri": "https://localhost:8080/"} id="THbPwNEKkfpy" outputId="6929400f-45b9-4ada-f680-e9f7ceb5a985" # Show the accuracy on train data accuracy(trained_model, train_loader) # + colab={"base_uri": "https://localhost:8080/"} id="FbCIF6Vekfpy" outputId="7771899f-5e6e-460b-bd3a-8c14098aae56" with torch.no_grad(): all_predicted = [] ys = [] for ind, data in enumerate(test_loader, 0): x, y = data x = x.squeeze(0) # Squeeze x in the correct shape y = y.squeeze(0) # Squeeze y in the correct shape output = model(x) output = output.unsqueeze(0) _, predicted = torch.max(output.data, 1) all_predicted.append(predicted.item()) ys.append(y.item()) # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="dyS-kzfdkfpy" outputId="b3a6ad8d-b851-43d8-ea25-d4e925779f5f" confusion_matrix = metrics.confusion_matrix(ys, all_predicted) disp = metrics.ConfusionMatrixDisplay(confusion_matrix, display_labels=list(label_dict.values())) fig, ax = plt.subplots(figsize=(20, 20)) disp.plot(ax=ax) # - # As seen from this confusion matrix everything is mapped to class 4, this class is over represented ~5000 out of 16000 examples. So the cost is lowest to predict that one. Therefore, we have to use a weighted random sampler. And probably also batches to train faster. So first, implement training in batches. # + id="ssrnJCMGkfpz" outputId="da80c4cc-f824-47f4-da19-7394882254d3" print(label_dict) # - # ## Testen met Fastai als referentie # Embedding dropout encoder = torch.nn.Embedding(10, 7, padding_idx=1) emb_drop = torch.nn.Dropout(p=0.5) tst_inp = torch.randint(0,10,(8,)) tst_out = emb_drop(encoder(tst_inp)) tst_out class EmbeddingDropout(torch.nn.Module): "Apply dropout to an Embedding with probability emp_p" def __init__(self, emb_p=0): super(EmbeddingDropout, self).__init__() self.emb_p = emb_p def forward(self, inp): drop = torch.nn.Dropout(self.emb_p) placeholder = torch.ones((inp.size(0), 1)) mask = drop(placeholder) out = inp * mask return out tst_inp = torch.randint(0,10,(1,)) print(tst_inp.shape) print(tst_inp) encoder = torch.nn.Embedding(10, 7, padding_idx=1) encoded = encoder(tst_inp) print(encoded.shape) emb_drop = EmbeddingDropout(emb_p=0.5) tst_out = emb_drop(encoded) print(tst_out.shape) for i in range(8): assert (tst_out[i]==0).all() or torch.allclose(tst_out[i], 2*encoder.weight[tst_inp[i]]) # + tst_inp = torch.randint(0,10,(8,)) drop = torch.nn.Dropout(0.5) encoder = torch.nn.Embedding(10, 7, padding_idx=1) encoded = encoder(tst_inp) print(encoded) print(encoded.shape) placeholder = torch.ones((tst_inp.size(0), 1)) mask = drop(placeholder) print(mask) print(mask.shape) encoded * mask # - # Embedding dropout encoder = torch.nn.Embedding(10, 7, padding_idx=1) emb_drop = EmbeddingDropout(emb_p=0.5) tst_inp = torch.randint(0,10,(8,)) print(tst_inp) print(tst_inp.shape) encoded = encoder(tst_inp) print(encoded) tst_out = emb_drop(encoded) tst_out (tst_out==).sum() (tst_out==1).sum() # num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, batch_sz = 1 tst = AWD_LSTM(2, 100, 20, 10, 0.2, 0.02, 0.1, 0.2) x = torch.randint(0, 100, (1,5)) bs,sl = x.shape[:2] print(bs) print(sl) r = tst(x) # ## Testing Pooling # ## Pooling testing language_model = AWD_LSTM(num_layers, vocab_sz, emb_dim, hid_sz, hidden_p, embed_p, input_p, weight_p, batch_sz=batch_size, pad_token=True) pad_token = vocab_sz + 1 encoder = SentenceEncoder(seq_len, language_model, pad_token) def pool_encoded_sequence_test(output, masked): r"""Pool the encoded AA sequence and return one vector with the max_pool and avg_pool concatenated""" hidden_states = output[0] #cell_states = output[1] mask = masked == 0 sl, bs = hidden_states.shape[:2] lens = hidden_states.shape[0] - mask.long().sum(dim = 0) last_lens = mask[-sl:,:].long().sum(dim = 0).max() - 1 print('Last Lens in pooling function') print(last_lens) last_hidden_state = hidden_states[-last_lens, :, :] #last_cell_state = cell_states[-1, :, :] hidden_state_avg = hidden_states.masked_fill_(mask[:, :, None], 0).sum(dim = 0) hidden_state_avg.div_(lens[:, None]) #cell_state_avg = cell_states.sum(dim=0) / sl hidden_state_max = hidden_states.masked_fill_(mask[:, :, None], -float('inf')).max(dim = 0)[0] #cell_state_max = hidden_states.max(dim=0)[0] #x = torch.cat([last_hidden_state, last_cell_state, hidden_state_avg, cell_state_avg, \ # hidden_state_max, cell_state_max], 0) x = torch.cat([last_hidden_state, hidden_state_avg, hidden_state_max], 1) x = x.view(bs, -1) #print('Output pooling:') #print(x) #masked_output = x return last_hidden_state, hidden_state_avg, hidden_state_max def test_tensor(test, test_against): assert test.shape[0] == test_against.shape[0] for i, val in enumerate(test, 0): try: assert round(val.item(), 4) == round(test_against[i].item(), 4) except Exception as e: print(i) print(val.item()) print(test_against[i].item()) print(e) print('Test successfull') for i, data in enumerate(train_loader, 0): xs, ys = data[0], data[1] output, masked = encoder(xs) last_hidden_state, hidden_state_avg, hidden_state_max = pool_encoded_sequence_test(output, masked) hidden_state = output[0] sl, bs = hidden_state.shape[:2] masked = masked == 1 real_seq_length = masked.sum(dim = 0) last_hidden_seq = (sl - real_seq_length).max() - 1 print(last_hidden_seq) for i in range(bs): seq_length = real_seq_length[i] print('Seq length') print(seq_length) real_hidden = hidden_state[:seq_length, i,:] real_avg = real_hidden.sum(dim = 0) real_avg = real_avg / seq_length print('Average test:') test_tensor(real_avg, hidden_state_avg[i, :]) real_max = real_hidden.max(dim = 0)[0] print('Max test') test_tensor(real_max, hidden_state_max[i, :]) real_last = hidden_state[-last_hidden_seq,i,:].squeeze(0) print('Last hidden test') test_tensor(real_last, last_hidden_state[i, :]) break
notebooks/proteinClassifier_v3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: venv-datascience # language: python # name: venv-datascience # --- # + import warnings warnings.filterwarnings("ignore", category=FutureWarning) from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression # - iris = load_iris() model = LogisticRegression().fit(iris['data'], iris['target']) model.predict(iris['data'])
ML - Applied Machine Learning Foundation/01.ML Basic/ML Basic - demo only.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import geoviews as gv import cartopy.io.shapereader as shpreader import shapely.geometry as sgeom gv.extension('matplotlib') gv.output(fig='svg', size=250) # - # ## Define data # + def sample_data(): """ Returns a list of latitudes and a list of longitudes (lons, lats) for <NAME> (2005). The data was originally sourced from the HURDAT2 dataset from AOML/NOAA: http://www.aoml.noaa.gov/hrd/hurdat/newhurdat-all.html on 14th Dec 2012. """ lons = [-75.1, -75.7, -76.2, -76.5, -76.9, -77.7, -78.4, -79.0, -79.6, -80.1, -80.3, -81.3, -82.0, -82.6, -83.3, -84.0, -84.7, -85.3, -85.9, -86.7, -87.7, -88.6, -89.2, -89.6, -89.6, -89.6, -89.6, -89.6, -89.1, -88.6, -88.0, -87.0, -85.3, -82.9] lats = [23.1, 23.4, 23.8, 24.5, 25.4, 26.0, 26.1, 26.2, 26.2, 26.0, 25.9, 25.4, 25.1, 24.9, 24.6, 24.4, 24.4, 24.5, 24.8, 25.2, 25.7, 26.3, 27.2, 28.2, 29.3, 29.5, 30.2, 31.1, 32.6, 34.1, 35.6, 37.0, 38.6, 40.1] return lons, lats shapename = 'admin_1_states_provinces_lakes_shp' states_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename) lons, lats = sample_data() track = sgeom.LineString(zip(lons, lats)) title = 'US States which intersect the track of <NAME> (2005)' track_buffer = track.buffer(2) shapes = [] for state in shpreader.Reader(states_shp).geometries(): # pick a default color for the land with a black outline, # this will change if the storm intersects with our track facecolor = [0.9375, 0.9375, 0.859375] if state.intersects(track): facecolor = 'red' elif state.intersects(track_buffer): facecolor = '#FF7E00' shapes.append(gv.Shape(state).opts(facecolor=facecolor)) shapes.append(gv.Shape(track_buffer).opts(alpha=0.5)) shapes.append(gv.Shape(track).opts(facecolor='none')) # - # ## Plot gv.Overlay(shapes).relabel(title)
datashader-work/geoviews-examples/gallery/matplotlib/katrina_track.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Testing Model # + import glob from fastai.vision import load_learner, open_image, torch, defaults data_directory = './image_data/' def model_predict(file_path = './test_data/'): '''productionize the trained model''' defaults.device = torch.device('cpu') learn = load_learner(data_directory) test_image_directory = glob.glob(file_path + '*.jpg') pred_class_list = [] for image in test_image_directory: img = open_image(fn = image) pred_class,pred_idx,outputs = learn.predict(img) img.show() print(pred_class) # - model_predict()
model_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/Fed29/tutorials2021/blob/main/3_generative/VAE_Tutorial_Start.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="j_NvQnAbHWVd" # + [markdown] id="e8PEhbMy8Q-H" # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/m2lschool/tutorials2021/blob/main/3_generative/VAE_Tutorial_Start.ipynb) # # Contact: {<EMAIL>, <EMAIL>} # # ## Contents # * Enabling TPUs in colab # * Handling nested data structures using tree utilities in JAX # * Distributing computation over multiple devices using *pmap* # * Amortized variational inference (VAEs) # * Training VAEs optimizing ELBO # * Training $\beta$-VAEs # * Training VAEs using constraint optimization (GECO) # # + [markdown] id="-xLj3uXiG0aG" # # Set up your environment! # + id="oPZ737IgZU27" outputId="daa37eb0-8d13-4581-afc9-d6715f5b1765" colab={"base_uri": "https://localhost:8080/"} #@title Download and install all the missing packages required for this tutorial { display-mode: "code" } # ! pip install ipdb -q # ! pip install chex -q # ! pip install optax -q # ! pip install dm_haiku -q # ! pip install tfp-nightly[jax] -q # ! pip install tf-nightly -q # ! pip install livelossplot -q # # ! pip install gast==0.3.3 -q # # ! pip install grpcio==1.32.0 -q # # ! pip install h5py==2.10.0 -q print("All packages installed!") # + id="hk4fInRg8NWe" # @title Imports import inspect import os import chex import dill import functools import haiku as hk import jax import jax.numpy as jnp import numpy as np import optax as tx import requests from pprint import pprint import seaborn as sns from matplotlib import pyplot as plt from livelossplot import PlotLosses from livelossplot.outputs import MatplotlibPlot import tensorflow as tf import tensorflow_probability from tensorflow_probability.substrates import jax as tfp sns.set(rc={"lines.linewidth": 2.8}, font_scale=2) sns.set_style("whitegrid") # Returns the code of the python implementation of a given funciton as a string. get_code_as_string = lambda fn: dill.source.getsource(fn.__code__) # + id="g3jP_DUzIdgq" outputId="66031c3c-1b8f-44f6-8556-3e0aa900f59a" colab={"base_uri": "https://localhost:8080/"} # ------------------ # # Enable TPU support # # ------------------ # # This cell execution might take a while! don't worry :) # Don't forget to select a TPU or GPU runtime environment in # Runtime -> Change runtime type try: if 'TPU_DRIVER_MODE' not in globals(): url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver_nightly' resp = requests.post(url) TPU_DRIVER_MODE = 1 # The following is required to use TPU Driver as JAX's backend. from jax.config import config config.FLAGS.jax_xla_backend = "tpu_driver" config.FLAGS.jax_backend_target = "grpc://" + os.environ['COLAB_TPU_ADDR'] except: print('TPUs not found. Enable a TPU runtime going to: ' '"Runtime -> Change runtime type"') devices = jax.devices() print("Available devices:", devices) # Should print something like # Available devices: [TpuDevice(id=0, host_id=0, coords=(0,0,0), core_on_chip=0), TpuDevice(id=1, host_id=0, coords=(0,0,0), core_on_chip=1), TpuDevice(id=2, host_id=0, coords=(1,0,0), core_on_chip=0), TpuDevice(id=3, host_id=0, coords=(1,0,0), core_on_chip=1), TpuDevice(id=4, host_id=0, coords=(0,1,0), core_on_chip=0), TpuDevice(id=5, host_id=0, coords=(0,1,0), core_on_chip=1), TpuDevice(id=6, host_id=0, coords=(1,1,0), core_on_chip=0), TpuDevice(id=7, host_id=0, coords=(1,1,0), core_on_chip=1)] # + id="-Y8PuFMDHXr5" outputId="cf7dc65a-3f66-4193-f9c7-5d902a1afe0f" colab={"base_uri": "https://localhost:8080/"} devices # + [markdown] id="0pt6BEKM-8vZ" # # Warmup: bits and bobs # # Let's take a minute to look at some JAX functionality we will be using in this tutorial. # + [markdown] id="WETghW-t_PXg" # ## How to work with nested data with `jax.tree_utils` # # It is fairly common to structure data and parameters into nested formats, for example (nested) dictionaries, namedtuples, lists, dataclasses and variants thereof. For example, we might want to cleanly scope and group our model's variables by their component name into some dictionary-like format, like in Haiku, or in a Reinforcement Learning setting we might want to explicitely label the components of a rollout. # # Typically in our code we don't want to assume a priori any strucuture of the containers we are manipulating, and prefer code that can transparently handle arbitrary nested structures. Luckily JAX can natively do this for us, and we only need to familiarize ourselves with its `jax.tree_util` package, and make sure that our custom objects are registered with it (not to worry, we have libraries that do this for us!). # # You can find out more in the JAX `tree_util` package [documentation](https://jax.readthedocs.io/en/latest/jax.tree_util.html). # + id="SGMOcKeh_aOd" outputId="bc0f9187-6695-46e6-f27c-4463bab633ca" colab={"base_uri": "https://localhost:8080/"} from collections import namedtuple data_container = namedtuple('data_box', 'component_a component_b') data = dict( a=jnp.ones(shape=()), b= [ jnp.ones(shape=()), data_container(jnp.ones(shape=()), jnp.ones(shape=()))], c=(jnp.ones(shape=()), jnp.ones(shape=()))) print('Structured data\n', data) # + id="ejRpRP3eIHSx" outputId="450a8732-b33b-494c-a658-11d78a92b9a9" colab={"base_uri": "https://localhost:8080/"} data # + id="oZ1taZEdHyXX" outputId="f4c199e9-d00b-4d68-8367-3c114e3752ce" colab={"base_uri": "https://localhost:8080/"} # We can use `jax.tree_map` to apply the same function to all the tensors # contained in a nested data structure. fn = lambda x: x * 2 output = jax.tree_map(fn, data) print('Structure data, after {}'.format(get_code_as_string(fn)), output) # + id="CR948AoRI6lt" outputId="9bb03bad-4a05-4ce6-9fd3-705ca11779c7" colab={"base_uri": "https://localhost:8080/"} data = dict( a = jnp.array([1]), b = [ jnp.array([2]), data_container(jnp.array([3]), jnp.array([4])) ], c = (jnp.array([6]), jnp.array([5])) ) print('Structured data\n', data) # + id="22hvi8oCIUiT" outputId="5b8fcda0-62fe-4544-e1eb-d5594c5b0253" colab={"base_uri": "https://localhost:8080/"} # We can also call functions with multiple structured inputs, for example # parameters and gradients in an update step. fn = lambda x, y, delta=0.1: x + delta * y output = jax.tree_multimap(fn, data, data) print('Structure data, after {}'.format(get_code_as_string(fn)), output) # + id="HtM70CxmJYe1" # + id="QR55O2s0Igru" outputId="f0bee8b7-9b39-4f92-90fc-2ba993b9152b" colab={"base_uri": "https://localhost:8080/"} # We can also 'flatten' the data to get a list of all the tensors contained in # the nested data structure. entries = jax.tree_leaves(data) print('Tree leaves\n', entries) # + id="n7ieQMgJJhzJ" outputId="f9376edf-b360-4515-c1aa-9a4c74cc301b" colab={"base_uri": "https://localhost:8080/"} # We can 'unflatten' flattened data to get back the original strucure if we keep # around the original structure defintion. entries, tree_def = jax.tree_flatten(data) # tree_def capture the structure data = jax.tree_unflatten(tree_def, entries) print('Flattened data\n', entries) print('Unflattened data\n', data) # + id="xwohRJwdJuWt" outputId="21ddf9ee-b10b-4f7a-cf75-44b5d5442a25" colab={"base_uri": "https://localhost:8080/"} tree_def # + id="9GqjhiZQFabr" outputId="3e239cff-8755-4f27-c15f-283fb49b916d" colab={"base_uri": "https://localhost:8080/"} # ------------------------ # # WARMUP OPTIONAL EXERCISE # # ------------------------ # # You have some batched data, structured in an unknow way and you want # to recover a list of unbatched data, structured the same way. # Write the code to do that using jax.tree_utils input_data = dict( a=jnp.arange(3), b=[jnp.arange(3), data_container(jnp.arange(3), jnp.arange(3))], c=(jnp.arange(3), jnp.arange(3))) print('Input data') pprint(input_data) # + id="zdwMajuGK99A" flattened_data, tree_def = jax.tree_flatten(input_data) # + id="QBouhyS0K9g-" split_data = list(zip(*flattened_data)) # + id="j4WCCU3QLsqf" outputId="122b8167-6cae-49a3-b91b-fa9374d8eb91" colab={"base_uri": "https://localhost:8080/"} jax.tree_unflatten(tree_def, split_data[0]) # + id="bbtINKOoLumw" outputId="4f99768a-36d3-44da-be09-d49a36dabc03" colab={"base_uri": "https://localhost:8080/"} jnp.array(flattened_data)[:,1] # + id="Mz0Xgg-fLOvT" outputId="a809b1a3-0114-4773-e25b-568798b8094b" colab={"base_uri": "https://localhost:8080/"} unbatched_data = [jax.tree_unflatten(tree_def, entries) for entries in split_data] unbatched_data # + id="CtnfrrGpNdIi" outputId="26d87d76-aa44-40d9-e7dc-b8de69c056ce" colab={"base_uri": "https://localhost:8080/"} flattened_data, tree_def = jax.tree_flatten(input_data) flattened_data # + id="4hIOrlMjNyz7" outputId="f6d7e04a-3ea4-4b66-9eee-09930c7710ce" colab={"base_uri": "https://localhost:8080/"} flattened_data = jnp.array(flattened_data) flattened_data[:,1].reshape(1,-1) # + id="zf2puOScN2wN" unbatched_data = [jax.tree_unflatten(tree_def, flattened_data[:,i]) for i in range(len(flattened_data))] unbatched_data # + id="lAGPH7naOyPH" outputId="d79a64ff-cf2e-4439-aaf5-f82bf95ba363" colab={"base_uri": "https://localhost:8080/"} flattened_data, tree_def = jax.tree_flatten(input_data) flattened_data # + id="Y2cSXn1gK9MA" outputId="2315842d-0ac0-427b-b1a6-ab787ea44d06" colab={"base_uri": "https://localhost:8080/"} def unbatch(data): flattened_data, tree_def = jax.tree_flatten(data) # ADD CODE BELOW # ----------------------- split_data = zip(*flattened_data) unbatched_data = [jax.tree_unflatten(tree_def, entries) for entries in split_data] # ----------------------- return unbatched_data print('\nSplit data') pprint(unbatch(input_data)) # Expected output: # Input data # {'a': DeviceArray([0, 1, 2], dtype=int32), # 'b': [DeviceArray([0, 1, 2], dtype=int32), # data_box(component_a=DeviceArray([0, 1, 2], dtype=int32), component_b=DeviceArray([0, 1, 2], dtype=int32))], # 'c': (DeviceArray([0, 1, 2], dtype=int32), # DeviceArray([0, 1, 2], dtype=int32))} # Split data # [{'a': DeviceArray([0], dtype=int32), # 'b': [DeviceArray([0], dtype=int32), # data_box(component_a=DeviceArray([0], dtype=int32), component_b=DeviceArray([0], dtype=int32))], # 'c': (DeviceArray([0], dtype=int32), DeviceArray([0], dtype=int32))}, # {'a': DeviceArray([1], dtype=int32), # 'b': [DeviceArray([1], dtype=int32), # data_box(component_a=DeviceArray([1], dtype=int32), component_b=DeviceArray([1], dtype=int32))], # 'c': (DeviceArray([1], dtype=int32), DeviceArray([1], dtype=int32))}, # {'a': DeviceArray([2], dtype=int32), # 'b': [DeviceArray([2], dtype=int32), # data_box(component_a=DeviceArray([2], dtype=int32), component_b=DeviceArray([2], dtype=int32))], # 'c': (DeviceArray([2], dtype=int32), DeviceArray([2], dtype=int32))}] # + [markdown] id="r9ePo9Jm4U_s" # ## How to parallelize gradients computation over multiple devices using JAX. # # In JAX you can use the `pmap` primitive to parallelize computation over multiple devices; using reduction methods in `jax.lax` you can also have access to values aggregated across devices during the distributed computation, giving you a lot of flexibility over what you can achieve! # # For example, you can split a *large* batch over 8 TPU cores, compute partial # gradients over the split batches and average them prior to updating # the model parameters - in parallel - across all devices. # # Let's look at some example code of how this can be done. # # + id="Qwzp5tLReyhG" outputId="7445a645-b9c5-4224-f671-198b3365ffa0" colab={"base_uri": "https://localhost:8080/", "height": 1000} # ------- # # EXAMPLE # # ------- # # First off, let's verify that you that in this colab you should have access to # multiple TPU cores. num_dev = jax.local_device_count() print('Number of devices:\n', num_dev, '\n') # Let's define a simple data generation function, and an MSE loss for linear # regression. def get_data(prng_key, batch_size): x_key, noise_key = jax.random.split(prng_key, 2) x = jax.random.uniform(x_key, shape=(batch_size,1)) true_model = lambda x: x * 3 + 2 noise = lambda key: jax.random.normal(key, shape=(batch_size, 1)) * 0.2 return jnp.concatenate([x, true_model(x) + noise(noise_key)], axis=1) def loss_fn(params, data): prediction = params[0] * data[:, 0] + params[1] target = data[:, 1] return jnp.mean((prediction - target) ** 2) batch_size = 1024 prng_key = jax.random.PRNGKey(0) data = get_data(prng_key, batch_size) params = jax.random.normal(prng_key, shape=(2,)) # On a single core we can compute the gradients over a minibatch with: grad_fn = jax.grad(loss_fn) gradients = grad_fn(params, data) # and update the parameters using any update rule, like those you can find in # the optax package. # We now want to take advantage of the the multiple core made available to us. # To do so, we batch computation _over cores_. # We format the data and batch it twice, over cores and per-device core: data = get_data(prng_key, batch_size * num_dev) data = jnp.reshape(data, (num_dev, batch_size) + data.shape[1:]) # Note that the leading dimension is now the number of cores! print('Data shape:\n', data.shape, '\n') # We provide each core with a copy of the parameters. Given an instance of the # params we can use JAX's broadcasting utility to achieve this. broadcast = lambda params: jnp.broadcast_to(params, (num_dev,) + params.shape) mapped_params = broadcast(params) # All the parameters copies are synced at the start of the model fitting; since # the udpates to the params will be the same, params will stay synced during # optimization. print('Params:\n', params, '\n') print('Mapped params:\n', mapped_params, '\n') # We then pmap the gradient fn, averaging the gradients computed across devices # using the pmap primitive and the jax.lax.pmean function. def get_averaged_grads(params, data): grads = grad_fn(params, data) grads = jax.lax.pmean(grads, axis_name='i') return grads get_averaged_grads = jax.pmap( get_averaged_grads, axis_name='i', devices=jax.devices()) averaged_grads = get_averaged_grads(mapped_params, data) print('Averaged_grads:\n', averaged_grads, '\n') # Note that this is equivalent to mapping the gradient function and manually # averaging the result! get_mapped_grads = jax.pmap(grad_fn, axis_name='i', devices=jax.devices()) mapped_grads = get_mapped_grads(mapped_params, data) print('Mapped_grads:\n', mapped_grads, '\n') print('Manually averaged_grads:\n', jnp.mean(mapped_grads, axis=0), '\n') # Of course we can pmap in one step, cleanly, much more complicated logic. # For example, the whole update step: optimizer = tx.sgd(1e-1) def update(params, opt_state, data): loss, grads = jax.value_and_grad(loss_fn)(params, data) grads = jax.lax.pmean(grads, axis_name='i') raw_updates, opt_state = optimizer.update(grads, opt_state) params = tx.apply_updates(params, raw_updates) return params, opt_state, loss # Note that pmap also compiles the function to XLA, akin to JIT! update = jax.pmap(update, axis_name='i', devices=jax.devices()) opt_state = jax.tree_map(broadcast, optimizer.init(params)) losses = [] for _ in range(250): prng_key, data_key = jax.random.split(prng_key) data = get_data(prng_key, batch_size * num_dev) data = jnp.reshape(data, (num_dev, batch_size) + data.shape[1:]) mapped_params, opt_state, loss = update(mapped_params, opt_state, data) losses.append(jnp.mean(loss)) sz = 5; plt.figure(figsize=(4*sz,sz)) plt.subplot(121) plt.plot(losses) plt.title('loss') plt.subplot(122) data = get_data(prng_key, 100) plt.scatter(data[:,0], data[:,1], label='data') plt.plot( [0, 1], [mapped_params[0, 1], mapped_params[0, 0] + mapped_params[0, 1]], 'r', label='prediction') plt.legend(); # + [markdown] id="5cfQlEC07pal" # # Get the data # # In this tutorial we will use the MNIST and Fashion MNIST datasets (and variations thereof). # We can use TensorFlow data to download the data from the cloud. # + id="5EHWPAsd7u50" outputId="97920cc6-60a3-4b37-818f-5950db83e225" colab={"base_uri": "https://localhost:8080/", "height": 548, "referenced_widgets": ["33132a84631c4313b2d5a0f070b5b388", "29d450ffc17c489cab07984208522a7b", "c90236087dd44371a8ce6c24c45109b9", "c2e1692e4b0843c58639312d24c7951e", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "a4f491110f0c4b54ad4fa640fcaf3f52", "835e682ff60c4910b79197eb39be6cf5", "<KEY>", "52ae507ddf3940ea966d5a39ffde7efb", "bbbff2c33f8d4725b54307daa2450a75", "c9173814cb884ae0b7b1f02b55b33883", "<KEY>", "<KEY>", "<KEY>", "dab7062204894939a422c95505080f3b", "<KEY>", "<KEY>", "8a5657c3786b4fc495daf6ece4d1e3fa", "<KEY>", "f2c5e8b55e024736a5356becfd3a7d27", "<KEY>", "e1003746ccf842f7a6ec6a3b2043739a", "<KEY>", "c0a3a618f55448d0983ad237a63625c9", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "08d988c599154c61b07e1d7e40e92666", "d8f1da208e624bcea9a45f4e9e8e0cae", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "058494c434a1416ca70a9c4ec7fde975", "9d7e6f43dc0f42a7b6a8b13116061049", "15948beee1d449a28795b36479b0485b", "<KEY>", "9907999c805f4e6db59e0aba97d56967", "7a8b33bc3da74f44a4ea2d1f61468f0f", "<KEY>", "<KEY>", "4a4cd3b37ed04c4a8330096557175675", "a5d6fa820d3b41f898f477a7590ed8ae", "24648e05f1324f1fbb0a64b99e9d7572", "ac439aa8bd884f12a2556e282c8083a0", "73a8deef4530440a883a066a5812314f", "<KEY>", "ca6a2e60af934f4d9a4e7048366a48c9", "<KEY>", "ca5a366f30f44c31a3685fe60af8e0cb", "<KEY>", "<KEY>", "<KEY>", "171a9542ebf4445a8acfacad9d64aded", "<KEY>", "<KEY>", "<KEY>", "<KEY>"]} import tensorflow_datasets as tfds mnist = tfds.load("mnist") fashion_mnist = tfds.load("fashion_mnist") # + [markdown] id="GyhvFtmloDWd" # [Chex](https://github.com/deepmind/chex) is a library of utilities for helping to write reliable JAX code. # # Within `chex` you will find a `dataclass` object definition, which will automatically register new class instances into JAX, so you can easily apply JAX's tree utilities out of the box. We will use it to define a labelled data object type. # + id="QmrdDH2ibvGG" @chex.dataclass class ContextualData(): target: chex.Array context: chex.Array # + id="-3loVhgk-H2b" # Here we provide some utilities for experiment and data visualization. def gallery(array, ncols=None): """Rearrange an array of images into a tiled layout.""" nindex, height, width, num_channels = array.shape if ncols is None: ncols = int(np.sqrt(nindex)) nrows = int(np.ceil(nindex/ncols)) pad = np.zeros((nrows*ncols-nindex, height, width, num_channels)) array = np.concatenate([array, pad], axis=0) result = (array.reshape(nrows, ncols, height, width, num_channels) .swapaxes(1,2) .reshape(height*nrows, width*ncols, num_channels)) return result def imshow(x, title=''): """Shorthand for imshow.""" plt.imshow(x[..., 0], cmap='gist_yarg', interpolation=None) plt.axis('off') plt.title(title) def custom_after_subplot(ax: plt.Axes, group_name: str, x_label: str): """Disable Legend in LiveLossPlot (interactive Matplotlib)""" ax.set_title(group_name) ax.set_xlabel(x_label) ax.legend().set_visible(False) # + [markdown] id="ezk2BhLaqDMD" # # The datasets # # In this tuturial we will train _conditional_ models. # As such, and as suggested by the `ContextualData` defintion, the dataset will provide targets and contexts. We will use two types of context, depending on the dataset. # # - **Simple**: for FashionMNIST the context will be the object class label, in one-hot format. # - **Hard**: for MNIST digits we will make things a bit more interesting: the user will specify a simple function, mapping tuples of integers in the range `[0,9]` to an integer in `[0, 9]`, for example: # ``` # lambda i, j: (i + j) % 10 # ``` # The context will be a tuple of images from MNIST whose labels will match the context integers, and the target will be an MNIST image of the corresponging # output label. Hance, the result will be a dataset whose conditional context is potentially very rich and challenging to capture. # + id="kKwY_jfDHZdy" outputId="d1d698d7-8d85-43ff-f2bd-ddbe2237bada" colab={"base_uri": "https://localhost:8080/", "height": 306} # --------------------------------- # # SIMPLE context dataset generation # # --------------------------------- # def get_fashion_mnist(batch_size, data_split='train', seed=1, conditional=True): def _preprocess(sample): image = tf.cast(sample["image"], tf.float32) / 255.0 context = tf.one_hot(sample["label"], 10) # We can optionally make context constant, effectively making the dataset # unconditional. This can be useful for debuggin purposes. if not conditional: context *= 0 return ContextualData(target=image, context=context) ds = fashion_mnist[data_split] ds = ds.map(map_func=_preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) ds = ds.cache() ds = ds.shuffle(100000, seed=seed).repeat().batch(batch_size) return iter(tfds.as_numpy(ds)) # Visualize a sample of the data ds = next(get_fashion_mnist(batch_size=12)) d = gallery(ds.target) imshow(d, title='Fashion MNIST targets') # + id="UA4MF2yLB-W4" # ------------------------------- # # HARD context dataset generation # # ------------------------------- # def get_raw_data(data_split='train'): def _preprocess(sample): image = tf.cast(sample["image"], tf.float32) / 255.0 id = sample["label"] return image, id ds = mnist[data_split] ds = ds.map(map_func=_preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) ds = ds.cache() ds = ds.shuffle(100000, seed=0).batch(2048) images, labels = next(iter(tfds.as_numpy(ds))) data_by_label = [] for i in range(10): data_by_label.append(images[labels==i]) min_num = min([d.shape[0] for d in data_by_label]) return np.stack([d[:min_num] for d in data_by_label]) def get_mnist_digits(batch_size, fn=None, data_split='train', max_num_examplars=None): """Instantiates a data generation function implementing the input fn in mnist. Args: batch_size: (int) batch size of the returned data fn: (python function) default sum of two digits modulo 10, function from n digits to a digit. The generator will return a batch of n + 1 digit images whose labels correspont to inputs and output of the function. data_split: (string) default 'train', crop of mnist to use for the data. max_num_examplars: (int) maximum number of exemplars to be used - even when not specified all digits will be represented by the same number of exemplars. Returns: Function of JAX PRNG returning samples from mnist related to each other via the user input fn function. """ raw_data = get_raw_data(data_split) sz = raw_data.shape[1] if max_num_examplars is not None: sz = min(max_num_examplars, sz) if fn is None: # Examples # fn = lambda i, j: (i + j) % 10 # fn = lambda i: (i + 1) % 10 fn = lambda i: (i + 1) % 10 num_inputs = len(inspect.signature(fn).parameters) def data_fn(prng): digit_prng, sample_prng = jax.random.split(prng, 2) digit_indices = jax.random.randint( digit_prng, shape=[batch_size, num_inputs], minval=0, maxval=10) digit_indices = digit_indices.split(num_inputs, axis=1) digit_indices += [fn(*digit_indices)] sample_indices = jax.random.randint( sample_prng, shape=[batch_size, num_inputs+1], minval=0, maxval=sz) sample_indices = sample_indices.split(num_inputs + 1, axis=1) samples = [raw_data[i[..., 0], j[..., 0], ...] for i, j in zip(digit_indices, sample_indices)] return samples def generator(key=None): if key is None: key = jax.random.PRNGKey(0) while True: key, sample_key = jax.random.split(key) data = data_fn(sample_key) yield ContextualData(target=data[-1], context=data[:-1]) return generator def tile_context(context, filler_value=.2): entries = [gallery(d) for d in data.context] entry_shape = entries[0].shape separator = np.full((entry_shape[0], 1, 1), filler_value) entries = [ np.concatenate([e, separator], axis=1) for e in entries[:-1]] + entries[-1:] return np.concatenate(entries, axis=1) # Visualize samples of target with hard context function context_fn = lambda x, y, z: (x + y + z) % 10 data = next(get_mnist_digits(fn=context_fn, batch_size=16)()) sz = 5 plt.figure(figsize=(4 * sz, sz)) plt.subplot(122) imshow(gallery(data.target), 'Target with ' + get_code_as_string(context_fn)) plt.subplot(121) imshow(tile_context(data.context) , 'Context') # + [markdown] id="qmLbpAW0uHuq" # For convenience, we define a dataset constructor function taking a `hard` flag switching between the MNIST and Fashion MNIST datasets, as well a dummy dataset # constructor that we will use for the purpose of retrieving shape information at graph construction time. # + id="4eFPL0ag2aiY" def get_dataset(batch_size, num_dev, hard=False, data_split='train'): # Instantiates the dataset adjusting the batch size to support training on # multiple devices. if hard: dataset = get_mnist_digits( batch_size=batch_size*num_dev, data_split=data_split)() else: dataset = get_fashion_mnist( batch_size=batch_size*num_dev, data_split=data_split) return dataset def get_dummy_data(hard=False): # Returns an instance of the data to gather shape info. return next(get_dataset(batch_size=1, num_dev=1, hard=hard)) # + [markdown] id="E54OTbDJ91h2" # # Amortized variational inference (VAEs) # # Consider a joint distribution $p(x, z)$ over a set of latent variables $z \in \mathcal{Z}$ and observed variable $x \in \mathcal{X}$ (for instance, the images of our dataset). # # Making inference over the observed variable $x$ involves computing the posterior distribution $p(z|x) = p(x,z)/p(x)$ which is often intractable to compute, as the _marginal likelihood_ $p(x) = \int_z p(x, z)dz$ requires integrating over a potentially exponential number of configurations of $z$. # # **Variational Inference (VI)** can be used to approximate the posterior $p(z|x)$ in a tractable fashion. VI casts the problem of computing the posterior as an optimization problem introducing a family of tractable (simpler) distributions $\mathcal{Q}$ parametrized by $\lambda$. The objective is to find the best approximation of the true posterior $q_{\lambda^*} \in \mathcal{Q}$ that minimizes the Kullback-Leibler (KL) divergence with the exact prosterior: # $$ # q_{\lambda^*}(z) = \underset{q_{\lambda}}{arg min} \ \ D_{KL}(q_{\lambda}(z) || p(z|x)) # $$ # # $q_{\lambda^*}(z)$ can serve as a proxy for the true posterior distribution. Note that the solution depends on the specific value of the observed (evidence) variables $x_i$ we are conditioning on, so computing the posterior requires solving an optimization problem for each sample independently. # # In this tutorial, we use a much more efficient approach. Rather than solving an optimization process per data point, we can **amortize the cost of inference** by leveraging the power of function approximation and learn a deterministic mapping to predict the distributional variables as a function of $x$. Specifically, the posterior parameters for $x_i$ will be the output of a *learned* function $f_\theta(x_i)$, where $\theta$ are parameters shared across all data points. # # <!-- Objective - maximize: # \begin{equation} # \mathbb{E}_{p^*(x)} \mathbb{E}_{q(z|x)} \log p_{\theta}(x|z) - \mathbb{E}_{p^*(x)} KL(q(z|x)||p(z)) # \end{equation} --> # # For more information, see: # * [<NAME>, (2013), Auto-Encoding Variational Bayes](https://arxiv.org/abs/1312.6114) # * [<NAME>, (2019), An Introduction to Variational Autoencoders](https://arxiv.org/abs/1906.02691) # + [markdown] id="SEyt2e2JvTcL" # # Implement and train a (Conditional) Variational AutoEncoder # # Variational AutoEncoders (VAEs) are a powerful class of deep generative models with latent variables, comprising of three main components: an encoder, a decoder and a prior. # # The encoder, also called *inference* or *recognition model*, computes the approximate posterior distribution $q_{\phi}(z|x)$ of a given sample conditioned on $x$, while the decoder, or *generative model* reconstructs the sample starting from the latent variables $z$. In the conditional setting, the encoder and decoder will potentially also receive an additional conditioning input that we will refer to as _context_. # # When we have a unconditional generative model, we generally don't have control over the specific outputs produced by the model, and the generated samples could be anything depending on the sampled latent variable. Perhaps, a more useful generative process should allow one to influence specific characteristics of the samples to generate, for instance, based on a context variable $c$, e.g. a label or category. For this reason, in this tutorial, we focus on Conditional VAEs (CVAEs) where both the encoder and the decoder are conditioned on a context variable $c$. # # The main components of our model will be: # # * $P^*$ is the true data distribution. We have some samples from this in the form of a dataset. # * $p(z)$ is a *prior* distribution over the latent space. In general the prior is simply $\mathcal{N}(0, 1)$ but in our case we will *learn* a conditional prior distribution $p(z|c)$ based on the context. # * $E(x, c)$ the encoder outputs distributions over the latent space $Z$, not just elements of it. The produced distribution is denoted $q_\phi(z|x, c)$ and is the (approximate) *posterior* distribution. # * $D(z, c)$ the decoder may be stochastic again, modeling the output distribution $p_\theta(x|z, c)$. # # Now we go over the reconstruction and sampling process and finally motivate the losses used to train VAEs in this tutorial. # # ### Reconstruction # The process for reconstruction is: # # 1. Take $x, c \sim P^*$. # 2. Encode it $E_\phi(x|c)$, yielding $q_\phi(z|x, c)$. # 3. Sample a latent $z \sim q_\phi(z|x, c)$. # 4. Decode the latent $p_\theta(\hat{x}|z, c) = D_\theta(z, c)$. # 5. Sample a reconstruction: $\hat{x} \sim p_\theta(\hat{x}|z, c)$. # # The prior has not showed up here, it plays a role in sampling. # # <center> # <img src="https://drive.google.com/uc?id=1ENXCf3UkaGKy9sAi98w_cqafAb-UBRMw" width="800" alt="Illustration of conditional VAE reconstruction and sampling" /> # <figcaption>Illustration of the conditional VAE architecture. <br> Credits: <a href="https://ijdykeman.github.io/ml/2016/12/21/cvae.html"> https://ijdykeman.github.io/ml/2016/12/21/cvae.html</a></figcaption> # </center> # # ### Sampling # The sampling process is: # # 1. Given a context $c$, sample a latent $z \sim p(z|c)$ from the conditional prior. # 2. Decode the latent $p_\theta(x|z, c) = D_\theta(z, c)$. # 3. Sample a reconstruction: $x \sim p_\theta(x|z, c)$. # # In practice we usually use simple, parametrizable distributions in the encoder and decoder. More specifically: # # **Encoder** # Each latent dimension is a (univariate) gaussian, parametrized by mean and standard deviation. Note, this is the same as a multivariate guassian over the latent space with a diagional covariance matrix. # # **Decoder** # We will quantize the pixels to 0 and 1, which allows us to use a Bernoulli distribution per pixel to model it. Though for visualizations we will continue to use grayscale values. # # # ## The Loss # # We use maximum likelihood for training, that is, ideally we would like to maximize: # # $$\mathbb{E}_{x,c \sim P^*}\log p_{\theta}(x|c).$$ # # Note that $p_{\theta}(x|c)$ is the marginal probability distribution $p_{\theta}(x|c) = \int p_\theta(x, z|c) dz$. We can rewrite this in familiar terms as $\int p_\theta(x|z,c) p(z|c) dz$. However, computing (and maximizing) the above marginal is computationally infeasible. # # Instead, we can show # # $$\log p_{\theta}(x|c) \ge \mathbb{E}_{z \sim q(z|x,c)} \big[\log p_\theta(x | z,c)\big] - \mathbb{KL}\big(q_\phi(z | x,c) || p(z|c)\big).$$ # # This right hand side is called the evidence lower bound (ELBO). Broadly speaking the term variational methods, like variational inference, refers to this technique of using an approximate posterior distribution and the ELBO; this is where Variational Autoencoder gets its name from too. # # In order to try to maximize the likelihood, we maximize the ELBO instead. Recall from the lecture that under some conditions (that are not going to apply to us) the inequality is actually an equality. This yield the following loss used with Variational AutoEncoders: # # <font size=4> # <br> # <!-- $$ \mathcal{L}(X, z) = \mathbb{E}\big[\log P(X|z)\big] - D_{KL}\big[Q(z|X) \big|\big| P(z)\big].$$ --> # # $$ \mathcal{L}(x|c) = - \Big( \mathbb{E}_{z \sim q(z|x, c)} \big[\log p_\theta(x | z, c)\big] - \mathbb{KL}\big(q_\phi(z | x, c) || p(z|c)\big) \Big).$$ # </font> # # Observe that: # * The first term encourages the model to reconstruct the input faithfully. This part is similar to the Vanilla AutoEncoder. # * The second term can be seen as a *regularization term* of the encoder towards the prior. # * Encoder, Decoder and Prior are conditioned on the context $c$. Removing the conditioning corresponds to recovering the original VAE formulation. # # (The formula contains an expectation; in practice that would be approximated with one or more samples.) # # ## Implementation # We start by defining the main VAE object class. # # We want to decouple its interface from how its components are defined; for example at this point we don't really care if we are using neural networks to implement the mapping from inputs to posterior. # # Some of the implementation will have to be `haiku` specific, but we will make an effort to restrict these details into the initialization functions. # # # + id="ekvgMkI4mKlh" def _transform(component): return hk.without_apply_rng(hk.transform(component)) # Sum-reduce on all dimensions but batch size _batch_sum = jax.vmap(jnp.sum) class VAE(): """A (conditional) Variational Autoencoder. The class expects at construction time haiku modules implementing the conditional {encoder, decoder, prior}, as well as context projector module. The encoder, decoder and prior use the output of the context projector together with their other inputs to define distributions (posterior, output and conditional prior respectively), implemented as tfp.distributions. The context projector is used to map a potentially nested context to a single condition tensor. """ def __init__(self, *, encoder, decoder, prior, context_projector): self._encoder = _transform(encoder) self._decoder = _transform(decoder) self._prior = _transform(prior) self._context_projector = _transform(context_projector) def init_params(self, prng, data): prng_encoder, prng_decoder, prng_prior, prng_proj = jax.random.split( prng, 4) # Initialize the context mapping. # ADD CODE BELOW # ----------------------- context_projector_params = ... projected_context = ... # ----------------------- # Initialize the conditional prior. # ADD CODE BELOW # ----------------------- prior_params = ... z = ... # ----------------------- # Initialize the encoder. # ADD CODE BELOW # ----------------------- encoder_params = ... # ----------------------- # Initialize the decoder. # ADD CODE BELOW # ----------------------- decoder_params = ... # ----------------------- # Merge all the parameters into a single data structure. params = hk.data_structures.merge( context_projector_params, prior_params, encoder_params, decoder_params) return params def sample(self, params, prng, context, mean=True): prior_prng, decoder_prng = jax.random.split(prng) # Map the context. # ADD CODE BELOW # ----------------------- projected_context = ... # ----------------------- # Get the conditional prior distribution, and take a sample from it. # ADD CODE BELOW # ----------------------- conditional_prior = ... z = ... # ----------------------- # Get the conditional output distribution. # ADD CODE BELOW # ----------------------- output_distribution = ... # ----------------------- if mean: return output_distribution.mean() else: return output_distribution.sample(seed=decoder_prng) def sample_prior(self, params, prng, context): projected_context = self._context_projector.apply(params, context) conditional_prior = self._prior.apply(params, projected_context) return conditional_prior.sample(seed=prng) def decode(self, params, prng, z, context, mean=True): projected_context = self._context_projector.apply(params, context) output_distribution = self._decoder.apply(params, z, projected_context) if mean: return output_distribution.mean() else: return output_distribution.sample(seed=prng) def reconstruct(self, params, prng, x, context, mean=True): posterior_prng, decoder_prng = jax.random.split(prng) # Map the context. # ADD CODE BELOW # ----------------------- projected_context = ... # ----------------------- # Get the conditional posterior distribution p(z|x, context), and sample # from it. # ADD CODE BELOW # ----------------------- posterior = ... z = ... # ----------------------- # Get the conditional output distribution. # ADD CODE BELOW # ----------------------- output_distribution = ... # ----------------------- if mean: return output_distribution.mean() else: return output_distribution.sample(seed=decoder_prng) def stochastic_elbo(self, params, prng, x, context): """ELBO = log_p(x) - KL(q(z|x) || p(z)).""" projected_context = self._context_projector.apply(params, context) z, kl = self._z_and_kl(params, prng, x, projected_context) output_distribution = self._decoder.apply(params, z, projected_context) # Sum reduce over signal domain (but not over batch!) log_p_x = _batch_sum(output_distribution.log_prob(x)) elbo = log_p_x - kl # Assemble all the stats that we want to log in an extra output dictionary. extra_outputs = dict(kl=kl, log_p=log_p_x, elbo=elbo) return elbo, extra_outputs def kl(self, params, prng, x, context): projected_context = self._context_projector.apply(params, context) _, kl = self._z_and_kl(params, prng, x, projected_context) return kl def _z_and_kl(self, params, prng, x, projected_context): """Sample z and compute KL(q(z|x) || p(z)) = log_p(q(z|x)) - log_p(p(x)).""" # Get the conditional prior, given the pre-projected context # ADD CODE BELOW # ----------------------- prior = ... # ----------------------- # Get the conditional posterior distribution p(z|x, context), and sample # from it. # ADD CODE BELOW # ----------------------- posterior = ... z = ... # ----------------------- # Compute the posterior log probability for the sampled z. # Note _batch_sum: what is this doing? log_q_z = _batch_sum(posterior.log_prob(z)) # Compute prior log probability for the sampled z. # ADD CODE BELOW # ----------------------- log_p_z = ... # ----------------------- # Compute the KL (see formula) # ADD CODE BELOW # ----------------------- kl = ... # ----------------------- return z, kl # + [markdown] id="RwghDI92yqv2" # Here we define all the utilities we will need to implement Haiku modules for the prior, encoder and decoder required to instantiate a VAE. # + id="_S6eUGE_u37o" def _make_positive(x): """Transforms elementwise unconstrained inputs into positive outputs.""" # The offset is such that the output will be equal to 1 whenever the input is # equal to 0. offset = jnp.log(jnp.exp(1.) - 1.) return jax.nn.softplus(x + offset) class DiagonalNormal(tfp.distributions.Normal): """Normal distribution with diagonal covariance.""" def __init__(self, params, name='diagonal_normal'): if params.shape[-1] != 2: raise ValueError( f'The last dimension of `params` must be 2, got {params.shape[-1]}.') super().__init__( loc=params[..., 0], scale=_make_positive(params[..., 1]), name=name) class ConditionalPrior(hk.Module): """A prior distribution whose parameters are computed by a conditioner.""" def __init__(self, map_ctor, distribution, name='prior_net'): super().__init__(name=name) # This function will map: (bs,) + context shape --> (bs, num_latents, 2) self._map = map_ctor() self._distribution = distribution def __call__(self, context): return self._distribution(self._map(context)) class ConditionalEncoder(hk.Module): """A posterior distribution whose parameters are computed by a conditioner.""" def __init__(self, map_ctor, distribution, name='posterior_net'): super().__init__(name=name) # This function will map inputs to the to posterior distribution parameters. self._map = map_ctor() self._distribution = distribution def __call__(self, x, context): # We assume that x is an image and the context is flat. chex.assert_rank(x, 4) chex.assert_rank(context, 2) # Tile the context in order to be concatenated to the input tensor x. # ADD CODE BELOW # ----------------------- bs, height, width, _ = x.shape context = ... x_and_context = ... # ----------------------- # Compute the posterior q(z|x, context) return self._distribution(self._map(x_and_context)) class ConditionalDecoder(hk.Module): """An output distribution whose parameters are computed by a conditioner.""" def __init__(self, map_ctor, distribution, name='output_net'): super().__init__(name=name) # This function will map (z, context) to the to output distribution # parameters. self._map = map_ctor() self._distribution = distribution def __call__(self, z, context): chex.assert_equal_shape_prefix([z, context], -1) # Concatenate the context to the latents # ADD CODE BELOW # ------------------------------------------------------------- z_and_context = ... # ------------------------------------------------------------- return self._distribution(self._map(z_and_context)) # + [markdown] id="7Xvfdu2gzylj" # Here we define how to assemble the VAE. # + id="6HEAdV69u-RR" # -- Flat model def get_model(num_latents=50, num_hiddens=500, data_shape=[28, 28, 1]): """Creates a fully-connected VAE model.""" def _build_map_to_latent_dist_params_net(): return hk.Sequential([ hk.Flatten(), hk.nets.MLP([num_hiddens, num_hiddens, num_latents * 2]), hk.Reshape([num_latents, 2]), ]) def encoder_fn(*args, **kwargs): return ConditionalEncoder( map_ctor=_build_map_to_latent_dist_params_net, distribution=DiagonalNormal)(*args, **kwargs) def prior_fn(*args, **kwargs): return ConditionalPrior( map_ctor=_build_map_to_latent_dist_params_net, distribution=DiagonalNormal)(*args, **kwargs) def _build_map_to_output_dist_params_net(): return hk.Sequential([ hk.Flatten(), hk.nets.MLP([num_hiddens, num_hiddens, np.prod(data_shape)]), hk.Reshape(data_shape), ]) def decoder_fn(*args, **kwargs): return ConditionalDecoder( map_ctor=_build_map_to_output_dist_params_net, distribution=tfp.distributions.Bernoulli)(*args, **kwargs) def _concatenate(tensors): proj = hk.nets.MLP([num_hiddens, num_latents]) data = [] for x in jax.tree_leaves(tensors): if x.ndim > 2: x = proj(hk.Flatten()(x)) # Note: this is not commutative! # What could we do to make this projection commutative? data.append(x) data = jnp.concatenate(data, axis=-1) return data def proj_fn(*args): """Maps context inputs to conditioning tensor.""" return hk.to_module(_concatenate)('context_projector')(*args) return VAE(encoder=encoder_fn, decoder=decoder_fn, prior=prior_fn, context_projector=proj_fn) # + [markdown] id="OhmPt26y0xcK" # # Training # + [markdown] id="6abZ0QQz03Ig" # ## Shared hyper-parameters # + id="suQ8L-zEbHZn" # @title Shared hyper-parameters # Model hyper-parameters: you can play around with these and see what changes! BATCH_SIZE = 128 #@param {type:'integer'} VIS_BATCH_SIZE = 64 #@param {type:'integer'} NUM_LATENTS = 30 #@param {type:'integer'} NUM_HIDDENS = 50 #@param {type:'integer'} TRAINING_STEPS = 1000 #@param {type:'integer'} USE_HARD_DATA = False #@param {type:'boolean'} NUM_DEV = len(jax.local_devices()) # Plot configs: no need to change them PLOT_REFRESH_EVERY = 50 #@param {type:'integer'} PLOT_EVERY = 5 #@param {type:'integer'} # + id="Gd7H4PgM1duQ" model = get_model(num_latents=NUM_LATENTS, num_hiddens=NUM_HIDDENS) # Once we have trained a model, we can explore its latent space by interpolating # (and decoding) between latents. def get_latent_interpolations(model, params, prng_key, num_steps, context): start_key, stop_key, decoder_key = jax.random.split(prng_key, 3) z_start = model.sample_prior(params, start_key, data.context) z_stop = model.sample_prior(params, stop_key, data.context) # To ensure that the interpolation is still likely under the Gaussian prior, # we use Gaussian interpolation - rather than linear interpolation. a = jnp.linspace(.0, 1.0, num_steps) a = jnp.expand_dims(a, axis=1) interpolations = (jnp.sqrt(a) * z_start + jnp.sqrt(1 - a) * z_stop) ncols = int(jnp.sqrt(num_steps)) context = jax.tree_map( lambda x: jnp.tile(x, [num_steps] + [1] * (x.ndim-1)), data.context) samples_from_interpolations = model.decode( params, decoder_key, interpolations, context, mean=True) return samples_from_interpolations # + id="Kz4P1vzcMetd" # These are utilities for shape manipulation to facilitate training using pmap. @jax.jit def format_data(data): return jax.tree_map( lambda x: x.reshape((NUM_DEV, BATCH_SIZE) + x.shape[1:]), data) def setup_for_distributed_training(params, prng_key, opt_state, num_dev): broadcast = lambda x: jnp.broadcast_to(x, (num_dev,) + x.shape) (params, opt_state) = jax.tree_map(broadcast, (params, opt_state)) prng_key = jax.random.split(prng_key, num_dev) return params, prng_key, opt_state get_slice = lambda x: jax.tree_map(lambda x: x[0], x) def reconstruct_and_sample(params, prng_key, model, data): prng_key = prng_key[0] params = get_slice(params) sample_key, reconstruction_key, prng = jax.random.split(prng_key, 3) reconstruction = model.reconstruct( params, reconstruction_key, data.target, data.context) sample = model.sample(params, sample_key, data.context) return data.target, reconstruction, sample # + [markdown] id="<KEY>" # # Training a VAE optimizing ELBO # + id="xPbmUU_o0fn0" def get_elbo_loss_fn(model): def elbo_loss_fn(params, prng, data): elbo, stats = jax.tree_map( jnp.mean, model.stochastic_elbo(params, prng, data.target, data.context)) return -elbo, stats return elbo_loss_fn # + id="Q73uv5tSv2v0" elbo_loss_fn = get_elbo_loss_fn(model) # Initialize the model prng_key = jax.random.PRNGKey(0) params = model.init_params(prng_key, get_dummy_data(hard=USE_HARD_DATA)) # Instantiate and initialize the optimizer elbo_optimizer = tx.adam(1e-2) opt_state = elbo_optimizer.init(params) # Setup the optimizer state and params for distributed training params, prng_key, opt_state = setup_for_distributed_training( params, prng_key, opt_state, num_dev=NUM_DEV) dataset = get_dataset( batch_size=BATCH_SIZE, num_dev=NUM_DEV, hard=USE_HARD_DATA) # Define and pmap the update function def elbo_update(params, prng_key, opt_state, data): loss_key, prng_key = jax.random.split(prng_key) # Use jax.value_and_grad to compute amd return all the outputs and the # gradients for elbo_loss_fn (tip: what does the has_aux kwargs do?) # ADD CODE BELOW # ------------------------------------------------------------- loss_outputs, grads = ... # ------------------------------------------------------------- # Reduce-mean the gradients across devices. # ADD CODE BELOW # ------------------------------------------------------------- grads = ... # ------------------------------------------------------------- # Perform an udpate step on the elbo_optimizer to produce parameter udpates, # them apply the updates of the model params. # ADD CODE BELOW # ------------------------------------------------------------- raw_updates, opt_state = ... params = ... # ------------------------------------------------------------- return params, prng_key, opt_state, loss_outputs elbo_update = jax.pmap(elbo_update, axis_name='i', devices=jax.devices()) # -- Set up logging and interactive plotting losses = [] kls = [] logps = [] plot = PlotLosses( groups={ 'log p(x)': ['log_p'], 'KL': ['kl'], 'negative ELBO': ['negative ELBO']}, outputs=[MatplotlibPlot(max_cols=3, after_subplot=custom_after_subplot)], step_names='Iterations') # + id="ID2JuhlQh5V3" for step in range(TRAINING_STEPS): params, prng_key, opt_state, stats = elbo_update( params, prng_key, opt_state, format_data(next(dataset))) elbo = stats[1]['elbo'].mean() kl = stats[1]['kl'].mean() log_p = stats[1]['log_p'].mean() if (step + 1) % PLOT_EVERY == 0: plot.update({ 'negative ELBO': -elbo, 'kl': kl, 'log_p': log_p }, current_step=step) if (step + 1) % PLOT_REFRESH_EVERY == 0: plot.send() losses.append(elbo) kls.append(kl) logps.append(log_p) # + [markdown] id="j9BwJgKK6Jxz" # ## Visualize reconstructions and samples # # # # + id="Lg4X-0sg14pG" targets, reconstructions, samples = reconstruct_and_sample( params, prng_key, model, next(get_dataset(batch_size=VIS_BATCH_SIZE, num_dev=1, hard=USE_HARD_DATA, data_split='test'))) sz = 6 _ = plt.figure(figsize=((3*sz, 1*sz))) plt.subplot(131) imshow(gallery(targets), 'Targets') plt.subplot(132) imshow(gallery(reconstructions), 'Reconstructions') plt.subplot(133) imshow(gallery(samples), 'Conditional samples'); # + [markdown] id="WVxusk8L7ghe" # ## Explore the latent space # # # + id="AsWl27VltqGq" data = get_dummy_data(hard=USE_HARD_DATA) num_steps = 7 * 7 samples_from_interpolations = get_latent_interpolations( model, get_slice(params), jax.random.PRNGKey(1), num_steps, data.context) sz = 6 _ = plt.figure(figsize=((2*sz, sz))) plt.subplot(121) imshow(data.target[0,...], 'Label example') plt.subplot(122) imshow(gallery(samples_from_interpolations), 'Latent space interpolation') # + [markdown] id="1f4Dv2DwZssH" # # Training a VAE with KL annealing # # Stochastic Variational Inference can get stuck in local optima since there is a certain tension between the likelihood and the KL terms. To ease the optimization, we could use a schedule fpr $\beta$ where the KL coefficient is slowly annealed from $0$ to $1$ throughout training. This corresponds to weight more the reconstruction term at the beginning of the training and then move towards the fully stochastic variational objective. The modified objective becomes: # # <font size=4> # <br> # <!-- $$ \mathcal{L}(X, z) = \mathbb{E}\big[\log P(X|z)\big] - D_{KL}\big[Q(z|X) \big|\big| P(z)\big].$$ --> # # $$ \mathcal{L}(x|c) = - \Big( \mathbb{E}_{z \sim q(z|x, c)} \big[\log p_\theta(x | z, c)\big] - \beta \ \mathbb{KL}\big(q_\phi(z | x, c) || p(z|c)\big) \Big).$$ # </font> # # where the hyper-parameter $\beta$ is annealed throughout optimization. # # **Tasks:** # - Modify the training objective with a linear KL annealing schedule. # - Look at the loss terms, what differences do you notice in their behaviours compared to the standard VAE objective? # - Look at the reconstructions and samples during training. What do you see? # # </br> # # For more information, see: # * [Bowman et al, (2015), Generating Sentences from a Continuous Space, (Section 3.1)](https://arxiv.org/abs/1511.06349) # * [Sønderby et al, (2016), Ladder variational Autoencoder, (Section 2.3)](https://arxiv.org/abs/1602.02282) # * [Burgess et al, (2018), Understanding disentangling in β-VAE](https://arxiv.org/abs/1804.03599) # # # + id="Z7z1jIum0hyP" def get_beta_vae_loss_fn(model): def beta_vae_loss_fn(params, prng, beta, data): _, loss_components = jax.tree_map( jnp.mean, model.stochastic_elbo( params, prng, data.target, data.context)) # The beta-VAE training loss function is a function of the beta # hyper-parameter. Implement the loss using the components returned by # the stochastic_elbo of the model class. # elbo_loss_fn # ADD CODE BELOW # ------------------------------------------------------------- loss = ... # ------------------------------------------------------------- return loss, loss_components return beta_vae_loss_fn # + id="EjaxZ-cpZjTp" prng_key = jax.random.PRNGKey(0) params = model.init_params(prng_key, get_dummy_data(hard=USE_HARD_DATA)) beta_vae_loss_fn = get_beta_vae_loss_fn(model) # Set up the optimzer and model like you did for the ELBO optimization # ADD CODE BELOW # ------------------------------------------------------------- beta_vae_optimizer = ... opt_state = ... params, prng_key, opt_state = ... dataset = ... def beta_vae_update(params, prng_key, opt_state, beta, data): ... return params, prng_key, opt_state, beta_vea_loss beta_vae_update = ... # ------------------------------------------------------------- # During the optimization of the beta-VAE we will be scheduling the value of # beta. Use optax's polynomial schedule to set up a linear schedule, e.g. # from 0.01 to 1.0 over TRAINING_STEPS//2 steps. # ADD CODE BELOW # ------------------------------------------------------------- beta_vae_current_step = ... initial_beta, final_beta = ... beta_schedule = ... # ------------------------------------------------------------- beta_vae_losses = [] beta_vae_kls = [] beta_vae_logps = [] beta_vae_groups = { 'log p(x)': ['log_p'], 'kl': ['kl'], 'negative ELBO': ['negative ELBO'], 'beta': ['beta'] } beta_vae_plot = PlotLosses( groups=beta_vae_groups, outputs=[MatplotlibPlot(max_cols=4, after_subplot=custom_after_subplot)], step_names='Iterations') # + id="fyLT0ohCafS-" broadcast = lambda x: jnp.broadcast_to(x, (NUM_DEV,) + x.shape) for _ in range(TRAINING_STEPS): beta_vae_current_step += 1 beta = beta_schedule(beta_vae_current_step) # Since beta is varying during training, it cannot be statically compiled into # udpate function and needs to be broadcast prior to being passed to the # beta_vae_update. params, prng_key, opt_state, stats = beta_vae_update( params, prng_key, opt_state, broadcast(beta), format_data(next(dataset))) elbo = stats[1]['elbo'].mean() kl = stats[1]['kl'].mean() log_p = stats[1]['log_p'].mean() if (beta_vae_current_step + 1) % PLOT_EVERY == 0: beta_vae_plot.update({ 'negative ELBO': -elbo, 'kl': kl, 'log_p': log_p, 'beta': beta }, current_step=beta_vae_current_step) if beta_vae_current_step % PLOT_REFRESH_EVERY == 0: beta_vae_plot.send() beta_vae_losses.append(elbo) beta_vae_kls.append(kl) beta_vae_logps.append(log_p) # + [markdown] id="bnGnxMkX6m9i" # ## Visualize reconstructions and samples # + id="4lDFDAS55-Hw" targets, reconstructions, samples = reconstruct_and_sample( params, prng_key, model, next(get_dataset(batch_size=VIS_BATCH_SIZE, num_dev=1, hard=USE_HARD_DATA, data_split='test'))) sz = 6 _ = plt.figure(figsize=((3*sz, 1*sz))) plt.subplot(131) imshow(gallery(targets), 'Targets') plt.subplot(132) imshow(gallery(reconstructions), 'Reconstructions') plt.subplot(133) imshow(gallery(samples), 'Conditional samples'); # + [markdown] id="rf7C01sk6u0c" # ## Explore the latent space # # + id="YFNXWrUXAuxQ" data = get_dummy_data(hard=USE_HARD_DATA) num_steps = 7 * 7 samples_from_interpolations = get_latent_interpolations( model, get_slice(params), jax.random.PRNGKey(1), num_steps, data.context) sz = 6 _ = plt.figure(figsize=((2*sz, sz))) plt.subplot(121) imshow(data.target[0,...], 'Label example') plt.subplot(122) imshow(gallery(samples_from_interpolations), 'Latent space interpolation') # + [markdown] id="dkCRFJ1sXlzp" # # Constrained optimization # # Constrained optimization can be used to dynamically tune the relative weight of the likelihood and KL terms during optimization. # This removes the need to manually tune $\beta$, or create an optimization schedule, which can be problem specific. # # The objective now becomes: # # \begin{equation} # \text{minimize } \mathbb{E}_{p^*(x)} KL(q(z|x)||p(z)) \text{ such that } \mathbb{E}_{p^*(x)} \mathbb{E}_{q(z|x) \log p_\theta(x|z)} > \kappa # \end{equation} # # This can be solved using Lagrange multipliers. The objective then becomes: # # \begin{equation} # \text{minimize } \mathbb{E}_{p^*(x)} KL(q(z|x)||p(z)) + \lambda (\mathbb{E}_{p^*(x)} \mathbb{E}_{q(z|x)} (\kappa - \log p_\theta(x|z))) # \end{equation} # # # The difference compared to the KL annealing is that: # # * $\lambda$ is a learned parameter - it will be learned using stochastic gradient descent, like the network parameters. The difference is that the lagrangian has to solve a maximization problem. You can see this intuitively: the graadient with respect to $\lambda$ in the objective above is $\mathbb{E}_{p^*(x)} \mathbb{E}_{q(z|x)} (\alpha - \log p_\theta(x|z))$. If $ \mathbb{E}_{p^*(x)} \mathbb{E}_{q(z|x)} (\alpha - \log p_\theta(x|z))> 0$, the constraint is not being satisfied, so the value of the lagrangian needs to increase. This will be done by doing gradient ascent, instead of gradient descent. Note that for $\lambda$ to be a valid lagranian in a minimization problem, it has to be positive. # * The practicioner has to specify the hyperparameter $\kappa$, which determines the reoncstruction quality of the model. # * the coefficient is in front of the likelihood term, not the KL term. This is mainly for convenience, as it is easier to specify the hyperparameter $\kappa$ for the likelihood (reconstruction loss). # # For more assumptions made by this method, see the Karush–Kuhn–Tucker conditions. # # For more information, see: # * http://bayesiandeeplearning.org/2018/papers/33.pdf # # + [markdown] id="E0aSoWHFV-GI" # ## Lagrange multipliers for constrained optimization # # This is a reimplementation in JAX of the [constrained optimization tools](https://github.com/deepmind/sonnet/blob/master/sonnet/python/modules/optimization_constraints.py) found in Sonnet v1. # # Note the peculiar implementation of the `clip` function, which is used to limit the valid range of the multipliers; this is used for example to force their values to be non-negative, or to limit their maximum values to control the interaction of the loss components during training. # # In this implementation the gradients flowing through the clipping function are not set to 0 when above and below the thresholds, if the gradients would make the inputs move towards the valid range. This is particularly useful when setting a maximum valid value, since it allows for the multipliers to become smaller once the constraints are (eventually) satisfied. # + id="Kj186VkXV1Fh" @functools.partial(jax.custom_vjp, nondiff_argnums=(1, 2, 3)) def clip(x, min_val, max_val, maximize=True): del maximize return jax.tree_map(lambda e: jnp.clip(e, min_val, max_val), x) def clip_fwd(x, min_val, max_val, maximize): return clip(x, min_val, max_val, maximize), x def clip_bwd(min_val, max_val, maximize, x, co_tangents): zeros = jax.tree_map(jnp.zeros_like, co_tangents) if min_val is not None: get_mask = lambda x, v, t: (x < v) & (t < 0 if maximize else t > 0) mask = jax.tree_multimap(get_mask, x, min_val, co_tangents) co_tangents = jax.tree_multimap(jnp.where, mask, zeros, co_tangents) if max_val is not None: get_mask = lambda x, v, t: (x > v) & (t > 0 if maximize else t < 0) mask = jax.tree_multimap(get_mask, x, max_val, co_tangents) co_tangents = jax.tree_multimap(jnp.where, mask, zeros, co_tangents) return co_tangents, clip.defvjp(clip_fwd, clip_bwd) class LagrangeMultiplier(hk.Module): """Lagrange Multiplier module for constrained optimization.""" def __init__(self, shape=(), initializer=1.0, maximize=True, valid_range=None, name='lagrange_multiplier'): super().__init__(name=name) self._shape = shape if callable(initializer): self._initializer = initializer else: self._initializer = lambda *args: jnp.ones(*args) * initializer self._maximize = maximize self._valid_range = valid_range if valid_range is not None else (0.0, None) assert self._valid_range[0] >= 0 def __call__(self): lag_mul = hk.get_parameter('w', self._shape, init=self._initializer) lag_mul = clip(lag_mul, *self._valid_range, maximize=self._maximize) return lag_mul # + [markdown] id="_l3Ni4tW7IZ3" # ## Training a VAE using GECO # + id="_rS27R4sXTRE" def get_geco_loss(prng, model, kappa, valid_range, init_lambda): def constraint_term(x, target): lag_mul = LagrangeMultiplier( shape=x.shape, valid_range=valid_range, initializer=init_lambda)() return jnp.sum(lag_mul * (x - target)), lag_mul constraint_term = _transform(constraint_term) lagmul_params = constraint_term.init(prng, jnp.ones(()), jnp.ones(())) def geco_loss(params, prng, data): """Loss using constrained optimization as in GECO.""" # Compute the KL term (make sure to average across the batch!) # ADD CODE BELOW # ----------------------- kl = ... # ----------------------- # Reconstruct the inputs and compute the reconstruction error (e.g. MSE) # ADD CODE BELOW # ----------------------- reconstruction = ... reconstruction_err = ... # ----------------------- # If you didn't use MSE before, you need to adjust the kappa term in the # constraint definition. constraint_satisfaction, lag_mul = constraint_term.apply( params, reconstruction_err, np.prod(data.target.shape[1:]) * kappa**2) loss = constraint_satisfaction + kl metrics = { 'loss': loss, 'mse': jnp.mean((reconstruction - data.target)**2), 'kl': kl, 'lag_mul': lag_mul} return loss, metrics return geco_loss, lagmul_params # + id="4v8QtWUX10aK" prng_key = jax.random.PRNGKey(0) kappa = 0.18 valid_range = (0, 4.0) init_lambda = 2.0 params = model.init_params(prng_key, get_dummy_data(hard=USE_HARD_DATA)) geco_loss_fn, lagmul_params = get_geco_loss( prng_key, model, kappa, valid_range, init_lambda=init_lambda) # + [markdown] id="OZUngLFyxIst" # ## Using multiple optimizers jointly # # We will now see how we can optimize joinlty the model parameters `params` and the Lagrange multipliers `lagmul_params`. # # We want to update the Lagrange multipliers via stochastic gradient *ascent*; for example we could consider using the logic in `tx.sgd` with a *negative* learning rate. The model params will be instead optimized using ADAM, just like in the previous cells. # # In the next cell you will find a handy wrapper to capture multiple optimizers into a single optax object. # # What is left to do is: # # 1. Merge all the parameters into a single tree; you can do so using the `hk.data_structures.merge` utility in Haiku: # # ``` # params = hk.data_structures.merge(params, lagmul_params) # ``` # 2. Specify how to filter the resulting `params` structure to select which variables should be mapped to which optimizer. Tip: you can filter the Lagrange multipliers with: # ``` # multiplier_filter = lambda m, n, p: 'lagrange' in m # ``` # and the model variables with: # ``` # model_params_filter = lambda m, n, p: 'lagrange' not in m # ``` # + id="KhqqfnHRWRcA" def multi_opt(**filter_optimizer_map): """Wraps multiple optimizers within an object with the optax interface. Args: **filter_optimizer_map: kwargs used to map optimizer names to (predicate, optimizer) tuples, where predicate is a function which will be passed to haiku.data_structure.filter in order to select which variables are to be updated by the corresponding optimizer. Returns: An optax.InitUpdate tuple. """ def filter_(predicate, params): if params is None: return None return hk.data_structures.filter(predicate, params) merge_ = hk.data_structures.merge def _init(params): opt_state = dict() for opt_name, (predicate, opt) in filter_optimizer_map.items(): opt_state[opt_name] = opt.init(filter_(predicate, params)) return opt_state def _update(updates, state, params=None): new_updates = {} new_state = dict() for opt_name, (predicate, opt) in filter_optimizer_map.items(): update, new_state[opt_name] = opt.update( filter_(predicate, updates), state[opt_name], filter_(predicate, params)) new_updates = merge_(new_updates, update) return new_updates, new_state return tx.InitUpdate(_init, _update) # + id="MHQGFLJnxEnh" # Merge them using hk.data_structures.merge # function. # ADD CODE BELOW # ----------------------- params = ... # ----------------------- # Optimize the Lagrange multipliers via stochastic gradient ascent. # Optimize the model params will be optimized using ADAM. # ADD CODE BELOW # ----------------------- geco_optimizer = ... opt_state = ... # ----------------------- params, prng_key, opt_state = setup_for_distributed_training( params, prng_key, opt_state, num_dev=NUM_DEV) dataset = get_dataset( batch_size=BATCH_SIZE, num_dev=NUM_DEV, hard=USE_HARD_DATA) def geco_update(params, prng_key, opt_state, data): loss_key, prng_key = jax.random.split(prng_key) geco_loss, grads = jax.value_and_grad( geco_loss_fn, has_aux=True)(params, loss_key, data) grads = jax.lax.pmean(grads, axis_name='i') raw_updates, opt_state = geco_optimizer.update(grads, opt_state) params = tx.apply_updates(params, raw_updates) return params, prng_key, opt_state, geco_loss geco_update = jax.pmap(geco_update, axis_name='i', devices=jax.devices()) geco_current_step = 0 mses = [] kls = [] lag_muls = [] geco_groups = { 'mse': ['mse'], 'kl': ['kl'], 'lag_mul': ['lag_mul'], } geco_plot = PlotLosses( groups=geco_groups, outputs=[MatplotlibPlot(max_cols=4, after_subplot=custom_after_subplot)], step_names='Iterations') # + id="pjz1119u4mIM" for _ in range(TRAINING_STEPS): geco_current_step += 1 params, prng_key, opt_state, stats = geco_update( params, prng_key, opt_state, format_data(next(dataset))) mse = stats[1]['mse'].mean() kl = stats[1]['kl'].mean() lag_mul = stats[1]['lag_mul'].mean() geco_plot.update({ 'mse': mse, 'kl': kl, 'lag_mul': lag_mul }) if geco_current_step % PLOT_REFRESH_EVERY == 0: geco_plot.send() mses.append(mse) kls.append(kl) lag_muls.append(lag_mul) # + [markdown] id="8p1MfoWRqn6z" # ## Visualize reconstructions and samples # + id="wVqlmUSfqE1C" targets, reconstructions, samples = reconstruct_and_sample( params, prng_key, model, next(get_dataset(batch_size=VIS_BATCH_SIZE, num_dev=1, hard=USE_HARD_DATA, data_split='test'))) sz = 6 _ = plt.figure(figsize=((3*sz, 1*sz))) plt.subplot(131) imshow(gallery(targets), 'Targets') plt.subplot(132) imshow(gallery(reconstructions), 'Reconstructions') plt.subplot(133) imshow(gallery(samples), 'Conditional samples'); # + [markdown] id="HJ1fj8fYqymD" # ## Explore the latent space # + id="yRg8i4WgDjcM" dummy_data = get_dummy_data(hard=USE_HARD_DATA) num_steps = 7 * 7 samples_from_interpolations = get_latent_interpolations( model, get_slice(params), jax.random.PRNGKey(0), num_steps, dummy_data.context) sz = 6 _ = plt.figure(figsize=((2*sz, sz))) plt.subplot(121) imshow(dummy_data.target[0,...], 'Label example') plt.subplot(122) imshow(gallery(samples_from_interpolations), 'Latent space interpolation')
3_generative/VAE_Tutorial_Start.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: TF 2.1 (GPU)/Py3.7.5 # language: python # name: tf21g # --- # # Imports # + import numpy as np import pandas as pd import glob import re import sys from bs4 import BeautifulSoup from snorkel.labeling.lf import labeling_function from snorkel.labeling import LabelingFunction from snorkel.labeling.model import LabelModel from snorkel.labeling import PandasLFApplier from snorkel.labeling import LFAnalysis from snorkel.labeling.model import MajorityLabelVoter # - # # Load Data # + def load_reviews(path, columns=["filename", 'review']): assert len(columns) == 2 l = list() for filename in glob.glob(path): # print(filename) with open(filename, 'r') as f: review = f.read() l.append((filename, review)) return pd.DataFrame(l, columns=columns) unsup_df = load_reviews("./aclImdb/train/unsup/*.txt") def load_labelled_data(path, neg='/neg/', pos='/pos/', shuffle=True): neg_df = load_reviews(path + neg + "*.txt") pos_df = load_reviews(path + pos + "*.txt") neg_df['sentiment'] = 0 pos_df['sentiment'] = 1 df = pd.concat([neg_df, pos_df], axis=0) if shuffle: df = df.sample(frac=1, random_state=42) return df train_df = load_labelled_data("./aclImdb/train/") test_df = load_labelled_data("./aclImdb/test/") # - # # Labeling Functions # Constants POSITIVE = 1 NEGATIVE = 0 ABSTAIN = -1 # ## Negative Sentiment Labeling Functions # Sample some negative reviews and write some functions train_df[train_df.sentiment == 0].review[:10].tolist() # + @labeling_function() def atrocious(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "atrocious" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def crap(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "crap" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def garbage(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "garbage" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def terrible(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "terrible" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def piece_of(x): if not isinstance(x.review, str): return ABSTAIN ex1 = {"piece", "of", "junk"} st_rvw = set(x.review.lower().split()) if st_rvw.issuperset(ex1): return NEGATIVE return ABSTAIN @labeling_function() def woefully_miscast(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "woeful" ex2 = "miscast" if ex1 in x.review.lower() or ex2 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def bad_acting(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "bad" ex2 = "acting" if ex1 in x.review.lower() and ex2 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def cheesy_dull(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "cheesy" ex2 = "dull" if ex1 in x.review.lower() or ex2 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def disappoint(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "disappoint" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def unsatisfied(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "unsatisf" # unsatisfactory, unsatisfied if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def ridiculous(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "ridiculous" if ex1 in x.review.lower(): return NEGATIVE return ABSTAIN @labeling_function() def bad(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "bad" if x.review.lower().count(ex1) >= 3: return NEGATIVE return ABSTAIN neg_lfs = [atrocious, terrible, piece_of, woefully_miscast, bad_acting, cheesy_dull, disappoint, crap, garbage, unsatisfied, ridiculous, bad] # - # ## Positive Sentiment Labeling Functions # Sample some positive reviews and write some functions train_df[train_df.sentiment == 1].review[:10].tolist() # + @labeling_function() def classic(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "a classic" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def must_watch(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "must watch" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def oscar(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "oscar nominated" if ex1 in x.review.lower() : return POSITIVE return ABSTAIN @labeling_function() def love(x): if not isinstance(x.review, str): return ABSTAIN st_rvw = set(x.review.lower().split()) ex1 = {"love", "the", "movie"} if st_rvw.issuperset(ex1) : return POSITIVE return ABSTAIN @labeling_function() def great_entertainment(x): if not isinstance(x.review, str): return ABSTAIN st_rvw = set(x.review.lower().split()) ex1 = {"great", "entertainment"} if st_rvw.issuperset(ex1) : return POSITIVE return ABSTAIN @labeling_function() def very_entertaining(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "very entertaining" if ex1 in x.review.lower() : return POSITIVE return ABSTAIN @labeling_function() def amazing(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "amazing" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def brilliant(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "brillant" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def fantastic(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "fantastic" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def awesome(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "awesome" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def great_acting(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "(great|awesome|amazing|fantastic|excellent) act" #ex1 = "(awesome|amazing|fantastic|excellent) act" if re.search(ex1, x.review.lower()): return POSITIVE return ABSTAIN @labeling_function() def great(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "great" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN @labeling_function() def great_direction(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "(great|awesome|amazing|fantastic|excellent) direction" if re.search(ex1, x.review.lower()): return POSITIVE return ABSTAIN @labeling_function() def great_story(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "(great|awesome|amazing|fantastic|excellent|dramatic) (script|story)" if re.search(ex1, x.review.lower()): return POSITIVE return ABSTAIN @labeling_function() def favourite(x): if not isinstance(x.review, str): return ABSTAIN ex1 = "my favourite" if ex1 in x.review.lower(): return POSITIVE return ABSTAIN # This function is updated later through iterative work # @labeling_function() # def superlatives(x): # if not isinstance(x.review, str): # return ABSTAIN # ex1 = ["best", "super", "great","awesome","amaz", "fantastic", # "excellent", "favorite"] # rv = x.review.lower() # counts = [rv.count(x) for x in ex1] # if sum(counts) >= 3: # return POSITIVE # return ABSTAIN pos_lfs = [classic, must_watch, oscar, love, great_entertainment, very_entertaining, amazing, brilliant, fantastic, awesome, great_acting, great_direction, great_story, favourite, great ] # - # ## Test labels on small subset of data # + # set of labeling functions lfs = neg_lfs + pos_lfs # lets take a sample of 1000 records from training set lf_train = train_df.sample(n=1000, random_state=42) # Apply the LFs to the unlabeled training data applier = PandasLFApplier(lfs) L_train = applier.apply(lf_train) # - # Train the label model and compute the training labels label_model = LabelModel(cardinality=2, verbose=True) label_model.fit(L_train, n_epochs=500, log_freq=50, seed=123) lf_train["snorkel"] = label_model.predict(L=L_train, tie_break_policy="abstain") pred_lfs = lf_train[lf_train.snorkel > -1] pred_lfs.describe() pred_mistake = pred_lfs[pred_lfs.sentiment != pred_lfs.snorkel] pred_mistake.describe() # ## Labeling functions inspired by Naive-Bayes Model # + # Utilities for defining keywords based functions def keyword_lookup(x, keywords, label): if any(word in x.review.lower() for word in keywords): return label return ABSTAIN def make_keyword_lf(keywords, label): return LabelingFunction( name=f"keyword_{keywords[0]}", f=keyword_lookup, resources=dict(keywords=keywords, label=label), ) # + # Some negative high prob words - arbitrary cutoff of 4.5x ''' contains(unfunny) = True 0 : 1 = 14.1 : 1.0 contains(waste) = True 0 : 1 = 12.7 : 1.0 contains(pointless) = True 0 : 1 = 10.4 : 1.0 contains(redeeming) = True 0 : 1 = 10.1 : 1.0 contains(laughable) = True 0 : 1 = 9.3 : 1.0 contains(worst) = True 0 : 1 = 9.0 : 1.0 contains(awful) = True 0 : 1 = 8.4 : 1.0 contains(poorly) = True 0 : 1 = 8.2 : 1.0 contains(sucks) = True 0 : 1 = 7.0 : 1.0 contains(lame) = True 0 : 1 = 6.9 : 1.0 contains(pathetic) = True 0 : 1 = 6.4 : 1.0 contains(wasted) = True 0 : 1 = 6.0 : 1.0 contains(crap) = True 0 : 1 = 5.9 : 1.0 contains(dreadful) = True 0 : 1 = 5.7 : 1.0 contains(mess) = True 0 : 1 = 5.6 : 1.0 contains(horrible) = True 0 : 1 = 5.5 : 1.0 contains(garbage) = True 0 : 1 = 5.3 : 1.0 contains(badly) = True 0 : 1 = 5.3 : 1.0 contains(wooden) = True 0 : 1 = 5.2 : 1.0 contains(terrible) = True 0 : 1 = 5.1 : 1.0 contains(worse) = True 0 : 1 = 5.0 : 1.0 contains(stupid) = True 0 : 1 = 4.7 : 1.0 contains(avoid) = True 0 : 1 = 4.7 : 1.0 contains(dull) = True 0 : 1 = 4.5 : 1.0 ''' waste_kw = make_keyword_lf(keywords=["waste"], label=NEGATIVE) pointless_kw = make_keyword_lf(keywords=["pointless"], label=NEGATIVE) redeeming_kw = make_keyword_lf(keywords=["redeeming"], label=NEGATIVE) neg_words = ["laughable", "worst", "awful", "poorly", "sucks", "lame", "pathetic", "dreadful", "mess", "horrible", "badly", "wooden", "terrible", "worse", "stupid", "avoid", "dull"] neg_nb_kw = make_keyword_lf(keywords=neg_words, label=NEGATIVE) print(neg_nb_kw) # update the counting function @labeling_function() def negatives(x): if not isinstance(x.review, str): return ABSTAIN ex1 = ["bad" , "terrible", "poor", "disappoint", "unsatisf"] neg_words = ["waste", "pointless", "redeeming","laughable", "worst", "awful", "poorly", "sucks", "lame", "pathetic", "dreadful", "mess", "horrible", "badly", "wooden", "terrible", "worse", "stupid", "avoid", "dull"] ex1 += neg_words rv = x.review.lower() counts = [rv.count(x) for x in ex1] if sum(counts) >= 2: return NEGATIVE return ABSTAIN neg_lfs += [waste_kw, pointless_kw, redeeming_kw, neg_nb_kw, negatives] # + # Some positive high prob words - arbitrary cutoff of 4.5x ''' contains(wonderfully) = True 1 : 0 = 7.6 : 1.0 contains(delightful) = True 1 : 0 = 6.0 : 1.0 contains(beautifully) = True 1 : 0 = 5.8 : 1.0 contains(superb) = True 1 : 0 = 5.4 : 1.0 contains(touching) = True 1 : 0 = 5.1 : 1.0 contains(brilliantly) = True 1 : 0 = 4.7 : 1.0 contains(friendship) = True 1 : 0 = 4.6 : 1.0 contains(finest) = True 1 : 0 = 4.5 : 1.0 contains(terrific) = True 1 : 0 = 4.5 : 1.0 contains(gem) = True 1 : 0 = 4.5 : 1.0 contains(magnificent) = True 1 : 0 = 4.5 : 1.0 ''' wonderfully_kw = make_keyword_lf(keywords=["wonderfully"], label=POSITIVE) delightful_kw = make_keyword_lf(keywords=["delightful"], label=POSITIVE) superb_kw = make_keyword_lf(keywords=["superb"], label=POSITIVE) pos_words = ["beautifully", "touching", "brilliantly", "friendship", "finest", "terrific", "magnificent"] pos_nb_kw = make_keyword_lf(keywords=pos_words, label=POSITIVE) print(pos_nb_kw) # update with more superlatives @labeling_function() def superlatives(x): if not isinstance(x.review, str): return ABSTAIN ex1 = ["best", "super", "great","awesome","amaz", "fantastic", "excellent", "favorite"] pos_words = ["beautifully", "touching", "brilliantly", "friendship", "finest", "terrific", "magnificent", "wonderfully", "delightful"] ex1 += pos_words rv = x.review.lower() counts = [rv.count(x) for x in ex1] if sum(counts) >= 3: return POSITIVE return ABSTAIN # + ''' contains(outstanding) = True 1 : 0 = 4.3 : 1.0 contains(wonderful) = True 1 : 0 = 4.2 : 1.0 contains(excellent) = True 1 : 0 = 4.1 : 1.0 contains(fantastic) = True 1 : 0 = 4.1 : 1.0 contains(freedom) = True 1 : 0 = 4.0 : 1.0 * contains(sinatra) = True 1 : 0 = 3.9 : 1.0 contains(noir) = True 1 : 0 = 3.8 : 1.0 contains(stunning) = True 1 : 0 = 3.6 : 1.0 contains(amazing) = True 1 : 0 = 3.6 : 1.0 contains(remarkable) = True 1 : 0 = 3.5 : 1.0 contains(perfect) = True 1 : 0 = 3.4 : 1.0 * contains(stewart) = True 1 : 0 = 3.4 : 1.0 contains(powerful) = True 1 : 0 = 3.4 : 1.0 contains(recommended) = True 1 : 0 = 3.4 : 1.0 * contains(barbara) = True 1 : 0 = 3.3 : 1.0 contains(favorite) = True 1 : 0 = 3.3 : 1.0 contains(emotions) = True 1 : 0 = 3.2 : 1.0 contains(rare) = True 1 : 0 = 3.2 : 1.0 contains(subtle) = True 1 : 0 = 3.2 : 1.0 contains(journey) = True 1 : 0 = 3.2 : 1.0 contains(perfectly) = True 1 : 0 = 3.2 : 1.0 * contains(marie) = True 1 : 0 = 3.2 : 1.0 ''' pos_words2 = ["remarkable", "stunning", "noir", "freedom", "fantastic", "excellent", "wonderful","outstanding", "perfect", "powerful", "recommended", "emotions", "rare", "subtle", "journey", "perfectly"] pos_nb_kw2 = make_keyword_lf(keywords=pos_words2, label=POSITIVE) # - pos_lfs += [wonderfully_kw, delightful_kw, superb_kw, pos_nb_kw, superlatives, pos_nb_kw2] # # Test Labeling Functions on Training Data # + # set of labeling functions lfs = neg_lfs + pos_lfs # Apply the LFs to the unlabeled training data applier = PandasLFApplier(lfs) # - print(lfs) # train on entire training set L_train_full = applier.apply(train_df) label_model = LabelModel(cardinality=2, verbose=True) label_model.fit(L_train_full, n_epochs=500, optimizer="adam", log_freq=50, seed=42) # + train_df["snorkel"] = label_model.predict(L=L_train_full, tie_break_policy="abstain") metrics = label_model.score(L=L_train_full, Y=train_df.sentiment, tie_break_policy="abstain", metrics=["accuracy", "coverage", "precision", "recall", "f1"]) label_model_acc = metrics["accuracy"] print(f"{'Label Model Accuracy:':<25} {label_model_acc * 100:.1f}%") print("All Metrics: ", metrics) print(LFAnalysis(L=L_train_full, lfs=lfs).lf_summary()) # - train_df["snorkel"].hist() # + # Grid Search from itertools import product lrs = [1e-1, 1e-2, 1e-3] l2s = [0, 1e-1, 1e-2] n_epochs = [100, 200, 500] optimizer = ["sgd", "adam"] thresh = [0.8, 0.9] lma_best = 0 params_best = [] for params in product(lrs, l2s, n_epochs, optimizer, thresh): # do the initial pass to access the accuracies label_model.fit(L_train_full, n_epochs=params[2], log_freq=50, seed=123, optimizer=params[3], lr=params[0], l2=params[1]) # accuracies weights = label_model.get_weights() # LFs above our threshold vals = weights > params[4] # the LM requires at least 3 LFs to train if sum(vals) >= 3: L_filtered = L_train_full[:, vals] label_model.fit(L_filtered, n_epochs=params[2], log_freq=50, seed=123, optimizer=params[3], lr=params[0], l2=params[1]) label_model_acc = label_model.score(L=L_filtered, Y=train_df.sentiment, tie_break_policy="abstain")["accuracy"] if label_model_acc > lma_best: lma_best = label_model_acc params_best = params print("best = ", lma_best, " params ", params_best) # - L_filtered.shape train_df["snorkel"] = label_model.predict(L=L_filtered, tie_break_policy="abstain") train_df.describe() # + from sklearn.model_selection import train_test_split # Randomly split training into 2k / 23k sets train_2k, train_23k = train_test_split(train_df, test_size=23000, random_state=42, stratify=train_df.sentiment) # - train_2k.sentiment.hist() train_2k.snorkel.hist() train_2k.to_pickle("train_2k.df") train_23k.snorkel.hist() train_23k.sentiment.hist() lbl_train = train_23k[train_23k.snorkel > -1] print(lbl_train.info()) lbl_train.hist() lbl_train = lbl_train.drop(columns=["sentiment"]) p_sup = lbl_train.rename(columns={"snorkel": "sentiment"}) p_sup.hist() p_sup.to_pickle("snorkel_train_labeled.df") # # Label Unsupervised # + # Now apply this to all the unsupervised reviews # Apply the LFs to the unlabeled training data applier = PandasLFApplier(lfs) # now lets apply on the unsuperisved dataset L_train_unsup = applier.apply(unsup_df) label_model = LabelModel(cardinality=2, verbose=True) label_model.fit(L_train_unsup[:, vals], n_epochs=params_best[2], optimizer=params_best[3], lr=params_best[0], l2=params_best[1], log_freq=100, seed=42) unsup_df["snorkel"] = label_model.predict(L=L_train_unsup[:, vals], tie_break_policy="abstain") # rename snorkel to sentiment for concatentation to the training dataset pred_unsup_lfs = unsup_df[unsup_df.snorkel > -1] p2 = pred_unsup_lfs.rename(columns={"snorkel": "sentiment"}) print(p2.info()) p2.to_pickle("snorkel-unsup-nbs.df") # - snorkel_labels = pd.concat((train_df.sentiment, p2.sentiment)) snorkel_labels.hist() unsup_df.snorkel.hist() p2.sentiment.hist() # # Increase Positive Label Coverage # + ''' contains(brilliant) = True 1 : 0 = 3.1 : 1.0 contains(favourite) = True 1 : 0 = 3.0 : 1.0 contains(highly) = True 1 : 0 = 3.0 : 1.0 contains(unexpected) = True 1 : 0 = 3.0 : 1.0 contains(loved) = True 1 : 0 = 3.0 : 1.0 contains(helps) = True 1 : 0 = 2.9 : 1.0 contains(provides) = True 1 : 0 = 2.9 : 1.0 contains(unique) = True 1 : 0 = 2.9 : 1.0 contains(deeply) = True 1 : 0 = 2.9 : 1.0 contains(tragic) = True 1 : 0 = 2.9 : 1.0 * contains(joan) = True 1 : 0 = 2.8 : 1.0 contains(incredible) = True 1 : 0 = 2.8 : 1.0 contains(intense) = True 1 : 0 = 2.8 : 1.0 contains(fascinating) = True 1 : 0 = 2.8 : 1.0 contains(unusual) = True 1 : 0 = 2.8 : 1.0 contains(today) = True 1 : 0 = 2.8 : 1.0 contains(creates) = True 1 : 0 = 2.8 : 1.0 contains(awesome) = True 1 : 0 = 2.8 : 1.0 contains(spectacular) = True 1 : 0 = 2.7 : 1.0 ''' pos_words3 = ["brilliant", "favourite", "highly", "unexpected", "loved", "helps", "provides","unique", "deeply", "tragic", "incredible", "intense", "fascinating", "unusual", "today", "creates", "awesome", "spectacular"] pos_nb_kw3 = make_keyword_lf(keywords=pos_words3, label=POSITIVE) # update with more superlatives @labeling_function() def superlatives3(x): if not isinstance(x.review, str): return ABSTAIN pos_words = ["brilliant", "favourite", "highly", "unexpected", "loved", "helps", "provides","unique", "deeply", "tragic", "incredible", "intense", "fascinating", "unusual", "today", "creates", "awesome", "spectacular"] rv = x.review.lower() counts = [rv.count(x) for x in pos_words] if sum(counts) >= 2: return POSITIVE return ABSTAIN # + # set of labeling functions lfs2 = lfs + [pos_nb_kw3, superlatives3] # Apply the LFs to the unlabeled training data applier2 = PandasLFApplier(lfs2) # - # train on entire training set L_train_full2 = applier2.apply(train_df) label_model2 = LabelModel(cardinality=2, verbose=True) label_model2.fit(L_train_full2, n_epochs=500, optimizer="adam", log_freq=50, seed=42) # + train_df["snorkel2"] = label_model2.predict(L=L_train_full2, tie_break_policy="abstain") metrics = label_model2.score(L=L_train_full2, Y=train_df.sentiment, tie_break_policy="abstain", metrics=["accuracy", "coverage", "precision", "recall", "f1"]) label_model_acc = metrics["accuracy"] print(f"{'Label Model Accuracy:':<25} {label_model_acc * 100:.1f}%") print("All Metrics: ", metrics) print(LFAnalysis(L=L_train_full2, lfs=lfs2).lf_summary()) # - train_df.snorkel2.hist() # + # Grid Search from itertools import product lrs = [1e-1, 1e-2, 1e-3] l2s = [0, 1e-1, 1e-2] n_epochs = [100, 200, 500] optimizer = ["sgd", "adam"] thresh = [0.8, 0.9] lma_best = 0 params_best = [] for params in product(lrs, l2s, n_epochs, optimizer, thresh): # do the initial pass to access the accuracies label_model2.fit(L_train_full2, n_epochs=params[2], log_freq=50, seed=123, optimizer=params[3], lr=params[0], l2=params[1]) # accuracies weights = label_model2.get_weights() # LFs above our threshold vals = weights > params[4] # the LM requires at least 3 LFs to train if sum(vals) >= 3: L_filtered = L_train_full2[:, vals] label_model2.fit(L_filtered, n_epochs=params[2], log_freq=50, seed=123, optimizer=params[3], lr=params[0], l2=params[1]) label_model_acc = label_model2.score(L=L_filtered, Y=train_df.sentiment, tie_break_policy="abstain")["accuracy"] if label_model_acc > lma_best: lma_best = label_model_acc params_best = params print("best = ", lma_best, " params ", params_best) # - train_df['snorkel3'] = label_model2.predict(L=L_filtered, tie_break_policy="abstain") train_df.snorkel3.hist() # + # Now apply this to all the unsupervised reviews # Apply the LFs to the unlabeled training data applier2 = PandasLFApplier(lfs2) # now lets apply on the unsuperisved dataset L_train_unsup2 = applier2.apply(unsup_df) label_model_unsup = LabelModel(cardinality=2, verbose=True) label_model_unsup.fit(L_train_unsup2[:, vals], n_epochs=params_best[2], optimizer=params_best[3], lr=params_best[0], l2=params_best[1], log_freq=100, seed=42) unsup_df["snorkel2"] = label_model_unsup.predict(L=L_train_unsup2[:, vals], tie_break_policy="abstain") # rename snorkel to sentiment for concatentation to the training dataset pred_unsup_lfs2 = unsup_df[unsup_df.snorkel2 > -1] # - pred_unsup_lfs2.info() pred_unsup_lfs2.hist() unsup_df.snorkel2.hist() p3 = pred_unsup_lfs2.rename(columns={"snorkel2": "sentiment"}) print(p3.info()) p3.to_pickle("snorkel-unsup-nbs-v2.df") p3.info() pred_unsup_lfs2
chapter-8-weak-supervision-snorkel/snorkel-labeling.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # <img src="http://cfs22.simplicdn.net/ice9/new_logo.svgz "/> # # # Assignment 01: Evaluate the FAA Dataset # # *The comments/sections provided are your cues to perform the assignment. You don't need to limit yourself to the number of rows/cells provided. You can add additional rows in each section to add more lines of code.* # # *If at any point in time you need help on solving this assignment, view our demo video to understand the different steps of the code.* # # **Happy coding!** # # * * * # #### 1: VIew and import the dataset #Import necessary libraries import pandas as pd #Import the FAA (Federal Aviation Authority) dataset df_faa_dataset = pd.read_csv("D:/COURSES/Artificial Intellegence Engineer/Data Analytics With Python/Analyse the Federal Aviation Authority Dataset using Pandas/SUBMISSION/SOURCE CODE/faa_ai_prelim.csv") # #### 2: View and understand the dataset #View the dataset shape df_faa_dataset.shape #View the first five observations df_faa_dataset.head() #View all the columns present in the dataset df_faa_dataset.columns # #### 3: Extract the following attributes from the dataset: # 1. Aircraft make name # 2. State name # 3. Aircraft model name # 4. Text information # 5. Flight phase # 6. Event description type # 7. Fatal flag #Create a new dataframe with only the required columns df_analyze_dataset = df_faa_dataset[['LOC_STATE_NAME', 'RMK_TEXT', 'EVENT_TYPE_DESC', 'ACFT_MAKE_NAME', 'ACFT_MODEL_NAME', 'FLT_PHASE', 'FATAL_FLAG']] #View the type of the object type(df_analyze_dataset) #Check if the dataframe contains all the required attributes df_analyze_dataset.head() # #### 4. Clean the dataset and replace the fatal flag NaN with “No” #Replace all Fatal Flag missing values with the required output df_analyze_dataset['FATAL_FLAG'].fillna(value="No",inplace=True) #Verify if the missing values are replaced df_analyze_dataset.head() #Check the number of observations df_analyze_dataset.shape # #### 5. Remove all the observations where aircraft names are not available #Drop the unwanted values/observations from the dataset df_final_dataset = df_analyze_dataset.dropna(subset=['ACFT_MAKE_NAME']) # #### 6. Find the aircraft types and their occurrences in the dataset #Check the number of observations now to compare it with the original dataset and see how many values have been dropped df_final_dataset.shape #Group the dataset by aircraft name aircraftType = df_final_dataset.groupby('ACFT_MAKE_NAME') #View the number of times each aircraft type appears in the dataset (Hint: use the size() method) aircraftType.size() # #### 7: Display the observations where fatal flag is “Yes” #Group the dataset by fatal flag fatalAccedents = df_final_dataset.groupby('FATAL_FLAG') #View the total number of fatal and non-fatal accidents fatalAccedents.size() # + tags=[] #Create a new dataframe to view only the fatal accidents (Fatal Flag values = Yes) accidents_with_fatality = fatalAccedents.get_group('Yes') # - accidents_with_fatality.head()
Analyse the Federal Aviation Authority Dataset using Pandas/SUBMISSION/SOURCE CODE/Pandas - Assignment 01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- df = pd.read_csv('CleanedDataNew.csv') import json import pandas as pd import numpy as np from collections import Counter import seaborn as sns from nltk.probability import FreqDist from nltk.corpus import stopwords from nltk import word_tokenize from nltk import pos_tag from string import punctuation,digits import re from keras.utils import to_categorical #from gensim.models import KeyedVectors from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical #from pandas_ml import ConfusionMatrix from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers import LSTM from keras.layers import Flatten from keras.layers import Bidirectional from keras.layers import Embedding # from keras.utils.np_utils import probas_to_classes from sklearn import preprocessing from keras.models import Sequential from sklearn.metrics import confusion_matrix,f1_score,precision_score,recall_score,accuracy_score from sklearn.model_selection import train_test_split # %matplotlib inline from keras.optimizers import Adam import matplotlib.pyplot as plt from matplotlib import rcParams from random import shuffle # figure size in inches rcParams['figure.figsize'] = 11.7,8.27 #import word2vecReader as godin_embedding #from gensim.models import KeyedVectors from sklearn.model_selection import StratifiedKFold #import skopt #from skopt import gp_minimize, forest_minimize #from skopt.space import Real, Categorical, Integer #from skopt.utils import use_named_args df.head() df_new= df.drop(columns=['url']) df_new.head() len(df_new['text']) def remove_punctuation(s): list_punctuation = list(punctuation) for i in list_punctuation: s = s.replace(i,' ') return s def clean_sentence(sentence): sentence = sentence.lower() #remove multiple repeat non num-aplha char !!!!!!!!!-->! sentence = re.sub(r'(\W)\1{2,}', r'\1', sentence) # print(sentence) #removes alpha char repeating more than twice aaaa->aa sentence = re.sub(r'(\w)\1{2,}', r'\1\1', sentence) # print(sentence) #removes links #sentence = re.sub(r'(?P<url>https?://[^\s]+)', r'', sentence) # print(sentence) # remove @usernames sentence = re.sub(r"\@(\w+)", "", sentence) # print(sentence) #removing stock names to see if it helps # sentence = re.sub(r"(?:\$|https?\://)\S+", "", sentence) #remove # from #tags sentence = sentence.replace('#','') sentence = sentence.replace("'s",'') sentence = sentence.replace("-",' ') # print(sentence) # split into tokens by white space tokens = sentence.split() # remove punctuation from each token tokens = [remove_punctuation(w) for w in tokens] # print(tokens) # remove remaining tokens that are not alphabetic # tokens = [word for word in tokens if word.isalpha()] #no removing non alpha words to keep stock names($ZSL) # filter out stop words stop_words = set(stopwords.words('english')) tokens = [w for w in tokens if not w in stop_words] # for w in stop_words: # print(w) # print(tokens) # filter out short tokens # tokens = [word for word in tokens if len(word) > 1] # print(tokens) remove_digits = str.maketrans('', '', digits) # print(tokens) tokens = [w.translate(remove_digits) for w in tokens] tokens = [w.strip() for w in tokens] tokens = [w for w in tokens if w!=""] # print(tokens) tokens = ' '.join(tokens) return tokens def create_tokenizer(lines): tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) return tokenizer # encode a list of lines def encode_text(tokenizer, lines, length): encoded = tokenizer.texts_to_sequences(lines) padded = pad_sequences(encoded, maxlen=length, padding='post') return padded #not needed here since this is binary classification def convert_lables(trainY,testY): le = preprocessing.LabelEncoder() le.fit(trainY+testY) temp1 = le.transform(trainY) return to_categorical(temp1,no_of_classes),le.classes_ #loading GloVe embedding def load_GloVe_embedding(file_name): embeddings_index = dict() f = open(file_name,encoding="utf8") for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Loaded %s word vectors.' % len(embeddings_index)) return embeddings_index # create a weight matrix for words in training docs def get_GloVe_embedding_matrix(embeddings_index): embedding_matrix = np.zeros((vocab_size, 100)) for word, i in tokenizer.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix sentence= df_new['text'] labels = df_new['target'] sentence = [clean_sentence(x) for x in sentence] lengths = [len(s.split()) for s in sentence] print('max len = ',max(lengths)) #sns.distplot(lengths) #Deviding it into train and test max_length = max(lengths) X_train = sentence[:4000] X_test = sentence[4000:] Y_train= labels[:4000] Y_test = labels[4000:] #Training data tokenizer = create_tokenizer(X_train) vocab_size = len(tokenizer.word_index) + 1 trainX = encode_text(tokenizer, X_train, max_length) # testX = encode_text(tokenizer, testX, max_length) #trainY,lable_encoding = convert_lables(Y,[]) #Testing data tokenizer = create_tokenizer(X_test) vocab_size = len(tokenizer.word_index) + 1 testX = encode_text(tokenizer, X_test, max_length) # + print(vocab_size) print(len(trainX)) print(len(X_train)) # - embeddings_index_glove = load_GloVe_embedding('glove.6B.100d.txt') len(embeddings_index_glove) get_embeddings = get_GloVe_embedding_matrix(embeddings_index_glove) #For each sentence #1. See all words's emebeddings (of size 100 for each word) #2. Take the mean of A[0] ,B[0], C[0].....N[0], such that A, B,C .. N are words of embeddings. #3. Do this till A[100]...N[100] #4. This creates a vector sentence1 : [mean of first bit of words........... mean of last bit of words] # + #Finds the mean of all the words in the sentence def mean_vector_sentence(sentence): l1=[] for word in sentence.split(): l1.append(get_embeddings[tokenizer.word_index[word]]) mat = np.array(l1) v=np.mean(mat) return v # - #Each sentence is now a vector , taken by mean of vectors of the words in the sentence vect_sentence=[] for s in sentence: vect_sentence.append(mean_vector_sentence(s)) len(vect_sentence) len(Y) # + #Now for example title for each title will be created such. #Will content embeddings be done sentence wise or the entire row content into one vector #These embeddings will be further used in the cnn network for the fused main model. # + embedding_dim = 256 filter_sizes =4 num_filters = 512 drop = 0.4 epochs = 100 batch_size = 10 # + from PIL import Image as PImage from os import listdir from keras.models import Model from keras.applications.vgg19 import decode_predictions from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.applications.vgg19 import preprocess_input from keras.applications.vgg19 import decode_predictions from keras.applications.vgg19 import VGG19 #function to find the image vector fro pre-trained VGG19 Model #Datasets of fake and real images for each article #file being the name of the folder of images. def image_embeddings(file): imagesList = listdir(file) model= VGG19(weights='imagenet') final_image = [] for img in imagesList: img= file+'/'+img #img = PImage.open(file +'/'+ img) image = load_img(img, target_size=(224, 224)) # convert the image pixels to a numpy array image = img_to_array(image) # reshape data for the model image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) # prepare the image for the VGG model image = preprocess_input(image) # predict the probability across all output classes yhat = model.predict(image) final_image.append(yhat) # convert the probabilities to class labels label = decode_predictions(yhat) # retrieve the most likely result, e.g. highest probability label = label[0][0] # print the classification # print('%s (%.2f%%)' % (label[1], label[2]*100)) return final_image # - # define the model def define_model(length_title, vocab_size_title, length_content , vocab_size_content,rel_embeddings): # channel 1 : title inputs1 = Input(shape=(length,)) embedding1 = Embedding(vocab_size,100)(inputs1) #Filter size:4 conv1 = Conv1D(filters=32, kernel_size=4, activation='relu')(embedding1) pool1 = MaxPooling1D(pool_size=2)(conv1) flat1 = Flatten()(pool1) # channel 2 : CONTENT + KG inputs2 = Input(shape=(length_content,)) embedding2 = Embedding(vocab_size, 100)(inputs2) conv2 = Conv1D(filters=32, kernel_size=4, activation='relu')(embedding2) #drop2 = Dropout(0.5)(conv2) pool2 = MaxPooling1D(pool_size=2)(drop2) flat2 = Flatten()(pool2) #should this be embedding content kalength? inputs3 = Input(shape=(length_content,)) #embedding3 = Embedding(vocab_size, 100)(inputs3) conv3 = Conv1D(filters=32, kernel_size=8, activation='relu')(rel_embedding) drop3 = Dropout(0.5)(conv3) pool3 = MaxPooling1D(pool_size=2)(drop3) flat3 = Flatten()(pool3) merged_content = concatenate([flat2,flat3]) #IMAGES inputs4 = #max length of of image embedding image_embedding = image_embeddings('fake') # merge merged = concatenate([flat1, merged_content ,image_embeddings]) #merged2= conactenate(image_embeddings) # interpretation dense1 = Dense(10, activation='relu')(merged) #dense2 = Dense(10,activation='relu')(merged2) outputs = Dense(1, activation='softmax')(dense1) #what should be put in input for image embedding? model = Model(inputs=[inputs1, inputs2, inputs3, inputs4], outputs=outputs) # compile model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # summarize print(model.summary()) plot_model(model, show_shapes=True, to_file='final.png') return model from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils.vis_utils import plot_model from keras.utils import to_categorical from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers import Flatten from keras.layers import Dropout from keras.layers import Embedding from keras.layers.convolutional import Conv1D from keras.layers.convolutional import MaxPooling1D from keras.optimizers import Adam # + #Model for title def define_model(length, vocab_size): # channel 1 : title inputs1 = Input(shape=(length,)) #embedding dimention :256 embedding1 = Embedding(vocab_size,100)(inputs1) #Filter size:4 conv1 = Conv1D(filters=32, kernel_size=4, activation='relu')(embedding1) #This is what I think it should be,becuase embedding dimention is256 #conv2= Conv2D(num_filters, kernel_size=(4,256), padding='valid', kernel_initializer='normal', activation='relu')(embedding1) #drop1 = Dropout(0.5)(conv1) #pool1 = MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None)(conv2) pool1 = MaxPooling1D(pool_size=2)(conv1) flat1 = Flatten()(pool1) merged = flat1 # interpretation dense1 = Dense(10, activation='relu')(merged) outputs = Dense(1, activation='sigmoid')(dense1) model = Model(inputs=inputs1, outputs=outputs) # compile model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) return model # - model =define_model(max_length,vocab_size) history_object = model.fit(trainX,Y_train,epochs=10, batch_size=64) p=model.predict(testX) p #Will this go into the model in final predict? #Ask Simra len(p) model.evaluate(testX,Y_test)
Title.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Two sample t test # **Two sample t test (Snedecor and Cochran 1989) is used to determine if two population means are equal. # A common application is to test if a new treatment or approach or process is yielding better results than the current treatment or approach or process.** # # * 1) Data is *paired* - For example, a group of students are given coaching classes and effect of coaching on the marks scored is determined. # * 2) Data is *not paired* - For example, find out whether the miles per gallon of cars of Japanese make is superior to cars of Indian make. import numpy as np import pandas as pd from scipy.stats import ttest_1samp, ttest_ind import matplotlib.pyplot as plt import matplotlib import seaborn as sns import scipy.stats as stats import statsmodels.stats.api as sm # ## Example 1 - Independent Two Sample T-Test # A hotel manager looks to enhance the initial impressions that hotel guests have when they check in. Contributing to initial impressions is the time it takes to deliver a guest’s luggage to the room after check-in. A random sample of 20 deliveries on a particular day were selected in Wing A of the hotel, and a random sample of 20 deliveries were selected in Wing B. The results are stored in Luggage . Analyze the data and determine whether there is a difference between the mean delivery times in the two wings of the hotel. (Use $\alpha$ = 0.05) <br> # Problem 10.83 from the Textbook adapted for Classroom Discussion(Chapter 10-page 387) mydata = pd.read_excel('Quiz_Dataset.xlsx') mydata.head() # ### Step 1: Define null and alternative hypotheses # In testing whether the mean time of deliveries of the luggages are same in both the wings of the hotel, the null hypothesis states that the mean time to deliver the luggages are the same, $\mu{A}$ equals $\mu{B}$. The alternative hypothesis states that the mean time to deliver the luggages are different, $\mu{A}$ is not equal to $\mu{B}$. # # * $H_0$: $\mu{A}$ - $\mu{B}$ = 0 i.e $\mu{A}$ = $\mu{B}$ # * $H_A$: $\mu{A}$ - $\mu{B}$ $\neq$ 0 i.e $\mu{A}$ $\neq$ $\mu{B}$ # ### Step 2: Decide the significance level # Here we select $\alpha$ = 0.05 and the population standard deviation is not known. # ### Step 3: Identify the test statistic # * We have two samples and we do not know the population standard deviation. # * Sample sizes for both samples are same. # * The sample is not a large sample, n < 30. So you use the t distribution and the $t_{STAT}$ test statistic for two sample unpaired test. # ### Step 4: Calculate the p - value and test statistic # ** We use the scipy.stats.ttest_ind to calculate the t-test for the means of TWO INDEPENDENT samples of scores given the two sample observations. This function returns t statistic and two-tailed p value.** # # ** This is a two-sided test for the null hypothesis that 2 independent samples have identical average (expected) values. This test assumes that the populations have identical variances.** # For this exercise, we are going to first assume that the variance is equal and then compute the necessary statistical values. t_statistic, p_value = ttest_ind(mydata['US_Cars'],mydata['Japanese_Cars']) print('tstat',t_statistic) print('P Value',p_value) # ### Step 5: Decide to reject or accept null hypothesis # + # p_value < 0.05 => alternative hypothesis: # they don't have the same mean at the 5% significance level print ("two-sample t-test p-value=", p_value) alpha_level = 0.05 if p_value < alpha_level: print('We have enough evidence to reject the null hypothesis in favour of alternative hypothesis') print('We conclude that the mean time to deliver luggages in of both the wings of the hotel are not same.') else: print('We do not have enough evidence to reject the null hypothesis in favour of alternative hypothesis') print('We conclude that mean time to deliver luggages in of both the wings of the hotel are same.') # - # Let us now go ahead and check the confidence intervals at a specific $\alpha$ value. # ## Example 2 - Paired T-Test # The file Concrete contains the compressive strength, in thousands of pounds per square inch (psi), of 40 samples of concrete taken two and seven days after pouring. (Data extracted from <NAME> and <NAME>, “Measurement-Error-Model Collinearities,” Technometrics, 34 (1992): 454–464.) # # At the 0.01 level of significance, is there evidence that the mean strength is lower at two days than at seven days? # # Problem 10.26 from the Textbook adapted for Classroom Discussion(Chapter 10-page 353) # mydata = pd.read_csv('Concrete.csv') mydata.head() # ## Step 1: Define null and alternative hypotheses # In testing whether the number of days has any effect on the lowering the compressive strength of the concrete, # * the null hypothesis states that the compressive strength of the cement is not lower at 2 days than at 7 days, $\mu_{2}$ $\geq$ $\mu_{7}$. # * The alternative hypthesis states that the compressive strength of the cement is lower at 2 days than at 7 days, $\mu_{2}$ < $\mu_{7}$ # # * $H_0$: $\mu_{2}$ - $\mu_{7}$ $\geq$ 0 # * $H_A$: $\mu_{2}$ - $\mu_{7}$ < 0 # # Here, $\mu_2$ denotes the mean compressive strenght of the cement after two days and $\mu_7$ denotes the mean compressive strength of the cement after seven days. # ## Step 2: Decide the significance level # Here we select $\alpha$ = 0.01 as given in the question. # ## Step 3: Identify the test statistic # * Sample sizes for both samples are same. # * We have two paired samples and we do not know the population standard deviation. # * The sample is not a large sample, n < 30. So you use the t distribution and the $t_{STAT}$ test statistic for two sample paired test. # ## Step 4: Calculate the p - value and test statistic # **We use the scipy.stats.ttest_rel to calculate the T-test on TWO RELATED samples of scores. This is a two-sided test for the null hypothesis that 2 related or repeated samples have identical average (expected) values. Here we give the two sample observations as input. This function returns t statistic and two-tailed p value.** # paired t-test: doing two measurments on the same experimental unit # e.g., before and after a treatment t_statistic, p_value = stats.ttest_rel(mydata['Two Days'],mydata['Seven Days']) print('tstat %1.3f' % t_statistic) print("p-value for one-tail:", p_value/2) # ## Step 5: Decide to reject or accept null hypothesis # + # p_value < 0.05 => alternative hypothesis: # they don't have the same mean at the 5% significance level print ("Paired two-sample t-test p-value=", p_value/2) alpha_level = 0.01 if (p_value/2) < alpha_level: print('We have enough evidence to reject the null hypothesis in favour of alternative hypothesis') else: print('We do not have enough evidence to reject the null hypothesis in favour of alternative hypothesis')
M2 Statistical Methods for Decision Making/Week_3_SMDM_Hypothesis_Testing/T Test (two-sample) - --.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Materials # # PyNE `Material` objects provide a way of representing, manipulating, and storing materials. A `Material` object is a collection of nuclides with various mass fractions (though methods for converting to/from atom fractions are present as well). Optionally, a `Material` object may have an associated mass. By keeping the mass and the composition separate, operations that only affect one attribute may be performed independent of the other. Most of the functionality of the `Material` class is # implemented in a C++, so this interface is very fast and light-weight. # # `Material`s may be initialized in a number of different ways. For example, initializing from # dictionaries of compositions are shown below. First import the `Material` class: from pyne.material import Material # Now create a low enriched uranium (leu) with a mass of 42: leu = Material({'U238': 0.96, 'U235': 0.04}, 42) leu # Create another `Material`, this one with more components. Notice that the mass is 9 x 1.0 = 9.0: nucvec = {10010: 1.0, 80160: 1.0, 691690: 1.0, 922350: 1.0, 922380: 1.0, 942390: 1.0, 942410: 1.0, 952420: 1.0, 962440: 1.0} mat = Material(nucvec) print(mat) # Materials may also be initialized from plain text or HDF5 files (see ``Material.from_text()`` and # ``Material.from_hdf5()``). # ------ # # ## Normalization # # Upon instantiation, the mass fraction that define a `Material` are normalized. However, you can always obtain the unnormalized mass vector through ``Material.mult_by_mass()``. Normalization routines to normalize the mass ``Material.normalize()`` or the composition ``Material.norm_comp()`` are also available. Here we see that our 42 units of LEU consists of 1.68 units of U-235 and 40.32 units of U-238: leu.mult_by_mass() # Recall that `mat` has a mass of 9. Here it is normalized to a mass of 1: mat.normalize() mat mat.mass # ----------- # # ## Material Arithmetic # # Various arithmetic operations between Materials and numeric types are also defined. # Adding two Materials together will return a new Material whose values are the weighted union # of the two original. Multiplying a Material by 2, however, will simply double the mass of the original Material. other_mat = mat * 2 other_mat other_mat.mass weird_mat = leu + mat * 18 print(weird_mat) # Note that there are also ways of mixing `Materials` by volume using known densities. See the `pyne.MultiMaterial` class for more information. # --------------- # # ## Raw Member Access # # You may also change the attributes of a material directly without generating a new # material instance. other_mat.mass = 10 other_mat.comp = {10020000: 3, 922350000: 15.0} print(other_mat) # Of course when you do this you have to be careful because the composition and mass may now be out # of sync. This may always be fixed with normalization. other_mat.norm_comp() print(other_mat) # -------- # # ## Indexing & Slicing # # Additionally (and very powerfully!), you may index into either the material or the composition # to get, set, or remove sub-materials. Generally speaking, you may only index into the # composition by integer-key and only to retrieve the normalized value. Indexing into the material allows the # full range of operations and returns the unnormalized mass weight. Moreover, indexing into # the material may be performed with integer-keys, string-keys, slices, or sequences of nuclides. leu.comp[922350000] leu['U235'] weird_mat['U':'Am'] other_mat[:920000000] = 42.0 print(other_mat) del mat[962440, 'TM169', 'Zr90', 80160] mat[:] # Other methods also exist for obtaining commonly used sub-materials, such as gathering the Uranium or # Plutonium vector. # ### Molecular Weights & Atom Fractions # # You may also calculate the molecular weight of a material via the ``Material.molecular_weight`` method. # This uses the ``pyne.data.atomic_mass`` function to look up the atomic mass values of # the constituent nuclides. leu.molecular_mass() # Note that by default, materials are assumed to have one atom per molecule. This is a poor # assumption for more complex materials. Take water for example. Without specifying the # number of atoms per molecule, the molecular weight calculation will be off by a factor of 3. # This can be remedied by passing the correct number to the method. If there is no other valid # number of molecules stored on the material, this will set the appropriate attribute on the # class. h2o = Material({'H1': 0.11191487328808077, 'O16': 0.8880851267119192}) h2o.molecular_mass() h2o.molecular_mass(3.0) h2o.atoms_per_molecule # It is also useful to be able to convert the current mass-weighted material to # an atom fraction mapping. This can be easily done via the `Material.to_atom_frac()` # method. Continuing with the water example, if the number of atoms per molecule is # properly set then the atom fraction returned is normalized to this amount. Alternatively, # if the atoms per molecule are set to its default state on the class, then a truly # fractional number of atoms is returned. h2o.to_atom_frac() h2o.atoms_per_molecule = -1.0 h2o.to_atom_frac() # Additionally, you may wish to convert an existing set of atom fractions to a # new material stream. This can be done with the `Material.from_atom_frac()` method, # which will clear out the current contents of the material's composition and replace # it with the mass-weighted values. Note that when you initialize a material from atom # fractions, the sum of all of the atom fractions will be stored as the atoms per molecule # on this class. Additionally, if a mass is not already set on the material, the molecular # weight will be used. # + h2o_atoms = {10010000: 2.0, 'O16': 1.0} h2o = Material() h2o.from_atom_frac(h2o_atoms) print(h2o.comp) print(h2o.atoms_per_molecule) print(h2o.mass) print(h2o.molecular_mass()) # - # Moreover, other materials may also be used to specify a new material from atom fractions. # This is a typical case for reactors where the fuel vector is convolved inside of another # chemical form. Below is an example of obtaining the Uranium-Oxide material from Oxygen # and low-enriched uranium. uox = Material() uox.from_atom_frac({leu: 1.0, 'O16': 2.0}) print(uox) # **NOTE:** Materials may be used as keys in a dictionary because they are hashable. # ### User-defined Metadata # # Materials also have an ``metadata`` attribute which allows users to store arbitrary # custom information about the material. This can include things like units, comments, # provenance information, or anything else the user desires. This is implemented as an # in-memory JSON object attached to the C++ class. Therefore, what may be stored in # the `metadata` is subject to the same restrictions as JSON itself. The top-level # of the `metadata` *should* be a dictionary, though this is not explicitly enforced. leu = Material({922350: 0.05, 922380: 0.95}, 15, metadata={'units': 'kg'}) leu print(leu) leu.metadata m = leu.metadata m['comments'] = ['Anthony made this material.'] leu.metadata['comments'].append('And then Katy made it better!') m['id'] = 42 leu.metadata leu.metadata = {'units': 'solar mass'} leu.metadata m leu.metadata['units'] = 'not solar masses' leu.metadata['units'] # As you can see from the above, the attrs interface provides a view into the underlying # JSON object. This can be manipulated directly or by renaming it to another variable. # Additionally, ``metadata`` can be replaced with a new object of the appropriate type. # Doing so invalidates any previous views into this container.
tutorial/02-materials.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] pycharm={"metadata": false} # # MLTSA vs Feature Permutations # # ###### *Note that this Jupyter Notebook requires you to have the MLTSA package installed. # - # As usual with MLTSA experiments we first create the 1D analytical model dataset. # + """First we import our dataset examples""" from MLTSA_datasets.OneD_pot.OneD_pot_data import potentials #We import the potentials class which will define them. from MLTSA_datasets.OneD_pot.OneD_pot_data import dataset #We import the dataset class which will hold our potentials. import matplotlib.pyplot as plt import numpy as np #This cell sets the potentials, don't re-run total_n_pots = 25 n_DW = 5 relevant_DW_n = 2 #After defining the desired parameters we define the potentials accordingly pots = potentials(total_n_pots, n_DW, relevant_DW_n) # This creates the first dataset of data. n_features = 180 degree_of_mixing = 2 #We specified the number of features wanted and how much they will mix oneD_dataset = dataset(pots, n_features, degree_of_mixing) # + [markdown] pycharm={} # Once the dataset has been created we generate the data we will use over the comparison # + pycharm={"name": "#%%\n"} """Now we generate the trajectories we will use for the whole experiment""" #Generate the trajectories n_simulations = 100 n_steps = 250 data, ans = oneD_dataset.generate_linear(n_simulations, n_steps) data_val, ans_val = oneD_dataset.generate_linear(int(n_simulations/2), n_steps) # + [markdown] pycharm={} # # + pycharm={"name": "#%%\n"} from MLTSA_sklearn.models import SKL_Train from sklearn.neural_network import MLPClassifier from MLTSA_sklearn.MLTSA_sk import MLTSA #For loop for MLTSA and Permutation on MLP time_bins = 50 time_range = np.linspace(0, n_steps, time_bins) results = {} results["MLTSA"] = [] results["NN"] = [] results["acc"] = [] for t in range(time_bins-1): time_frame = [int(time_range[t]), int(time_range[t+1])] X, Y = oneD_dataset.PrepareData(data, ans, time_frame, mode="Normal") X_val, Y_val = oneD_dataset.PrepareData(data_val, ans_val, time_frame, mode="Normal") NN = MLPClassifier(random_state=0, verbose=False, max_iter=500) trained_NN, train_acc, test_acc = SKL_Train(NN, X, Y) Y_pred = trained_NN.predict(X_val) val_acc = Y_val == Y_pred val_acc = np.mean(val_acc) ADrop_train_avg = MLTSA(data[:,:,int(time_frame[0]):int(time_frame[1])], ans, trained_NN, drop_mode="Average") results["MLTSA"].append(ADrop_train_avg) results["NN"].append(trained_NN) results["acc"].append([train_acc, test_acc, val_acc]) # + pycharm={"name": "#%%\n"} acc = np.array(results["acc"]) adrop = np.array(results["MLTSA"]) plt.figure() plt.title("Accuracy through replicas (MLP)") plt.plot(acc.T[0]*100,"-o", label="Training",) plt.plot(acc.T[1]*100,"-o", label="Test") plt.xlabel("Replica") plt.ylabel("Accuracy") plt.legend() std = np.std(adrop, axis=0)*100 mean = np.mean(adrop, axis=0)*100 plt.figure() plt.title("MLTSA - MLP") plt.plot(mean) plt.ylabel("Accuracy") plt.xlabel("Feature (CV)") # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} import seaborn as sns #plt.figure(figsize=(50,5)) #plt.matshow(adrop.T) sns.heatmap(adrop.T) # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} from MLTSA_sklearn.MLTSA_sk import MLTSA_Plot #We simply get the plot with this MLTSA_Plot(adrop, oneD_dataset, pots, errorbar=False) # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} from MLTSA_sklearn.models import SKL_Train from sklearn.neural_network import MLPClassifier from MLTSA_sklearn.MLTSA_sk import MLTSA #For loop for MLTSA and Permutation on MLP time_bins = 50 time_range = np.linspace(0, n_steps, time_bins) region = 25 results_d = {} results_d["MLTSA"] = [] results_d["NN"] = [] results_d["acc"] = [] for t in range(time_bins-1): time_frame = [int(time_range[t]), int(time_range[t]+25)] X, Y = oneD_dataset.PrepareData(data, ans, time_frame, mode="Normal") X_val, Y_val = oneD_dataset.PrepareData(data_val, ans_val, time_frame, mode="Normal") NN = MLPClassifier(random_state=0, verbose=False, max_iter=500) trained_NN, train_acc, test_acc = SKL_Train(NN, X, Y) Y_pred = trained_NN.predict(X_val) val_acc = Y_val == Y_pred val_acc = np.mean(val_acc) ADrop_train_avg = MLTSA(data[:,:,int(time_frame[0]):int(time_frame[1])], ans, trained_NN, drop_mode="Average") results_d["MLTSA"].append(ADrop_train_avg) results_d["NN"].append(trained_NN) results_d["acc"].append([train_acc, test_acc, val_acc]) # + pycharm={"name": "#%%\n"} acc = np.array(results_d["acc"]) adrop = np.array(results_d["MLTSA"]) plt.figure() plt.title("Accuracy through replicas (MLP)") plt.plot(acc.T[0]*100,"-o", label="Training",) plt.plot(acc.T[1]*100,"-o", label="Test") plt.xlabel("Replica") plt.ylabel("Accuracy") plt.legend() std = np.std(adrop, axis=0)*100 mean = np.mean(adrop, axis=0)*100 plt.figure() plt.title("MLTSA - MLP") plt.plot(mean) plt.ylabel("Accuracy") plt.xlabel("Feature (CV)") # + pycharm={"name": "#%%\n"} import seaborn as sns #plt.figure(figsize=(50,5)) #plt.matshow(adrop.T) sns.heatmap(adrop.T) # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} for n,feat in enumerate(adrop): print(np.argmin(feat), feat[np.argmin(feat)]) plt.scatter(n,np.argmin(feat), color="r" ) # + jupyter={"outputs_hidden": false} pycharm={"is_executing": true, "name": "#%%\n"} plt.figure() plt.title("MLTSA - MLP") plt.plot(adrop[0]) plt.ylabel("Accuracy") plt.xlabel("Feature (CV)") # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} obj = CVclass(n_features) # + [markdown] pycharm={"name": "#%% md\n"} #
notebooks/MLTSA_through_time.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: svhn-detection-tf-R5ZWXfXq-py3.8 # language: python # name: svhn-detection-tf-r5zwxfxq-py3.8 # --- import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) # + cell_id="a326d59e-8141-4b37-acc5-ea5041589658" import tensorflow as tf import tensorflow_addons as tfa import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np from svhn_dataset import SVHN # + cell_id="a93063dc-2bdd-4781-921c-b1188f318b5f" dataset = SVHN().train.map(SVHN.parse) for sample in dataset.take(10): pass print(sample['image'].shape) print(sample.keys()) sizes = np.array([x['image'].shape[0] for x in dataset.as_numpy_iterator()]) print(f'training samples: {len(sizes)}') print(f'max size: {np.max(sizes)}') print(f'min size: {np.min(sizes)}') print(f'mean size: {np.mean(sizes)}') print(f'number of samples bigger then 128: {np.sum(sizes > 128)}') print(f'number of samples bigger then 256: {np.sum(sizes > 256)}') # + cell_id="bc7f015c-0b8f-41d7-b915-243a805d6bac" input_size = 128 for sample in dataset.take(6406): pass @tf.function def scale(x): return dict(image = x['image'], classes = x['classes'], bboxes = x['bboxes']) def draw_image_and_bb(image, bbs): print(f'size: {image.shape}') plt.imshow(image) ax = plt.gca() for bb in bbs: ymin, xmin, ymax, xmax = bb.numpy() y, x = (ymin + ymax) / 2, (xmin + xmax) / 2 h, w = (ymax - ymin), (xmax - xmin) rect = patches.Rectangle((xmin, ymin),w,h,linewidth=2,edgecolor='r',facecolor='none') ax.add_patch(rect) plt.show() print(f'max size: {max_size}') draw_image_and_bb(sample['image'].numpy(), sample['bboxes']) # + [markdown] cell_id="aa6d0782-b8f9-411b-b9d8-b956d965ba9e" # # Dataset properties # max size: 293 # mean size: 76.4 # number of images bigger than 128: 1011 # train size: 10000 # + cell_id="b2e53309-2b45-4d8b-aebb-74e2eca97c66" def generate_anchors(pyramid_levels, image_size, first_feature_scale=4, anchor_scale=4.0, aspect_ratios = [(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)], num_scales=3): boxes_all = [] for s in range(pyramid_levels): boxes_level = [] for octave in range(num_scales): for aspect_h, aspect_w in aspect_ratios: scale = 2 ** (octave / num_scales) stride = first_feature_scale * 2 ** s base_anchor_size = anchor_scale * stride * scale anchor_size_x = base_anchor_size * aspect_w / 2.0 anchor_size_y = base_anchor_size * aspect_h / 2.0 x = np.arange(stride / 2, image_size, stride) y = np.arange(stride / 2, image_size, stride) xv, yv = np.meshgrid(x, y) xv = xv.reshape(-1) yv = yv.reshape(-1) boxes = np.vstack((yv - anchor_size_y, xv - anchor_size_x, yv + anchor_size_y, xv + anchor_size_x)) boxes = np.swapaxes(boxes, 0, 1) boxes_level.append(np.expand_dims(boxes, axis=1)) boxes_level = np.concatenate(boxes_level, axis=1) boxes_all.append(boxes_level.reshape(-1, 4)) return np.vstack(boxes_all) anchors = generate_anchors(4, 128, anchor_scale=3.0, first_feature_scale =4) # + cell_id="6c850a8f-01c3-41ba-a778-4cae0dfa3a4a" from importlib import reload import efficientdet reload(efficientdet) net = efficientdet.EfficientDet(5, 9, input_size= 128) # + cell_id="cd6c3181-0185-4bf4-b6f4-c62ef606dbdf" input_tensor = tf.random.uniform((2, 128, 128, 3), dtype=tf.float32) output = net(input_tensor) print(output[0].shape) print(output[1].shape) # + cell_id="34835b74-e76e-4684-82e4-6445a3dc87af" tags=[] import train from importlib import reload import utils import efficientdet import data reload(data) reload(train) from data import create_data, SVHN args, argstr = train.parse_args(['--test']) args.test = True args.batch_size = 1 args.learning_rate = 0.5 args.epochs = 100 num_classes = SVHN.LABELS pyramid_levels = args.pyramid_levels smallest_stride = 2**(6 - pyramid_levels) anchors = utils.generate_anchors(pyramid_levels, args.image_size, first_feature_scale=smallest_stride, anchor_scale=float(smallest_stride), num_scales=args.num_scales, aspect_ratios=args.aspect_ratios) train_dataset, dev_dataset, eval_dataset = create_data(args.batch_size, anchors, image_size = args.image_size, test=args.test) # Prepare network and trainer anchors_per_level = args.num_scales * len(args.aspect_ratios) network = efficientdet.EfficientDet(num_classes, anchors_per_level, input_size = args.image_size, pyramid_levels = pyramid_levels) model = train.RetinaTrainer(network, anchors, train_dataset, (dev_dataset, eval_dataset), args) # Start training print(f'running command: {argstr}') model.fit() # Save model model.save() print('model saved') # + cell_id="da42ebbc-dde3-4c69-be2b-9a773da58206" tags=[] for sample in model.eval_dataset.batch(1).take(1): class_pred, bbox_pred = network(sample['image'], training=False) tf.nn.softmax(class_pred, -1) draw_image_and_bb(sample['image'][0,...].numpy(), sample['bbox'][0,...]) # + cell_id="c6be3b08-542c-433d-b8c6-c8f9cd2f7634" tags=[] import tensorflow as tf regression_pred = utils.bbox_from_fast_rcnn(model.anchors, bbox_pred) regression_pred = tf.expand_dims(regression_pred, 2) boxes, scores, classes, valid = tf.image.combined_non_max_suppression( regression_pred, tf.nn.softmax(class_pred), 3, 5, score_threshold=0.15, iou_threshold=0.4, clip_boxes=False) boxes = tf.clip_by_value(boxes, 0, model.args.image_size) draw_image_and_bb(sample['image'][0,...].numpy(), boxes[0,...]) print(scores) print(classes) # + cell_id="4daec138-5333-4f28-95da-e74818b97ab4" tags=[] print(scores) print(classes) print(tf.nn.softmax(class_pred))
svhn_detection/notebooks/svhn-playground.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) # # <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=TechnologyStudies/ComputerScienceSocrata/3-joining-datasets.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> # # Joining Datasets # # Unlike standard SQL, SODA does not (currently) support the joining of separate datasets. As you recall, this is a fundamental part of working with data. Often, there are different sets of data for the same entity, and it doesn't make sense to store them all in one dataset. Even if you wanted to, this would quickly increase the # of columns in a dataset. # # For example, the [School Locations](https://data.calgary.ca/Services-and-Amenities/School-Locations/fd9t-tdn2) dataset we have already looked at stores both the geographical information of schools in Calgary. The [School Enrolment](https://data.calgary.ca/Demographics/School-Enrolment-Data/9qye-mibh) dataset stores the enrollment information for schools. It should be quite obvious that these two datasets should remain separate. Most often, you would not need enrollment #s when looking for locations, and vice versa. If the datasets were permanently combined, you likely have a lot of redundant columns. Moreover, the school enrollment dataset is *keyed* on the school year. You would have to repeat the geographical data in each row, which would be a poor use of space. # # But, what if we wanted to demonstrate additional features of the scattermapbox by visualizing school enrollment? We will need to obtain data from the two seperate datasets, and dynamically *join* them together. As mentioned, we can't do it in SODA, but we can do so programatically using the pandas 'merge' function. # + import requests as rq import pandas as pd import io as io domain = "https://data.calgary.ca/resource/" uuid_school_locations = "fd9t-tdn2" uuid_school_enrollment = "9qye-mibh" def run_query(domain, uuid, query): session = rq.Session() results = session.get(domain + uuid +".csv?$query=" + query) dataframe = pd.read_csv(io.StringIO(results.content.decode('utf-8'))) return dataframe # - # The first dataset contains latitude and longitude # + query = """ SELECT * """ calgary_school_location = run_query(domain, uuid_school_locations, query) calgary_school_location # - # The second dataset contains enrollment data. Note that the enrollment dataset also contains a school_year column, which makes sense, as enrollment values do change. However, our intent is to visualize enrollment at a specific point in time, so we use the WHERE clause to filter out rows that do not match that time. # + query = """ SELECT * WHERE school_year = '2019-2020' """ calgary_school_enrollment = run_query(domain, uuid_school_enrollment, query) print(calgary_school_enrollment) # - # ## Data from CSV files # # We could instead use pandas to import data from CSV ([comma separated values](https://en.wikipedia.org/wiki/Comma-separated_values)) files. # + import pandas as pd calgary_school_location = pd.read_csv("https://data.calgary.ca/resource/64t2-ax4d.csv") calgary_school_enrollment = pd.read_csv("https://data.calgary.ca/resource/9qye-mibh.csv?$where=School_Year%20=%20'2019-2020'") # - calgary_school_location # ## Joining data sets # # Whichever method we use to import the data, we can now *join* the two datasets on the school name (`school_name` in `calgary_school_location` and `name` or `NAME` in `calgary_school_enrollment`) as the values in these fields match up. In proper SQL parlance, they share a *key*. Again, the dataset has already been filtered for a single school year. This means that there should be no duplicates of school name in the school enrollment dataset. # # Thus, we can do a simple left join with the enrollment on the left and the locations on the right. That way, our resulting dataframe will only have data on schools that have enrollment data. We would run into problems later on if there are NaN (aka null) values in the total field. # + calgary_school_location_enrollment = pd.merge(left=calgary_school_enrollment, right=calgary_school_location, how='left', left_on='school_name', right_on='NAME' ) # right_on='name' ) #use this line if you imported data using Requests calgary_school_location_enrollment # - # ## Visualizing the data # # We will now visualize the resulting dataset, and use the `size` and `color` to add two extra dimensions of data - the total enrollment and the school authority. # # ##### Note # # - the `showlegend` parameter is used to hide the legend, but this is only to clean up the presentation! # + import plotly.express as px figure1 = px.scatter_mapbox(calgary_school_location_enrollment, size="total", color="school_authority_name", #showlegend= False, color_continuous_scale=px.colors.cyclical.IceFire, size_max=45, lat="latitude", lon="longitude", hover_name="school_name", hover_data=["TYPE", "GRADES", "ADDRESS_AB"], #hover_data=["type", "grades", "address_ab"], #use this line if you imported data using Requests zoom=10, height=600) figure1.update_layout(mapbox_style="open-street-map") figure1.update_layout(showlegend= False) figure1.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # - # ## Conclusion # # This notebook introduced the ability to join datasets. The last notebook in this series is [filtering datasets](./4-filtering-datasets.ipynb). # [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
_build/html/_sources/curriculum-notebooks/TechnologyStudies/ComputerScienceSocrata/3-joining-datasets.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- from bokeh.io import output_notebook, show, reset_output import numpy as np output_notebook() # ### Plotting connected plots on bokeh # + from bokeh.models import ColumnDataSource, TapTool, DataRange1d, Plot, LinearAxis, Grid, HoverTool, CustomJS from bokeh.plotting import figure, output_file, show from bokeh.models.glyphs import HBar from bokeh.layouts import row, column import bokeh.palettes p = figure(plot_width=400, plot_height=400, tools="tap", title="Click the Dots") C = np.array(bokeh.palettes.BrBG10) C2 = C[np.random.randint(low = 0, high=10, size= 100)] source = ColumnDataSource(data=dict( x=np.random.rand(100), y=np.random.rand(100), color= C2 )) p.circle('x', 'y', color='color', size=20, source=source) source2 = ColumnDataSource(data=dict( x=[1,2], y=[1,2])) callback = CustomJS(args=dict(source2=source2), code=""" var data = source2.data; var geom = cb_data['geometries']; console.log(geom); console.log(data); //data['x'] = [geom.sx+1,geom.sx-1] data['y'] = [geom.sx,geom.sy] console.log(data); source2.change.emit(); """) taptool = p.select(type=TapTool) taptool.callback = callback; xdr = DataRange1d() ydr = DataRange1d() p2 = figure(plot_width=400, plot_height=400) p2.vbar(x='x', width=0.5, bottom=0, top='y', source=source2, color="firebrick") #glyph = HBar(source2.data['x'], source2.data['y'], left=0, height=0.5, fill_color="#b3de69") #p2.add_glyph(source2, glyph) #p2.add_glyph(source, glyph) show(row(p,p2)) # + # zooming in on clusters using sliders from bokeh.layouts import row, column from bokeh.models import CustomJS, ColumnDataSource, Slider import matplotlib.pyplot as plt slider = Slider(start=0, end=6, value=1, step=1, title="Cluster number") temp = np.random.rand(7,10) temp = temp.tolist() CorrMat = np.random.rand(7,7) source = ColumnDataSource(data=dict( x = temp, In= range(7))) source2 = ColumnDataSource(data=dict( x=[0]*10, y=range(10))) source3 = ColumnDataSource(data=dict( x=[0]*7, y=range(7))) update_curve = CustomJS(args=dict(source=source, source2 = source2, slider=slider), code=""" var data = source.get('data'); var data2 = source2.get('data'); var f = slider.value; console.log(data); console.log(data2); data2['x'] = data['x'][f]; source2.change.emit(); """) plot = figure(plot_width=400, plot_height=400, title = 'Correlation with bulk') plot.vbar(x='y', width=0.1, bottom=0, top='x', source=source2, color="firebrick") slider.js_on_change('value', update_curve) show(column(slider, plot)) # - #plotting heatmap of correlation matrix
TestingBokeh/.ipynb_checkpoints/BokehConnectedPlots-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:quetzal_env] # language: python # name: conda-env-quetzal_env-py # --- # + import sys sys.path.insert(0, r'../../../quetzal') import pandas as pd from quetzal.model import stepmodel, model # %matplotlib inline # - training_folder = '../../' sm = stepmodel.read_zip(training_folder + 'model/preparation/road.zip') sandbox = stepmodel.read_zip(training_folder + 'model/preparation/sandbox.zip') sandbox = sandbox.change_epsg(epsg=3857, coordinates_unit='meter') sm.links = sandbox.links sm.nodes = sandbox.nodes sm.plot('links', ax=sm.plot('nodes', color='green', ax=sm.plot('road_links', color='red', linewidth=0.1))) # # Networkcaster # à faire sur un réseau propre, avant l'agrégation sm.integrity_test_all(errors='ignore', verbose=True) sm.preparation_cast_network( nearest_method='nodes', n_neighbors_centroid=10, n_neighbors=5 ) sm.to_zip( training_folder + 'model/preparation/sandbox_networkcasted.zip' ) sm.analysis_lines() sm.plot('links', ax=sm.plot('nodes', color='green'))
quetzal_paris-master/notebooks/transport/EX11_networkcaster_GIS_routes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Example 2: Preprocessing, Postprocessing, and Model Scripts # # In this example, you will learn how to define custom preprocessing, postprocessing, and model inference scripts that will be used in Open Seismic. These custom scripts will be useful for you if you want to use a model that does not exist within Open Seismic, but you would still like to use our inference pipeline powered by OpenVINO. # # ### Sections # 2.1 **Overview of Inference Tasks in Open Seismice** <br/> # 2.2 **Defining Pre, Post, and Model Inference Scripts** <br/> # &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.2.1 **Regular, Coarse, and Fine Cube Inference**<br/> # &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.2.2 **Section Inference**<br/> # 2.3 **Defining Conversion Scripts**<br/> # # **Note:** This example does not have cells to run. Instead, the goal of this example is to go over the structure of the custom scripts. In the next example, we will use the scripts defined here in Open Seismic. # ## 2.1 Specifying Preprocessing Scripts # # There are four main inference tasks that Open Seismic supports: # 1. **Regular Inference:** This is an all purpose inference task that loops through your input data. # 2. **Coarse Cube Inference:** This task is mainly used for fault segmentation. Specifically, a small mini cube of a much larger 3D seismic data is used as input, and a small mini cube of the same size is expected as output from the network. This cube is stored appropriately (a 3D coordinate is matched with its network output) in an output cube that is of the same size as the larger input. # 3. **Fine Cube Inference:** This task is mainly used for salt identification. Specifically, a small mini cube of a much larger 3D seismic data is used as input, and a scalar value is expected as output from the network. This scalar value is stored within a scaled down cube, and optionally, this can be interpolated to match the larger input size. # 4. **Section Inference:** This task is mainly used for facies classification. Specifically, a small 2D section of a much larger slice of seismic data is used as input, and a small 2D mask of the same size is expected as output from the network. The small section is stored appropriately in an output mask that is of the same size as the larger slice. Section input size will be maximized to do inference on the largest ingestible area since larger section size has been shown to produce more accurate results. # # Furthermore, there are synchronous and asynchronous modes for each inference task. However, we expect that most use cases will involve asynchronous inference. # # Next, we will do a break down of preprocessing, postprocessing, and model inference scripts. This level of granularity is needed since these tasks are fundamentally different. # ## Section 2.2: Defining Pre, Post, and Model Inference Scripts # # Below is a breakdown of the expected definitions for each inference task (regular, coarse, and fine cube inference tasks were combined since their usage of scripts is the same). # # In general, this is what each script should include: # 1. The preprocessing script `preprocessor.py` should at least define one function called `preprocess`. # 2. The postprocessing script `postprocessor.py` should at least define one function called `postprocess`. # 3. The model script `model.py` should at least define one class called `model`. # # ### Subsection 2.2.1: Regular, Coarse, and Fine Cube Inference # # **Preprocessing:** `preprocessor.py` should define `preprocess` as follows: # ``` # def preprocess(data, input_layers, input_shape=(...), model=None): # ... # return {input_layer_1: data_1, ..., input_layer_n: data_n} # ``` # The inputs are defined as follows: # 1. `data`: Input data passed from the inference task. # 2. `input_layers`: A list of the input layers that exist within the model. # 3. `input_shape`: A tuple specifying the shape of the input or a list of tuples specifying shapes of the input layers. You can match input shape with the input layer by index of `input_layers`. # 4. `model`: The model object defined in `model.py`. # # **Postprocessing:** `postprocessor.py` should define `postprocess` as follows: # ``` # def postprocess(output_dict, output_shape=(...)): # ... # return {output_layer_1: data_1, ..., output_layer_n: data_n} # ``` # The inputs are defined as follows: # 1. `output_dict`: An output dictionary mapping output layer name to associated output data. In reality, this should only be a dictionary of one output layer key. # 2. `output_shape`: A tuple specifying the shape of the output. # # **Model:** `model.py` should define the model class with the following methods: # ``` # class model(object): # def __init__(self, xml_path, bin_path, requests=1, input_shape=(...)): # # Initialize model. Must include the following attritubes: # self.ie = IECore() # self.requests = requests # self.read_net = self.ie.read_network( # model=xml_path, weights=bin_path) # self.exec_net = self.ie.load_network( # network=self.read_net, device_name="...", # num_requests=requests) # self.name = "..." # ... # # # Include a warmth session for optimal inference # self.exec_net.requests[0].infer() # ``` # # Here are the methods for synchronous inference: # ``` # # Continuing model definition... # def infer(self, input_dict, flexble_infer=False): # # Use flexible infer condition for varying-shape inference # ... # return output_dict, latency # # def reshape_input(self, shapes): # # Reshape input layer(s) to specific shape(s) # ... # ``` # # Here are the getter methods for general usage: # ``` # # Continuing model definition... # def get_input_shape(self): # # May be list instead of tuple for multiple input layers # ... # return input_shape # # def get_inputs(self): # # Return list of input layer names # ... # return input_layer_names # # def get_outputs(self): # # Return list of output layer names # ... # return output_layer_names # ``` # # Finally, here are the methods for asynchronous inference: # ``` # # Continuing model definition... # def get_requests(self): # # Return requests from exec net # return self.exec_net.requests # or self.requests # # def get_idle_request_id(self): # # Return idle request # return self.exec_net.get_idle_request_id() # ``` # ### Section 2.2.2: Section Inference # # This section mentions the subtle differences between the other inference tasks and the section inference task. # # **Preprocessing:** `preprocessor.py` should define `preprocess` as follows: # ``` # def preprocess(data, input_layers, model, input_shape=(...)): # ... # return {input_layer_1: data_1, ..., input_layer_n: data_n} # ``` # The inputs are defined as follows: # 1. `data`: Input data passed from the inference task. # 2. `input_layers`: A list of the input layers that exist within the model. # 3. `input_shape`: A tuple specifying the shape of the input or a list of tuples specifying shapes of the input layers. You can match input shape with the input layer by index of `input_layers`. # 4. `model`: The model object defined in `model.py`. # # Notice that the only difference is that the `model` parameter must not be `None`. # # **Postprocessing:** `postprocessor.py` should define `postprocess` as follows: # ``` # def postprocess(output_dict, output_shape): # ... # return {output_layer_1: data_1, ..., output_layer_n: data_n} # ``` # The inputs are defined as follows: # 1. `output_dict`: An output dictionary mapping output layer name to associated output data. In reality, this should only be a dictionary of one output layer key. # 2. `output_shape`: A tuple specifying the shape of the output. # # Notice that the only difference is that the `output_shape` parameter must not be `None`. # ## Section 2.3: Defining Conversion Scripts # # In this section, we will show you how to define your conversion scripts. Recall in Example 1 where we learned how to convert models to popular frameworks like Tensorflow or ONNX and convert them using OpenVINO's model optimizer. Instead of doing these steps separately, Open Seismic has provided a pipeline for conversion and optimization before running inference. However, we need to learn how to define those conversion scripts. # # In our system, we ask that our conversion scripts include: # 1. An .sh file for calling a Python conversion script with appropriate parameters # 2. A Python conversion script that will convert the original model to a popular framework equivalent # # ### Conversion.sh Script # Use below's code snippet as your conversion.sh script: # ``` # # #!/bin/bash # # for ARGUMENT in "$@" # do # # KEY=$(echo $ARGUMENT | cut -f1 -d=) # VALUE=$(echo $ARGUMENT | cut -f2 -d=) # # case "$KEY" in # *) ARGS="$ARGS $KEY" ;; # esac # done # # python3 $PWD/path/to/convert.py $ARGS # ``` # # The only thing you need to edit is the path to the conversion Python script. Also note that this path must be from the perspective of your mounted volume when using Open Seismic's Docker container. Finally, the arguments for the Python conversion script will be read via the .sh for loop. You can control the arguments passed to the Python conversion script via the JSON config that you will also need to specify. JSON configuration and other usage topics surrounding Open Seismic's Docker container is covered in Example 3! # # ### Conversion.py Script # # The Python conversion script needs to read arguments from the commandline, so the argparse library is useful in this scenario. It might also be helpful to specify one of the arguments as the path to the converted graph written to disk. This can make writing the JSON config file easier, since you can specify the output path as the input path for the model optimizer to look at. # ## Summary # # Congratulations! You have finished Example 2. This example was mainly to prepare you for Example 3 where we will put this knowledge into action and use the defined scripts in Open Seismic. Here is what you have learned in this example: # 1. The purpose of each inference task. # 2. The signatures, return values, and purposes for each required function and class. # # If you need an example of the scripts talked about in this example, please go to the directory `examples/assets/example3/assets/example3_assets`. Look in sub-directories `example3_optimization` for conversion scripts, and look in `example3_scripts` for preprocessing, postprocessing, and model scripts.
examples/Example2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # ディープラーニングに必要な数学と NumPy の操作 # # 1. NumPy の基本 # ## NumPy のインポート import numpy as np # ## ndarray による1次元配列の例 a1 = np.array([1, 2, 3]) # 1次元配列を生成 print('変数の型:',type(a1)) print('データの型 (dtype):', a1.dtype) print('要素の数 (size):', a1.size) print('形状 (shape):', a1.shape) print('次元の数 (ndim):', a1.ndim) print('中身:', a1) # ## ndarray による1次元配列の例 a2 = np.array([[1, 2, 3],[4, 5, 6]], dtype='float32') # データ型 float32 の2次元配列を生成 print('データの型 (dtype):', a2.dtype) print('要素の数 (size):', a2.size) print('形状 (shape):', a2.shape) print('次元の数 (ndim):', a2.ndim) print('中身:', a2) # # 2. ベクトル(1次元配列) # ## ベクトル a の生成(1次元配列の生成) a = np.array([4, 1]) # ## ベクトルのスカラー倍 for k in (2, 0.5, -1): print(k * a) # ## ベクトルの和と差 b = np.array([1, 2]) # ベクトル b の生成 print('a + b =', a + b) # ベクトル a とベクトル b の和 print('a - b =', a - b) # ベクトル a とベクトル b の差 # # 3. 行列(2次元配列) # ## 行列を2次元配列で生成 A = np.array([[1, 2], [3 ,4], [5, 6]]) B = np.array([[5, 6], [7 ,8]]) print('A:\n', A) print('A.shape:', A.shape ) print() print('B:\n', B) print('B.shape:', B.shape ) # ## 行列Aの i = 3, j = 2 にアクセス print(A[2][1]) # ## A の転置行列 print(A.T) # ## 行列のスカラー倍 print(2 * A) # ## 行列の和と差 print('A + A:\n', A + A) # 行列 A と行列 A の和 print() print('A - A:\n', A - A) # 行列 A と行列 A の差 # ## 行列 A と行列 B の和 print(A + B) # ## 行列の積 print(np.dot(A, B)) # ## 積 BA print(np.dot(B, A)) # ## アダマール積 A $\circ$ A print(A * A) # ## 行列 X と行ベクトル a の積 X = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) a = np.array([[1, 2, 3, 4, 5]]) print('X.shape:', X.shape) print('a.shape:', a.shape) print(np.dot(X, a)) # ## 行列 X と列ベクトル a の積 X = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) a = np.array([[1], [2], [3], [4], [5]]) print('X.shape:', X.shape) print('a.shape:', a.shape) Xa = np.dot(X, a) print('Xa.shape:', Xa.shape) print('Xa:\n', Xa) # ## NumPy による行列 X と1次元配列の積 X = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) a = np.array([1, 2, 3, 4, 5]) # 1次元配列で生成 print('X.shape:', X.shape) print('a.shape:', a.shape) Xa = np.dot(X, a) print('Xa.shape:', Xa.shape) print('Xa:\n', Xa) import numpy as np np.array([1, 0.1]) # # 4. ndarray の 軸(axis)について # ## Aの合計を計算 np.sum(A) # ## axis = 0 で A の合計を計算 print(np.sum(A, axis=0).shape) print(np.sum(A, axis=0)) # ## axis = 1 で A の合計を計算 print(np.sum(A, axis=1).shape) print(np.sum(A, axis=1)) # ## np.max 関数の利用例 Y_hat = np.array([[3, 4], [6, 5], [7, 8]]) # 2次元配列を生成 print(np.max(Y_hat)) # axis 指定なし print(np.max(Y_hat, axis=1)) # axix=1 を指定 # ## argmax 関数の利用例 print(np.argmax(Y_hat)) # axis 指定なし print(np.argmax(Y_hat, axis=1)) # axix=1 を指定 # # 5. 3次元以上の配列 # ## 行列 A を4つ持つ配列の生成 A_arr = np.array([A, A, A, A]) print(A_arr.shape) # ## A_arr の合計を計算 np.sum(A_arr) # ## axis = 0 を指定して A_arr の合計を計算 print(np.sum(A_arr, axis=0).shape) print(np.sum(A_arr, axis=0)) # ## axis = (1, 2) を指定して A_arr の合計を計算 print(np.sum(A_arr, axis=(1, 2)))
notebooks/Chapter03/math_numpy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={} colab_type="code" id="OG2JlAXx3VoJ" #Declare a string and store it in a variable. st="hello" #Check the type and print the id of the same. print("type=",type(st)) print("id=",id(st)) # + colab={} colab_type="code" id="wPxm3G8W3dqN" #Which are valid/invalid strings 1. 'This is Python class' #valid valid/invalid 2. "This is Python class" #valid valid/invalid 3. '''This is Python class''' #valid valid/invalid 4. """This is Python class""" #valid valid/invalid 5. 'This is Python's class' #invalid valid/invalid 6. "Learnbay provides "Java", "Python" classes" #invalid valid/invalid 7. "Learnbay provides 'Java', 'Python' classes" valid/invalid #valid 8. "This is Python's class" valid/invalid #valid 9. """Learnbay provides "Java", "Python" classes""" #valid valid/invalid 10. '''Learnbay provides "Java", "Python" classes''' #valid valid/invalid # 11. '''Learnbay provides "Java", "Python" #valid classes''' valid/invalid 12. 'This is Python class' #invalid valid/invalid # + colab={} colab_type="code" id="Drx8fhT23g7a" #Write the code to get the output mentioned below print statement my_str = "Although that way may not be obvious at first unless you're Dutch." my_str1 = "Although that way may not be obvious at first unless you're Dutch." print(len(my_str)) #output:- The length of my_str is 66 print(my_str is my_str1) #output:- id of my_str and my_str1 is same? - True print("type of my_str",type(my_str)) #output:- Type of my_str is: str # + colab={} colab_type="code" id="403e-I3A3lCO" #Indexing my_str = "Although 8 that way may not be obvious at first unless you're Dutch" #Write the code to get the output,instructions are mentioned below print statement. use indexing print("The first character in my_str is:",my_str[0]) #output:- The first character in my_str is: A #Note:- Use positive indexing print("The first character in my_str is:",my_str[-len(my_str)]) #output:- The first character in my_str is: h #Note:- Use len() function. print("The character at index 10 in my_str is:",my_str[10]) #output:- The character at index 10 in my_str is: c #Note:- Use positive indexing print("The last character in my_str is:",my_str[-1]) #output:- The last character in my_str is: h #Note:- Use negative indexing. print("The last character in my_str is:",my_str[len(my_str)-1]) #output:- The last character in my_str is: h #Note:- Use len() function. print("The character at index 9 in my_str is:",my_str[9]) #output:- The character in my_str is: 8 #Note:- Use positive index # + colab={} colab_type="code" id="NK_QdtsM3luu" #Slicing my_str = "Although that way may not be obvious at first unless you're Dutch." #Write the code to get the output,instructions are mentioned below print statement. use slicing print("You have sliced:",my_str[::]) #output:- You have sliced: Although that way may not be obvious at first unless you're Dutch.Without begin, end and step print("You have sliced:",my_str[0:len(my_str)]) #output:- You have sliced: Although that way may not be obvious at first unless you're Dutch.with begin as 0 end using len and without step print("You have sliced:",my_str[::1]) #output:- You have sliced: Although that way may not be obvious at first unless you're Dutch.without begin and end but using step print("You have sliced:",my_str[0:len(my_str):1]) #output:- You have sliced: Although that way may not be obvious at first unless you're Dutch.With begin, end and step print("You have sliced:",my_str[0:len(my_str):-1]) #output:- You have sliced: .with using begin and end using postive values and step as negative values. #Slicing command should print empty string. print("You have sliced:",my_str[0:len(my_str):2]) #output:- You have sliced: Atog htwymyntb biu tfrtuls o'eDth print("You have sliced:",my_str[0:len(my_str):3]) #output:- You have sliced: Ahgttam tebo r lsorDc print("You have sliced:",my_str[::-1]) #output:- You have sliced: .hctuD er'uoy sselnu tsrif ta suoivbo eb ton yam yaw taht hguohtlA. Use only step print("You have sliced:",my_str[-1:-len(my_str)-1:-1]) #output:- You have sliced: .hctuD er'uoy sselnu tsrif ta suoivbo eb ton yam yaw taht hguohtlA. Use begin end and step. print("You have sliced:",my_str[::-2]) #output:- You have sliced: .cu ruysen si asovoe o a a athuhl. use only step print("You have sliced:",my_str[-1:-len(my_str)-1:-2]) #output:- You have sliced: .cu ruysen si asovoe o a a athuhl. use begin, end and step. print(my_str[10:17:-1]) #What will be the output? #Nothing will be printed print("You have sliced:",my_str[-49:-56:-1]) #output:- You have sliced: yaw ta, Using begin, end and step. print("You have sliced:",my_str[49:56:1]) #output:- You have sliced: ess you. Using begin, end and step. # + colab={} colab_type="code" id="qUSYa5x-3n5j" #Basic operation on string str1 = 'Learnbay' str2 = 'Python' #Write the code to get the output,instructions are mentioned below. #Output is: Learnbay Python print(str1+str2) #Error: TypeError: can only concatenate str (not "int") to str #Error: TypeError: can only concatenate str (not "float") to str #Find below Output #Output is: LearnbayLearnbayLearnbay print(str1 * 3) #Error: TypeError: can't multiply sequence by non-int of type 'float' #Error: TypeError: can't multiply sequence by non-int of type 'str' # + colab={} colab_type="code" id="gREffmnr3s-p" #Find below Output str1 = 'Python' str2 = 'Python' str3 = 'Python$' str4 = 'Python$' #print True by using identity operator between str1 and str2 print(str1 is str2) #print False by using identity operator between str1 and str3 print(str1 is str3) #print False by using identity operator between str4 and str3 print(str4 is str3) #Check if P is available in str1 and print True by using membership operator print("P" in str1) #Check if $ is available in str3 and print True by using membership operator print("$" in str3) #Check if N is available in str3 and print False by using membership operator print("N" in str3) # + colab={} colab_type="code" id="QNFjxDr73u2H" #Complete the below code str1 = 'This is Python class' #write the code to replace 'Python' with 'Java' and you should get below error. #TypeError: 'str' object does not support item assignment. str1['Python']='Java' # + colab={} colab_type="code" id="-JgFbPmn3w3D" str1 = 'A' str2 = 'A' #Compare str1 and str2 and print True using comparison operator print(str1<=str2) #Compare str1 and str2 and print True using equality operator print(str1==str2) #Compare str1 and str2 and print False using equality operator print(str1!=str2) #Compare str1 and str2 and print False using comparison operator print(str1<str2) # + colab={} colab_type="code" id="fJ46_L-53yhW" str1 = 'A' str2 = 'a' #Compare str1 and str2 and print True using comparison operator print(str1<str2) #Compare str1 and str2 and print True using equality operator print(str1!=str2) #Compare str1 and str2 and print False using equality operator print(str1==str2) #Compare str1 and str2 and print False using comparison operator print(str1>str2) # + colab={} colab_type="code" id="e-Lr9va330gi" str1 = 'A' str2 = 65 #Compare str1 and str2 using comparison operator and it should give below error. #Error: TypeError: '>=' not supported between instances of 'str' and 'int' print(str1>=str2) #Compare str1 and str2 and print True using equality operator print(str1!=str2) #Compare str1 and str2 and print False using equality operator print(str1==str2) # + colab={} colab_type="code" id="JO04jmpN32Im" str1 = 'Python' str2 = 'Python' #Compare str1 and str2 and print True using comparison operator print(str1<=str2) #Compare str1 and str2 and print True using equality operator print(str1==str2) #Compare str1 and str2 and print False using equality operator print(str1!=str2) #Compare str1 and str2 and print False using comparison operator print(str1<str2) # + colab={} colab_type="code" id="nmVAYYC_35ip" str1 = 'Python' str2 = 'python' #Compare str1 and str2 and print True using comparison operator print(str1<str2) #Compare str1 and str2 and print True using equality operator print(str1!=str2) #Compare str1 and str2 and print False using equality operator print(str1==str2) #Compare str1 and str2 and print False using comparison operator print(str1>str2) # + colab={} colab_type="code" id="7ulv5ith37OJ" a = 'Python' b = '' #Apply logical opereators (and, or & not) on above string values and observe the output. print(a and b) # o/p--> "Python"(T) and ''(False) =''(False) print(a or b) #o/p--->"Python"(T) or ''(False) ="Python"(T) print(not a) #o/p----> not "python"(T)=False print(not b) #o/p----> not ""(False)=True print() # + colab={} colab_type="code" id="Yg_gsZBL383n" a = '' b = '' #Apply logical opereators (and, or & not) on above string values and observe the output. print(a and b) # o/p--> ''(False) and ''(False) =''(False) print(a or b) # o/p--> ""(False) or ''(False) =''(False) print(not a) #o/p---> not ''(False)=True # + colab={} colab_type="code" id="cIWkP9Hf3-q5" a = 'Python' b = 'learnbay' #Apply logical opereators (and, or & not) on above string values and observe the output. print(a and b) # o/p--> "Python"(T) and 'Learnbay'(True) ='Learnbay'(True) print(a or b) #o/p--> "Python"(T) or 'Learnbay'(True) ='Python'(True) print(not a) #o/p----> not "python"(T)=False # + colab={} colab_type="code" id="Y0Ot_E704AX5" my_str = "Although 8 that way may not be obvious at first unless you're Dutch" #Write the code to get the total count of 't' in above string. Use find() and index() method. print(my_str.count('t',my_str.find('t'))) print(my_str.count('t',my_str.index('t'))) #Write the code to get the index of '8' in my_str. Use find() and index() method. print(my_str.find('8')) print(my_str.index('8')) #What will be the output of below code? #print(my_str.find('the')) # o/p : # -1 (becaz substring is not in input string) #print(my_str.index('the')) # o/p : # value error (becaz substring is not in input string) print(my_str.find('t', 9, 15)) print(my_str.rfind('u')) print(my_str.rindex('u')) # + colab={} colab_type="code" id="Gommq59Q4CMi" #W A P which applies strip() method if any string, which will be taken from user, starts and ends with space, or applies #rrstrip() method if that string only ends with space or applies lstrip() method if that string only starts with a space. #For example:- #input:- ' Python ' #output:- 'Python' st=input("enter any string:\n") if st[0]==' 'and st[-1]==' ': print(st.strip()) #input:- ' Python' #output:- 'Python' elif st[0]==' ': print(st.lstrip()) #input:- 'Python ' #output:- 'Python' elif st[-1]==' ': print(st.rstrip()) # + colab={} colab_type="code" id="9IUy-cpS4Dtt" my_str = "Although 8 that way may not be obvious at first unless you're Dutch" #Write the code to convert all alphabets in my_str into upper case. print(my_str.upper()) #Write the code to convert all alphabets in my_str into lower case. print(my_str.lower()) #Write the code to swap the cases of all alphabets in my_str.(lower to upper and upper to lower) print(my_str.swapcase()) # + colab={} colab_type="code" id="-BjS-z674HKW" #Write the code which takes one string from user and if it starts with small case letter then convert it to corresponding #capital letter otherwise if starts with capital letters then convert first character of every word in that string into capital. st=input("enter any string:\n") if st[0].isupper(): ot=st.title() print(ot) else: st=st.capitalize() ot=st.title() print(ot) # + colab={} colab_type="code" id="-MCuDy5J4JQS" #Take a string from user and check if it is:- # 1. alphanumeric # 2. alphabets # 3. digit # 4. all letters are in lower case # 5. all letters are in upper case # 6. in title case # 7. a space character # 8. numeric # 9. all number elements in string are decimal ipt=input("enter any string:\n") if ipt.isalnum(): print("given string is alphanumeric") if ipt.isalpha(): print("given string is in alphabets") if ipt.isdigit(): print("given string is in digits") if ipt.isupper(): print("given string is in uppercase") if ipt.islower(): print("given string is in lowercase") if ipt.istitle(): print("given string satisfies title") if ipt.isspace(): print("given string is space char") if ipt.isnumeric(): print("given string is in numeric") if ipt.isdecimal(): print("given string is in decimal") # + colab={} colab_type="code" id="tiTN-4ik4KAG" #W A P which takes a string as an input and prints True if the string is valid identifier else returns False. #Sample Input:- 'abc', 'abc1', 'ab1c', '1abc', 'abc$', '_abc', 'if' st=input("enter any string:\n") if st.isidentifier(): print(f"{st} is a valid identifier") else: print(f"{st} is a not a valid identifier") # + colab={} colab_type="code" id="tAMkSIN84MPe" #What will be output of below code? s = chr(65) + chr(97) print(s.isprintable()) #o/p : chr(65)=A,chr(97)=a ; s=A+a--->Aa---->which is printable s = chr(27) + chr(97) print(s.isprintable()) s = '\n' print(s.isprintable()) #o/p:False becaz \n is executable but not printable s = '' print(s.isprintable()) # + colab={} colab_type="code" id="pU9Os0mD4Pk1" #What will be output of below code? my_string = ' ' print(my_string.isascii()) #o/p: True becaz space is an ascii char my_string = 'Studytonight' print(my_string.isascii()) # o/p:true becaz every char in string is in ascii my_string = 'Study tonight' print(my_string.isascii()) #o/p:true becaz every char in string is in ascii my_string = 'Studytonight@123' print(my_string.isascii()) #o/p:true becaz every char in string is in ascii my_string = '°' print(my_string.isascii()) #o/p:false becaz every char in string is not in ascii my_string = 'ö' print(my_string.isascii()) #o/p:false becaz every char in string is not in ascii # + colab={} colab_type="code" id="VsLV8FF74QTB" #What will be the output of below code? firstString = "<NAME>" secondString = "<NAME>" if firstString.casefold() == secondString.casefold(): print('The strings are equal.') else: print('The strings are not equal.') # o/p: # strings are equal becaz casefold can cnvert any special chr into lower case and after conversion firststr is equal to secondstr # + colab={} colab_type="code" id="1m0U7jLa4Wjf" #Write the code to get below output #O/P 1:- python** (using ljust method) ipt="python".ljust(8,"*") print(ipt) #Write the code to get below output #O/P 1:- **python (using rjust method) ipt="python".rjust(8,'*') print(ipt) #Write the code to get below output #O/P 1:- **python** (using rjust method) ipt="python".rjust(8,'*') print(ipt.ljust(10,'*')) # + colab={} colab_type="code" id="cRVkvW6s4YKK" #Write a Python program to find the length of the my_str:- #Input:- 'Write a Python program to find the length of the my_str' #Output:- 55 my_str='Write a Python program to find the length of the my_str' print("length of input is: ",len(my_str)) # + colab={} colab_type="code" id="SjABWI284Zuz" #Write a Python program to find the total number of times letter 'p' is appeared in the below string:- Input='<NAME> picked a peck of pickled peppers.' #Output:- 9 char=input("enter any substring to count:\n") print(Input.count(char)) # + colab={} colab_type="code" id="-iZtqbEo4bQp" #Write a Python Program, to print all the indexes of all occurences of letter 'p' appeared in the string:- #Input:- '<NAME> picked a peck of pickled peppers.' #Output:- # 0 # 6 # 8 # 12 # 21 # 29 # 37 # 39 # 40 count=0 for i in range(len(Input)-1): if Input[i]==char: print(i) count+=1 if count==0: print("given char is not a substring") # + colab={} colab_type="code" id="_A8Eu8f84daM" #Write a python program to find below output:- Input='<NAME> picked a peck of pickled peppers.' #Output:- ['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers'] print(Input.split()) # + colab={} colab_type="code" id="juh7tQuL4fNc" #Write a python program to find below output:- #Input:- '<NAME> picked a peck of pickled peppers.' #Output:- 'peppers pickled of peck a picked piper peter' st=Input.split() print(" ".join(st[::-1])) # + colab={} colab_type="code" id="aaHQYz194fW7" #Write a python program to find below output:- #Input:- '<NAME> picked a peck of pickled peppers.' #Output:- 'sreppep delkcip fo kcep a dekcip repip retep' print("".join(reversed(Input))) # + colab={} colab_type="code" id="LSgj9glC4feI" #Write a python program to find below output:- #Input:- '<NAME> picked a peck of pickled peppers.' #Output:- 'retep repip dekcip a kcep fo delkcip sreppep' st='<NAME> picked a peck of pickled peppers.' ot_lst=[] ot_str="" for i in st[-1:-len(st)-1:-1]: if i==' ': ot_lst.append(ot_str) ot_str="" else: ot_str+=i #print(ot_lst) ot_lst.append(ot_str) fl_lst='' for j in ot_lst[-1:-len(ot_lst)-1:-1]: fl_lst+=" "+j print(fl_lst) # + colab={} colab_type="code" id="WUxPAkY94foo" #Write a python program to find below output:- #Input:- '<NAME> picked a peck of pickled peppers.' #Output:- '<NAME> Picked A Peck Of Pickled Peppers' print(Input.title()) # + colab={} colab_type="code" id="IT1NSPxA4mww" #Write a python program to find below output:- #Input= '<NAME> Picked A Peck Of Pickled Peppers.' #Output:- '<NAME> picked a peck of pickled peppers' st='<NAME> Picked A Peck Of Pickled Peppers.' ot_lst=[] ot_str='' fl_lst="" for i in st: if i==' 'or i==".": fl_lst+=" "+chr(ord(ot_str[0])+32)+ot_str[1:] ot_str="" else: ot_str+=i print(fl_lst) # + colab={} colab_type="code" id="3Gg65vSc4m3C" #Write a python program to implement index method. If sub_str is found in my_str then it will print the index # of first occurrence of first character of matching string in my_str:- Input = '<NAME> Picked A Peck Of Pickled Peppers.'#, sub_str = 'Pickl' #Output:- 29 sub_str = 'Pickl' print(Input.rfind(sub_str)) # + colab={} colab_type="code" id="iFRhp_JI4m6k" #Write a python program to implement replace method. If sub_str is found in my_str then it will replace the first #occurrence of sub_str with new_str else it will will print sub_str not found:- Input='<NAME> Picked A Peck Of Pickled Peppers.'#, sub_str = 'Peck', new_str = 'Pack' #Output:- '<NAME> Picked A Pack Of Pickled Peppers.' sub_str=input("enter sub_str to be replaced:\n") new_str=input("enter new_str to replace:\n") lst=Input.split() if sub_str in lst: print(Input.replace(sub_str,new_str)) else: print("substring not found") # + colab={} colab_type="code" id="dQ9YhBBc4m9V" #Write a python program to find below output (implements rjust and ljust):- Input = '<NAME> Picked A Peck Of Pickled Peppers.'#, sub_str = 'Peck', #Output:- '*********************Peck********************' sub_str ='Peck' #lnt=len(Input)- ltlen=Input.index(sub_str)+len(sub_str)-1 rj=sub_str.rjust(ltlen,"*") lj=rj.ljust(len(Input),"*") print(lj) # + colab={} colab_type="code" id="w37BRLdt4tYT" #Write a python program to find below output (implement partition and rpartition):- Input= 'This is Python class'#, sep = 'is', #Output:- ['This', 'is', 'Python class'] lst=list(Input.rpartition('is')) print(lst) # + colab={} colab_type="code" id="W64gCpeu4vaF" #Write a python program which takes one input string from user and encode it in below format:- 1. #Input:- 'Python' #Output:- 'R{vjqp' ipt1='Python' opt1='' for i in ipt1: opt1+=chr(ord(i)+2) print(opt1) # 2. #Input:- 'Python' #Output:- 'Rwvfql' ipt2='Python' opt2='' for i in ipt2: if ipt2.index(i)%2==0: opt2+=chr(ord(i)+2) else: opt2+=chr(ord(i)-2) print(opt2) # 121-119 # # 3. #Input:- 'Python' #Output:- 'R{vfml' ipt3='Python' opt3='' for i in ipt3: if ipt3.index(i)<3: opt3+=chr(ord(i)+2) else: opt3+=chr(ord(i)-2) print(opt3)
Swarna/String_Assignment_Swarna.ipynb