text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Load data ``` import os, glob import cv2 import numpy as np import matplotlib.pyplot as plt from multiprocessing import Pool import functools %matplotlib inline ``` ## video2npy ``` import skvideo.io import skvideo.datasets vid_root = '/data/dataset/UCF/' vid_ls = glob.glob(vid_root+"v_BabyCrawling**.avi") vid_ls.sort() print(len(vid_ls)) print(vid_ls[:5]) videogen = skvideo.io.vreader(vid_ls[55]) for i, frame in enumerate(videogen): #print(i, frame.shape) if i == 4: print(type(frame)) print(frame[:, 40:280, :].shape) plt.imshow(frame) def get_frames_npy(vid_path, out_path, length = 7, skip = 2, pre = 1): if not os.path.exists(out_path): os.mkdir(out_path) vid_name = os.path.basename(vid_path).split('.')[0] videogen = skvideo.io.vreader(vid_path) frames_lst = [cv2.resize(frame[:, 40:280, :], (256, 256)) for i, frame in enumerate(videogen) if i%skip == 0] n = 0 for i in range(int(len(frames_lst)/(length*2))): A = np.asarray(frames_lst[i:i+length]) B = np.asarray(frames_lst[i+length-pre:i+length*2-pre]) v = np.asarray([A,B]) v = np.transpose(v , (0,4,1,2,3)) np.save('{}{}_{}.npy'.format(out_path, vid_name, i),v) n += 1 return n ``` ### 超参数输出 ``` npy_path = '/data/dataset/ucf-npy/' vid_root = '/data/dataset/UCF/' vid_ls = glob.glob(vid_root+"v_BabyCrawling**.avi") vid_ls.sort() total_npy = 0 print('共有视频:{}'.format(len(vid_ls))) ## Hyperparameter N = 76 # how many videos would be used length = 7 skip = 2 pre = 1 if N == '': N = len(vid_ls) if N > len(vid_ls): raise ValueError("处理视频数大于视频总数") with Pool(12) as p: p.map(functools.partial(get_frames_npy, out_path = npy_path, length = length, skip = skip, pre = 1), vid_ls[:N]) print(len(os.listdir(npy_path))) ``` ## 输出检验 ``` os.listdir(npy_path) f_t = npy_path+os.listdir(npy_path)[3] a= np.load(f_t) plt.figure(1) plt.subplot(121) plt.imshow(np.transpose(a[0], (1,2,3,0))[0]) plt.subplot(122) plt.imshow(np.transpose(a[1], (1,2,3,0))[0]) rm -rf /data/dataset/ucf-npy/ ``` ## images2npy ``` def get_one_clip(lst,index ,skip ,length ): return lst[index:index+length*skip:skip] def get_clips(img_lst,skip ,length): clips =[get_one_clip(img_lst,i,skip,length) for i in range(len(img_lst)) if len(get_one_clip(img_lst,i,skip,length)) == length ] return clips def get_pair(img_lst,pre ,skip ,length): A = get_clips(img_lst[:][:-pre],skip ,length) B = get_clips(img_lst[pre:],skip ,length) return A,B read_ = lambda x : cv2.resize(cv2.imread(x)[:, int(1242/2-375/2):int(1242/2+375/2),::-1],(256,256)) def gen_np(c): # print(c) img1 = [ read_(i) for i in c[0]] img2 = [ read_(i) for i in c[1]] v = np.asarray([img1,img2]) v = np.transpose(v , (0,4,1,2,3)) # v.transpose(0,4,1,2,3) return v def dump(img_lst,dirpath='data' ,start =0 ,skip = 2 ,length =7 ,pre =2): a,b = get_pair(img_lst,pre ,skip ,length) task = [ (i,j) for i ,j in zip(a,b)] for i ,j in enumerate(task): v = gen_np(j) np.save('{}{}.npy'.format(dirpath,i+start),v) # return def f(data_path): start = 0 img_lst = glob.glob(data_path+"**.png") img_lst.sort() dump(img_lst,'video/{}{}'.format(*data_path.split('/')[-3:-1]),start,2 ,7 ,2) f_lst = glob.glob('/data/dataset/depthdata/vkitti_1.3.1_rgb/**/**/') with Pool(12) as p: p.map(f,f_lst) fi = 'video/000115-deg-left0.npy' a= np.load(fi) plt.imshow(np.transpose(a[0],(1,2,3,0))[2]) ``` ---
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import math from scipy import stats import pickle from causality.analysis.dataframe import CausalDataFrame from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import matplotlib.font_manager as fm import plotly import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) ``` Open the data from past notebooks and correct them to only include years that are common between the data structures (>1999). ``` with open('VariableData/money_data.pickle', 'rb') as f: income_data, housing_data, rent_data = pickle.load(f) with open('VariableData/demographic_data.pickle', 'rb') as f: demographic_data = pickle.load(f) with open('VariableData/endowment.pickle', 'rb') as f: endowment = pickle.load(f) with open('VariableData/expander.pickle', 'rb') as f: expander = pickle.load(f) endowment = endowment[endowment['FY'] > 1997].reset_index() endowment.drop('index', axis=1, inplace=True) demographic_data = demographic_data[demographic_data['year'] > 1999].reset_index() demographic_data.drop('index', axis=1, inplace=True) income_data = income_data[income_data['year'] > 1999].reset_index() income_data.drop('index', axis=1, inplace=True) housing_data = housing_data[housing_data['year'] > 1999].reset_index() housing_data.drop('index', axis=1, inplace=True) rent_data = rent_data[rent_data['year'] > 1999].reset_index() rent_data.drop('index', axis=1, inplace=True) ``` Define a function to graph (and perform linear regression on) a given set of data. ``` def grapher(x, y, city, title, ytitle, xtitle, filename): slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) fit = slope * x + intercept trace0 = go.Scatter( x = x, y = y, mode = 'markers', name=city, marker=go.Marker(color='#D2232A') ) fit0 = go.Scatter( x = x, y = fit, mode='lines', marker=go.Marker(color='#AC1D23'), name='Linear Fit' ) data = [trace0, fit0] layout = go.Layout( title = title, font = dict(family='Gotham', size=12), yaxis=dict( title=ytitle ), xaxis=dict( title=xtitle) ) fig = go.Figure(data=data, layout=layout) return iplot(fig, filename=filename) ``` Investigate the connection between the endowment's value and the Black population in Cambridge, controlling for rent and housing prices. ``` x = pd.to_numeric(endowment['Value ($B)']).as_matrix() y = pd.to_numeric(demographic_data['c_black']).as_matrix() z1 = pd.to_numeric(rent_data['cambridge']).as_matrix() z2 = pd.to_numeric(housing_data['cambridge']).as_matrix() X = CausalDataFrame({'x': x, 'y': y, 'z1': z1, 'z2': z2}) plt.rcParams['font.size'] = 10 gotham_black = fm.FontProperties(fname='/Users/hakeemangulu/Library/Fonts/Gotham Black Regular.ttf') gotham_book = fm.FontProperties(fname='/Users/hakeemangulu/Library/Fonts/Gotham Book Regular.otf') endow_black = grapher(x, y, "Cambridge", "The Correlation Between Endowment and Black Population", "Black Population of Cambridge", "Endowment ($B)", "endow_black") causal_endow_black = X.zplot(x='x', y='y', z=['z1', 'z2'], z_types={'z1': 'c', 'z2': 'c'}, kind='line', color="#D2232A") fig = causal_endow_black.get_figure() fig.set_size_inches(9, 5.5) ax = plt.gca() ax.set_frame_on(False) ax.get_yaxis().set_visible(False) ax.legend_.remove() ax.set_title("The Controlled Correlation Between Endowment (Billions of Dollars) and Black Population", fontproperties=gotham_black, size=10, color="#595959") ax.set_xlabel("Endowment", fontproperties=gotham_book, fontsize=10, color="#595959") for tick in ax.get_xticklabels(): tick.set_fontproperties(gotham_book) tick.set_fontsize(10) tick.set_color("#595959") fig.savefig('images/black_endow.svg', format='svg', dpi=1200, bbox_inches='tight') ``` Investigate the connection between the endowment's value and the housing prices in Cambridge, controlling for growth of the population. ``` x = pd.to_numeric(endowment['Value ($B)']).as_matrix() y = pd.to_numeric(housing_data['cambridge']).as_matrix() z1 = pd.to_numeric(demographic_data['c_white']).as_matrix() z2 = pd.to_numeric(demographic_data['c_poc']).as_matrix() X = CausalDataFrame({'x': x, 'y': y, 'z1': z1, 'z2': z2}) endow_housing = grapher(x, y, "Cambridge", "The Correlation Between Endowment and Housing Prices", "Housing Prices in Cambridge", "Endowment ($B)", "endow_housing") causal_endow_housing = X.zplot(x='x', y='y', z=['z1', 'z2'], z_types={'z1': 'c', 'z2': 'c'}, kind='line', color="#D2232A") fig = causal_endow_housing.get_figure() fig.set_size_inches(9, 5.5) ax = plt.gca() ax.set_frame_on(False) ax.get_yaxis().set_visible(False) ax.legend_.remove() ax.set_title("The Controlled Correlation Between Endowment (Billions of Dollars) and Housing Prices", fontproperties=gotham_black, size=10, color="#595959") ax.set_xlabel("Endowment", fontproperties=gotham_book, fontsize=10, color="#595959") for tick in ax.get_xticklabels(): tick.set_fontproperties(gotham_book) tick.set_fontsize(10) tick.set_color("#595959") fig.savefig('images/housing_endow.svg', format='svg', dpi=1200, bbox_inches='tight') ``` Investigate the connection between the endowment's value and the rent prices in Cambridge, controlling for growth of the population. ``` x = pd.to_numeric(endowment['Value ($B)']).as_matrix() y = pd.to_numeric(rent_data['cambridge']).as_matrix() z1 = pd.to_numeric(demographic_data['c_white']).as_matrix() z2 = pd.to_numeric(demographic_data['c_poc']).as_matrix() X = CausalDataFrame({'x': x, 'y': y, 'z1': z1, 'z2': z2}) endow_rent = grapher(x, y, "Cambridge", "The Correlation Between Endowment and Rent", "Rent in Cambridge", "Endowment ($B)", "endow_rent") causal_endow_rent = X.zplot(x='x', y='y', z=['z1', 'z2'], z_types={'z1': 'c', 'z2': 'c'}, kind='line', title='The Controlled Correlation Between Endowment and Rent') fig = causal_endow_rent.get_figure() fig.set_size_inches(9, 5.5) ax = plt.gca() ax.set_frame_on(False) ax.get_yaxis().set_visible(False) ax.legend_.remove() ax.set_title("The Controlled Correlation Between Endowment (Billions of Dollars) and Housing Prices", fontproperties=gotham_black, size=10, color="#595959") ax.set_xlabel("Endowment", fontproperties=gotham_book, fontsize=10, color="#595959") for tick in ax.get_xticklabels(): tick.set_fontproperties(gotham_book) tick.set_fontsize(10) tick.set_color("#595959") fig.savefig('images/rent_endow.svg', format='svg', dpi=1200, bbox_inches='tight') ``` Investigate the connection between the amount Harvard pays the city of Cambridge per year (PILOT) and the rent prices in Cambridge, controlling for growth of the population. ``` x = pd.to_numeric(expander['Payments to City']).as_matrix() y = pd.to_numeric(rent_data['cambridge']).as_matrix() # Remove the last two elements of the other arrays – PILOT data is not sufficient otherwise. y = y[:-2].copy() z1 = pd.to_numeric(demographic_data['c_white']).as_matrix() z1 = z1[:-2].copy() z2 = pd.to_numeric(demographic_data['c_poc']).as_matrix() z2 = z2[:-2].copy() X = CausalDataFrame({'x': x, 'y': y, 'z1': z1, 'z2': z2}) pilot_rent = grapher(x, y, "Cambridge", "The Correlation Between Harvard's PILOT and Rent", "Rent in Cambridge", "PILOT ($)", "pilot_rent") causal_endow_rent = X.zplot(x='x', y='y', z=['z1', 'z2'], z_types={'z1': 'c', 'z2': 'c'}, kind='line') ```
github_jupyter
# Data Mining, Preparation and Understanding Today we'll go through Data Mining, Preparation & Understanding which is a really fun one (and important). In this notebook we'll try out some important libs to understand & also learn how to parse Twitter with some help from `Twint`. All in all we'll go through `pandas`, `twint` and some more - let's start by installing them. ``` %%capture !pip install twint !pip install wordcloud import twint import pandas as pd import tqdm import nltk nltk.download('stopwords') ``` ## Tonights theme: ÅF Pöyry (and perhaps some AFRY) To be a Data Miner we need something to mine. ![alt text](https://financesmarti.com/wp-content/uploads/2018/09/Dogcoin-Mining-min.jpg) In this case it won't be Doge Coin but rather ÅF, ÅF Pöyry & AFRY. To be honest, it's not the best theme (pretty generic names ones you go ASCII which we'll do to simplify our lifes. ### What is Twint `Twint` is a really helpful library to scrape Twitter, it uses the search (i.e. not the API) and simplifies the whole process for us as users. The other way to do this would be to use either the API yourself (time-consuming to learn and also limited in calls) or to use BS4 (Beatiful Soup) which is a great python-lib to scrape websites. But I'd dare say that it is better for static content sites such as Wikipedia, Aftonbladet etc rather than Twitter etc. This all together led to the choice of `Twint` _even_ though it has a **huge** disadvantage - it does not support UTF8 from what I can find. ### What is pandas Pandas is a library to parse, understand and work with data. It's really fast using the `DataFrame` they supply. Using this `DataFrame` we can manipulate the data in different ways. It has all the functions you can imagine from both SQL and Excel, a great tool all in all. ### Bringing it all together Let's take a look at how we can use this all together! First a quick look at the Twint config. ``` """ Twint Config: Variable Type Description -------------------------------------------- Retweets (bool) - Display replies to a subject. Search (string) - Search terms Store_csv (bool) - Set to True to write as a csv file. Pandas (bool) - Enable Pandas integration. Store_pandas (bool) - Save Tweets in a DataFrame (Pandas) file. Get_replies (bool) - All replies to the tweet. Lang (string) - Compatible language codes: https://github.com/twintproject/twint/wiki/Langauge-codes (sv, fi & en supported) Format (string) - Custom terminal output formatting. Hide_output (bool) - Hide output. Rest of config: https://github.com/twintproject/twint/wiki/Configuration """ c = twint.Config() c.Query c.Search = " ÅF " c.Format = "Username: {username} | Tweet: {tweet}" c.Pandas = True c.Store_pandas = True c.Pandas_clean = True c.Show_hashtags = True c.Limit = 10 twint.run.Search(c) ``` **What do we see?** No Swedish, what so ever. This is not interesting for our usecase as all the tweets are about something else really. Let's try ÅF Pöyry instead ``` c.Search = "ÅF AFRY Pöyry" twint.run.Search(c) ``` Looking at this we have a much better result. This really shows the power of Ngrams (bigram). Let's play around some in the next box trying `@AFkarriar` as keyword and also to include `Replies` and some other fields. ``` c.Replies = True twint.run.Search(c) # Play around with params, do whatever! ``` ### Results Ok, so we have tried out a few different things we can use in `Twint`. For me `@AFkarriar` worked out best - **what was your favorite?** Let's analyze some more. ``` FILENAME = "afpoyry.csv" c = twint.Config() c.Query c.Show_hashtags = True c.Search = "ÅF" c.Lang = "sv" #c.Get_replies = True c.Store_csv = True c.Hide_output = True c.Output = FILENAME twint.run.Search(c) data = pd.read_csv(FILENAME) print(data.shape) print(data.dtypes) ``` ### Cleaning We can most likely clean some titles from here, just to make it simpler for us ``` data_less = data.filter(["tweet", "username"]) data_less.head() data_less["tweet"].head() from wordcloud import WordCloud from IPython.display import Image t = '\n'.join([x.tweet for i, x in data_less.iterrows()]) WordCloud().generate(t).to_file('cloud.png') Image('cloud.png') ``` **Stop Words** - Anyone remember? Let's remove them! NLTK is a great toolkit for just about everything in NLP, we can find a list of stopwords for most languages here, including Swedish. ``` from nltk.corpus import stopwords swe_stop = set(stopwords.words('swedish')) list(swe_stop)[:5] ``` **Stemming** - Anyone remember? Let's do it! NLTK is _the_ lib to use when you want at least _some_ swedish. But I think I've squeezed all the swedish out of NLTK that I can find right now... ``` from nltk.stem import SnowballStemmer stemmer = SnowballStemmer("swedish") stemmer.stem("hoppade") ``` **Cleaning** - Anyone remember? Let's do it! ![alt text](https://imgflip.com/s/meme/X-All-The-Y.jpg) To have a "better" word cloud we need to reduce the dimensions and keep more important words. ``` %%capture !pip install regex from string import punctuation import regex as re # bad_words = re.compile("https|http|pic|www|och|med|att|åf|pöyry|läs") http_re = re.compile("https?.*?(\w+)\.\w+(\/\s)?") whitespace_re = re.compile("\s+") punc_set = set(punctuation) def clean_punct(tweet): return ''.join([c for c in tweet if c not in punc_set]) def remove_stopwords(tweet): return " ".join([t for t in tweet.split(" ") if t not in swe_stop]) # Example of cleaning: remove punct, lowercase, https and stemming/lemmatizing # (we want to reduce the space/dimensions) def clean_text(tweet): tweet = tweet.lower() tweet = ' '.join([word for word in tweet.split() if not word.startswith('pic.')]) tweet = http_re.sub(r'\1', tweet) tweet = tweet.lower() tweet = remove_stopwords(clean_punct(tweet)).strip() tweet = whitespace_re.sub(' ', tweet) return tweet clean_text("hej där borta. hur mår du? vem vet.. Jag vet inte. http:/google.com pic.twitterlol") #data_less["tweet"] = data_less["tweet"].apply(lambda x: clean_text(x)) data_less["tweet"] from wordcloud import WordCloud from IPython.display import Image t = '\n'.join([x.tweet for i, x in data_less.iterrows()]) WordCloud().generate(t).to_file('cloud_clean.png') Image('cloud_clean.png') from collections import Counter def print_most_common(wcount, n=5): for (name, count) in wcount.most_common(n): print(f"{name}: {count}") t_hash = ' '.join([x for x in t.split() if x.startswith("#")]) hash_count = Counter(t_hash.split()) WordCloud().generate(t_hash).to_file('cloud_#.png') print_most_common(hash_count, 10) t_at = ' '.join([x for x in t.split() if x.startswith("@")]) at_count = Counter(t_at.split()) WordCloud().generate(t_at).to_file('cloud_@.png') print_most_common(at_count, 10) ``` ### WordClouds! Let's take a look at what we've got. ``` Image('cloud_clean.png') Image('cloud_no_stop.png') Image('cloud_@.png') Image('cloud_#.png') ``` ### What to do? A big problem with Swedish is that there's very few models which we can do some fun with, and our time is very limited. Further on we can do the following: 1. Look at Ngram see if we can see common patterns 2. ... ``` """ 1. Try perhaps some type of Ngrams 4. Find different shit 4. Try to find connections 5. Move over to spark (?) https://towardsdatascience.com/nlp-for-beginners-cleaning-preprocessing-text-data-ae8e306bef0f https://medium.com/@kennycontreras/natural-language-processing-using-spark-and-pandas-f60a5eb1cfc6 """ ``` ### AFRY Let's create a wordcloud & everything for AFRY. This is for you to implement fully! ``` FILENAME2 = "afry.csv" c = twint.Config() c.Query c.Show_hashtags = True c.Search = "afry" c.Lang = "sv" c.Get_replies = True c.Store_csv = True c.Hide_output = True c.Output = FILENAME2 twint.run.Search(c) data_afry = pd.read_csv(FILENAME2) t_afry = '\n'.join([x.tweet for i, x in data_afry.iterrows()]) WordCloud().generate(t_afry).to_file('cloud_afry.png') Image('cloud_afry.png') ``` ### Jonas Sjöstedt (jsjostedt) vs Jimmy Åkesson (jimmieakesson) Implementation as follows: 1. Get data for both (tip: use `c.Username` or `c.User_id` and don't forget formatting output in terminal if used) 2. Clean data 3. ?? (Perhaps wordclouds etc) 4. TfIdf 5. Join ds & shuffle, train clf 6. Testing! ## Jimmie Åkesson ``` FILENAME = "jimmie2.csv" c = twint.Config() c.Query c.Show_hashtags = True #c.Search = "ÅF" c.Username = "jimmieakesson" #c.Get_replies = True c.Store_csv = True c.Output = FILENAME twint.run.Search(c) data_jimmie = pd.read_csv(FILENAME) print(data_jimmie.shape) data_less_jimmie = data_jimmie.filter(["tweet", "username"]) data_less_jimmie.head() data_less_jimmie["tweet"] = data_less_jimmie["tweet"].apply(lambda x: clean_text(x)) data_less_jimmie.head() from wordcloud import WordCloud from IPython.display import Image t = '\n'.join([x.tweet for i, x in data_less_jimmie.iterrows()]) WordCloud().generate(t).to_file('cloud_clean_jimmie.png') Image('cloud_clean_jimmie.png') ``` ## Jonas Sjöstedt ``` FILENAME_J = "jonas.csv" c = twint.Config() c.Query c.Show_hashtags = True #c.Search = "ÅF" c.Username = "jsjostedt" #c.Get_replies = True c.Store_csv = True c.Hide_output = True c.Output = FILENAME_J twint.run.Search(c) data_jonas = pd.read_csv(FILENAME_J) print(data_jonas.shape) data_less_jonas = data_jonas.filter(["tweet", "username"]) data_less_jonas.head() data_less_jonas["tweet"] = data_less_jonas["tweet"].apply(lambda x: clean_text(x)) data_less_jonas.head() t = '\n'.join([x.tweet for i, x in data_less_jonas.iterrows()]) WordCloud().generate(t).to_file('cloud_clean_jonas.png') Image('cloud_clean_jonas.png') ``` # TfIdf ``` from sklearn.feature_extraction.text import TfidfVectorizer cv=TfidfVectorizer(ngram_range=(1,1)) word_count_vector_jonas = cv.fit_transform(data_less_jonas["tweet"]) feature_names = cv.get_feature_names() #get tfidf vector for first document first_document_vector=word_count_vector_jonas[0] #print the scores df = pd.DataFrame(first_document_vector.T.todense(), index=feature_names, columns=["tfidf"]) df.sort_values(by=["tfidf"],ascending=False) word_count_vector_jimmie = cv.fit_transform(data_less_jimmie["tweet"]) feature_names = cv.get_feature_names() #get tfidf vector for first document first_document_vector=word_count_vector_jimmie[2] #print the scores df = pd.DataFrame(first_document_vector.T.todense(), index=feature_names, columns=["tfidf"]) df.sort_values(by=["tfidf"],ascending=False) ``` # Join dfs & shuffle, train clf ``` print(data_jimmie.shape) print(data_jonas.shape) from sklearn.utils import shuffle tfidf = TfidfVectorizer(ngram_range=(1,2)) data_less_jonas = data_less_jonas.head(2581) print(data_less_jonas.shape) combined = pd.concat([data_less_jimmie,data_less_jonas]) combined = shuffle(combined) print(combined.shape) combined.head() from sklearn.model_selection import train_test_split tweet_tfidf = tfidf.fit_transform(combined["tweet"]) X_train, X_test, y_train, y_test = train_test_split(tweet_tfidf, combined["username"], test_size=0.1, random_state=42) X_train[:3] from sklearn.svm import LinearSVC clf = LinearSVC() model = clf.fit(X_train, y_train) from sklearn.metrics import classification_report y_pred = clf.predict(X_test) print(classification_report(y_test, y_pred)) ``` # Testing! ``` def testClassifier(tweet): vector = tfidf.transform([clean_text(tweet)]) print(model.predict(vector)) testClassifier("") testClassifier("Arbetsmarknaden är inte fri svenska kollektivavtal privatisering arbetslösa kommun") ``` # Going forward I see 4 options: 1. Find stuffs that can help people in the office (@AFRY) 2. Create models for Swedish and perhaps Open Source 3. Make "interesting"/"fun" stuffs (such as applying Text Generation on something like Cards Against Humanity etc) 4. Try something new (perhaps Image Recognition?) Focusing on Swedish is only possible in 1 & 2. Some concrete options: * Explore SparkNLP * Ask around at AFRY for things to automate * Apply text-generation with SOTA to generate either something like Cards Against Humanity or some persons Tweet etc. * Create datasets to create Swedish models on (might need a mech-turk; this will be pretty time-consuming before we see any type of results). * Something completely different. ``` ```
github_jupyter
``` # ['nigga', 'hate', 'love','ass','hell','better'] # #accuracy over all cross-validation folds: [0.6317343173431734, 0.618450184501845, 0.6140221402214022, 0.622140221402214, 0.6137370753323486] # mean=0.62 std=0.01 # ['nigga', 'hate', 'love','ass','hell','better','bitch','fuck','dick'] # accuracy over all cross-validation folds: [0.6287822878228783, 0.6199261992619927, 0.6154981549815498, 0.6236162361623616, 0.6159527326440177] # mean=0.62 std=0.00 # ['nigga', 'hate', 'love','ass','hell','better','bitch','fuck','dick','hey','shit','sexy','awesome'] # accuracy over all cross-validation folds: [0.6501845018450184, 0.6789667896678967, 0.6516605166051661, 0.6494464944649446, 0.6676514032496307] # mean=0.66 std=0.01 # Having all individual words as features # accuracy over all cross-validation folds: [0.7011070110701108, 0.6856088560885609, 0.6915129151291513, 0.7166051660516605, 0.7119645494830132] # mean=0.70 std=0.01 #Same as above but remove all words appearing in less than 1% of all tweets, plus 2 and 3 grams # accuracy over all cross-validation folds: [0.692250922509225, 0.6789667896678967, 0.6907749077490775, 0.7202952029520295, 0.7171344165435746] # mean=0.70 std=0.02 #Same as above but remove all words appearing in less than 5% of all tweets, plus 2 and 3 grams # accuracy over all cross-validation folds: [0.6464944649446495, 0.6686346863468635, 0.6575645756457564, 0.6553505535055351, 0.6506646971935007] # mean=0.66 std=0.01 #Same as above but remove all words appearing in less than 0.5% of all tweets, plus 2 and 3 grams # accuracy over all cross-validation folds: [0.6981549815498155, 0.6952029520295203, 0.6929889298892989, 0.7062730627306273, 0.7104874446085672] # mean=0.70 std=0.01 #if I don`t clean the token which appears time too little, the word table of coefficients for nonhostile will be strange.(even have some japanese) from collections import Counter import numpy as np import pandas as pd import re from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction import DictVectorizer def load_data(datafile): """ Read your data into a single pandas dataframe where - each row is an instance to be classified (this could be a tweet, user, or news article, depending on your project) - there is a column called `label` which stores the class label (e.g., the true category for this row) """ df = pd.read_csv("\\Users\\11977\\elevate-osna-harassment\\osna\\data.csv")[['text', 'hostile']] df.columns = ['text', 'label'] df['label'] = ['hostile' if i==1 else 'nonhostile' for i in df.label] # df['directed'] = ['directed' if i==1 else 'nondirected' for i in df.directed] return df df = load_data('~/Dropbox/elevate/harassment/training_data/data.csv.gz') df.label.value_counts() # def make_features(df): # vec = DictVectorizer() # feature_dicts = [] # words_to_track = ['nigga', 'hate', 'love','ass','hell','better','bitch','fuck','dick','hey','shit','sexy','awesome'] # # will get different model for different features. # #words_to_track = ['you'] # for i,row in df.iterrows(): # features = {} # token_counts = Counter(re.sub('\W+', ' ', row['text'].lower()).split()) # for w in words_to_track: # features[w] = token_counts[w] # feature_dicts.append(features) # X = vec.fit_transform(feature_dicts) # return X, vec #X, vec = make_features(df) from sklearn.feature_extraction.text import CountVectorizer vec = CountVectorizer(min_df=0.005,ngram_range=(1,3)) X = vec.fit_transform(t for t in df['text'].values) X X.shape vec.vocabulary_ X[0,5] X[:,3].sum() for word, idx in vec.vocabulary_.items(): print('%20s\t%d' % (word, X[:,idx].sum())) vec.get_feature_names() y = np.array(df.label) Counter(y) y[[0,5,12]] class_names = set(df.label) for word, idx in vec.vocabulary_.items(): for class_name in class_names: class_idx = np.where(y==class_name)[0] print('%20s\t%20s\t%d' % (word, class_name, X[class_idx, idx].sum())) clf = LogisticRegression(multi_class='auto') clf.fit(X, y) clf.coef_ coef = [-clf.coef_[0], clf.coef_[0]] print(coef) clf.classes_ for ci, class_name in enumerate(clf.classes_): print('coefficients for %s' % class_name) display(pd.DataFrame([coef[ci]], columns=vec.get_feature_names())) features = vec.get_feature_names() for ci, class_name in enumerate(clf.classes_): print('top features for class %s' % class_name) for fi in coef[ci].argsort()[::-1][:10]: # descending order. print('%20s\t%.2f' % (features[fi], coef[ci][fi])) from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score kf = KFold(n_splits=5, shuffle=True, random_state=42) accuracies = [] for train, test in kf.split(X): clf.fit(X[train], y[train]) pred = clf.predict(X[test]) accuracies.append(accuracy_score(y[test], pred)) print('accuracy over all cross-validation folds: %s' % str(accuracies)) print('mean=%.2f std=%.2f' % (np.mean(accuracies), np.std(accuracies))) ```
github_jupyter
# Finite Difference Method This note book illustrates the finite different method for a Boundary Value Problem. ### Example Boudary Value Problem $$ \frac{d^2 y}{dx^2} = 4y$$ ### Boundary Condition $$ y(0)=1.1752, y(1)=10.0179 $$ ``` import numpy as np import math import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") class ListTable(list): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders an HTML Table in IPython Notebook. """ from IPython.core.display import HTML def _repr_html_(self): html = ["<table>"] for row in self: html.append("<tr>") for col in row: html.append("<td>{0}</td>".format(col)) html.append("</tr>") html.append("</table>") return ''.join(html) from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') ``` ## Discrete Axis The stepsize is defined as $$h=\frac{b-a}{N}$$ here it is $$h=\frac{1-0}{10}$$ giving $$x_i=0+0.1 i$$ for $i=0,1,...10.$ ``` ## BVP N=10 h=1/N x=np.linspace(0,1,N+1) fig = plt.figure(figsize=(10,4)) plt.plot(x,0*x,'o:',color='red') plt.xlim((0,1)) plt.xlabel('x',fontsize=16) plt.title('Illustration of discrete time points for h=%s'%(h),fontsize=32) plt.show() ``` ## The Difference Equation The gerenal difference equation is $$ \frac{1}{h^2}\left(y_{i-1}-2y_i+y_{i+1}\right)=4y_i \ \ \ i=1,..,N-1. $$ Rearranging the equation we have the system of N-1 equations $$i=1: \frac{1}{0.1^2}\color{green}{y_{0}} -\left(\frac{2}{0.1^2}+4\right)y_1 +\frac{1}{0.1^2} y_{2}=0$$ $$i=2: \frac{1}{0.1^2}y_{1} -\left(\frac{2}{0.1^2}+4\right)y_2 +\frac{1}{0.1^2} y_{3}=0$$ $$ ...$$ $$i=8: \frac{1}{0.1^2}y_{7} -\left(\frac{2}{0.1^2}+4\right)y_8 +\frac{1}{0.1^2} y_{9}=0$$ $$i=9: \frac{1}{0.1^2}y_{8} -\left(\frac{2}{0.1^2}+4\right)y_9 +\frac{1}{0.1^2} \color{green}{y_{10}}=0$$ where the green terms are the known boundary conditions. Rearranging the equation we have the system of 9 equations $$i=1: -\left(\frac{2}{0.1^2}+4\right)y_1 +\frac{1}{0.1^2} y_{2}=0$$ $$i=2: \frac{1}{0.1^2}y_{1} -\left(\frac{2}{0.1^2}+4\right)y_2 +\frac{1}{0.1^2} y_{3}=-\frac{1}{0.1^2}\color{green}{y_{0}}$$ $$ ...$$ $$i=8: \frac{1}{0.1^2}y_{7} -\left(\frac{2}{0.1^2}+4\right)y_8 +\frac{1}{0.1^2} y_{9}=0$$ $$i=9: \frac{1}{0.1^2}y_{8} -\left(\frac{2}{0.1^2}+4\right)y_9 =0$$ where the green terms are the known boundary conditions. Putting this into matrix form gives a $9\times 9 $ matrix $$ A=\left(\begin{array}{ccc ccc ccc} -204&100&0& 0&0&0& 0&0&0\\ 100&-204&100 &0&0&0& 0&0&0\\ 0&100&-204& 100&0&0& 0&0&0\\ .&.&.& .&.&.& .&.&.\\ .&.&.& .&.&.& .&.&.\\ 0&0&0& 0&0&0& 100&-204&100\\ 0&0&0& 0&0&0& 0&100&-204 \end{array}\right) $$ an unknown vector $$ \color{red}{\mathbf{y}}=\color{red}{ \left(\begin{array}{c} y_1\\ y_2\\ y_3\\ .\\ .\\ y_8\\ y_9 \end{array}\right)} $$ ``` y=np.zeros((N+1)) # Boundary Condition y[0]=1.1752 y[N]=10.0179 ``` and the known right hand side is a known $9\times 1$ vector with the boundary conditions $$ \mathbf{b}=\left(\begin{array}{c}-117.52\\ 0\\ 0\\ .\\ .\\ 0\\ -1001.79 \end{array}\right) $$ $$ A\mathbf{y}=\mathbf{b}$$ The plot below is a graphical representation of the matrix A. ``` b=np.zeros(N-1) # Boundary Condition b[0]=-y[0]/(h*h) b[N-2]=-y[N]/(h*h) A=np.zeros((N-1,N-1)) # Diagonal for i in range (0,N-1): A[i,i]=-(2/(h*h)+4) for i in range (0,N-2): A[i+1,i]=1/(h*h) A[i,i+1]=1/(h*h) plt.imshow(A) plt.xlabel('i',fontsize=16) plt.ylabel('j',fontsize=16) plt.yticks(np.arange(N-1), np.arange(1,N-0.9,1)) plt.xticks(np.arange(N-1), np.arange(1,N-0.9,1)) clb=plt.colorbar() clb.set_label('Matrix value') plt.title('Matrix A',fontsize=32) plt.tight_layout() plt.subplots_adjust() plt.show() ``` ## Solving the system To solve invert the matrix $A$ such that $$A^{-1}Ay=A^{-1}b$$ $$y=A^{-1}b$$ The plot below shows the graphical representation of $A^{-1}$. ``` invA=np.linalg.inv(A) plt.imshow(invA) plt.xlabel('i',fontsize=16) plt.ylabel('j',fontsize=16) plt.yticks(np.arange(N-1), np.arange(1,N-0.9,1)) plt.xticks(np.arange(N-1), np.arange(1,N-0.9,1)) clb=plt.colorbar() clb.set_label('Matrix value') plt.title(r'Matrix $A^{-1}$',fontsize=32) plt.tight_layout() plt.subplots_adjust() plt.show() y[1:N]=np.dot(invA,b) ``` ## Result The plot below shows the approximate solution of the Boundary Value Problem (blue v) and the exact solution (black dashed line). ``` fig = plt.figure(figsize=(8,4)) plt.plot(x,y,'v',label='Finite Difference') plt.plot(x,np.sinh(2*x+1),'k:',label='exact') plt.xlabel('x') plt.ylabel('y') plt.legend(loc='best') plt.show() ```
github_jupyter
### Package installs If you are using jupyter lab online, all packages will be available. If you are running this on your local computer, you may need to install some packages. Run the cell below if using jupyter lab locally. ``` !pip install numpy !pip install scipy !pip install pandas !pip install scikit-learn !pip install seaborn ``` ### Importing data To begin, we need to understand the data. The ribosome genes are available in a .fasta file called 'ribosome_genes.fasta'. You can have a look if you like. These genes will be imported as classes (RibosomeGene). Each RibosomeGene object has a name, accession, sequence and length. You can access these properties using '.' syntax. (see below). Try to think of each gene as something physical, rather than code. In real life, each gene has a .length, its organism has a .name, and it has a .sequence. We can write code in this way too. we will import these into **ribosome_genes**, which is a list of our genes. ``` import warnings warnings.filterwarnings('ignore') from utilities import import_16s_sequences ribosome_genes = import_16s_sequences() print('{:<20}{:<30}{:<15}{:<10}'.format('gene.accession', 'gene.name', 'gene.length', 'gene.sequence')) for gene in ribosome_genes: print('{:<20}{:<30}{:<15}{:<10}'.format(gene.accession, gene.name[:27], gene.length, gene.sequence[:8] + '...')) ``` ### SECTION 1: PAIRWISE DISTANCES To be able to compare organisms via their sequences, we need a way to measure their difference as a distance. **K-mer distance**<br> The kmer distance between two sequences is defined here as the total number of k-mers that are unique to either sequence.<br> eg: If seq1 has 3 unique kmers not found in seq2 (copy number difference also matters), and seq2 has 2 unique kmers, the kmer distance is 5. ``` def create_kmer_dictionary(seq, k): kmer_dict = {} num = len(seq) - k + 1 for i in range(num): kmer = seq[i:i+k] if kmer not in kmer_dict: kmer_dict[kmer] = 0 kmer_dict[kmer] += 1 return kmer_dict create_kmer_dictionary('CCUUCGGG', 2) def calculate_total_unique_kmers(kmers1, kmers2): unique_kmers = 0 c1 = c2 = c3 = c4 = c5 = 0 for k in kmers1: if k not in kmers2: c1 += kmers1[k] elif k in kmers1 and k in kmers2: c2 = c2+ abs(kmers1[k] - kmers2[k]) for k2 in kmers2: if k2 not in kmers1: c3 += kmers2[k2] unique_kmers = c1+c2+c3 return unique_kmers kmers1 = {'CCUUCGGG':1} kmers2 = {'CCUUUUUG':2} calculate_total_unique_kmers(kmers1, kmers2) def kmer_distance(seq1, seq2, k): kmers1 = create_kmer_dictionary(seq1,k) kmers2 = create_kmer_dictionary(seq2,k) distance = calculate_total_unique_kmers(kmers1, kmers2) return distance ``` Let's check our function. We can use the first two entries in the 'ribosome_genes' list. If implemented correctly, the following should return 24 ``` distance = kmer_distance(ribosome_genes[1].sequence, ribosome_genes[3].sequence, 8) print(distance) ``` **smith-waterman alignment**<br> Another way to compare the similarity of two sequences is through alignment. The alignment score of two sequences will be high when they are similar, and low when they are distinct. Keep in mind the matrix must be 1 element larger than the sequence lengths. Consider whether indel scores for the first row and column need to be filled in. ``` import numpy as np def init_scoregrid(seq1, seq2, indel_score=-4): rs = len(seq1) +1 cs = len(seq2) +1 scoregrid = np.zeros((rs, cs), np.int) return scoregrid ``` Let's do a sanity check that the grid has been initialised properly. <br> The following should print the initialised scoregrid ``` print(init_scoregrid('hello', 'kittycat')) ``` Write a function that calculates the initialised scoregrid. It accepts two sequences, a scoregrid and match/mismatch and indel scores. ``` import itertools def calculate_scoregrid(seq1, seq2, scoregrid, match_score=1, mismatch_score=-4, indel_score=-4): for i, j in itertools.product(range(1, scoregrid.shape[0]), range(1, scoregrid.shape[1])): match = scoregrid[i - 1, j - 1] + (match_score if seq1[i - 1] == seq2[j - 1] else + mismatch_score) delete = scoregrid[i - 1, j] + indel_score insert = scoregrid[i, j - 1] + indel_score scoregrid[i, j] = max(match, delete, insert, 0) return scoregrid ``` Let's do another sanity check. <br> The following should print a calculated scoregrid, with the these numbers in the bottom right corner: <br> 2 0 <br> 0 3 ``` scoregrid = init_scoregrid('hello', 'helllo') print(calculate_scoregrid('hello', 'helllo', scoregrid)) def report_alignment_score(scoregrid): # given a completed scoregrid, return the smith-waterman alignment score. sw_alignment_score = scoregrid.max() return sw_alignment_score ``` Final sanity check. Should return 4. ``` scoregrid = init_scoregrid('hello', 'helllo') calculated_scoregrid = calculate_scoregrid('hello', 'helllo', scoregrid) print(report_alignment_score(calculated_scoregrid)) ``` Ok! now we're ready to put it all together. <br> Fill in the function below with the three functions you wrote to calculate the alignment score of two sequences ``` def smith_waterman(seq1, seq2): matrix = init_scoregrid(seq1, seq2, indel_score=-4) element_scores = calculate_scoregrid(seq1, seq2, scoregrid, match_score=1, mismatch_score=-4, indel_score=-4) alignment_score = report_alignment_score(scoregrid) return alignment_score ``` The following should print 4 ``` print(smith_waterman('hello', 'helllo')) ``` **pairwise distances** We have now written two functions which can calculate the distance of two sequences. We can calculate the k-mer distance, and the smith-waterman alignment score. lets use these two methods to calculate the pairwise distance of our genes. ``` import numpy as np def init_distance_matrix(genes): values=[] for gene in genes: s=gene.accession values.append(s) values.append(0) distance_matrix = {} for gene in ribosome_genes: key = gene.accession distance_matrix[key]={values[i]: values[i + 1] for i in range(0, len(values), 2)} return distance_matrix ``` Let's print the distance matrix to make sure it worked. ``` from utilities import print_distance_matrix distance_matrix = init_distance_matrix(ribosome_genes) print_distance_matrix(distance_matrix) ``` Time to fill in the matrix with distances. <br> Write a function which calculates the pairwise distance of genes using kmer distance. you will need to call the 'kmer_distance' function you have written above. ``` def calculate_kmer_distance_matrix(genes, matrix, k): for gene1 in genes: key1=gene1.accession for gene2 in genes: key2=gene2.accession matrix[key1][key2]=kmer_distance(gene1.sequence,gene2.sequence,k) return matrix ``` Let's do the same as above, but this time use the 'smith_waterman' alignment distance function you wrote. ``` def calculate_sw_alignment_distance_matrix(genes, matrix): for gene1 in genes: key1=gene1.accession for gene2 in genes: key2=gene2.accession matrix[key1][key2]=smith_waterman(gene1.sequence,gene2.sequence) return matrix ``` Let's test them out. The two cells below will use your calculate_kmer_distance_matrix, and calculate_sw_alignment_distance_matrix functions to add distances to the matrix. <br> **NOTE:** the smith-waterman distance calculations can take time. Give it a minute. ``` distance_matrix = init_distance_matrix(ribosome_genes) kmer_distance_matrix = calculate_kmer_distance_matrix(ribosome_genes, distance_matrix, 8) print('\nkmer distance matrix') print_distance_matrix(kmer_distance_matrix) distance_matrix = init_distance_matrix(ribosome_genes) sw_alignment_distance_matrix = calculate_sw_alignment_distance_matrix(ribosome_genes, distance_matrix) print('\nsmith waterman alignment score distance matrix') print_distance_matrix(sw_alignment_distance_matrix) ``` Let's visualise those in a better manner for human eyes. The cell below will plot heatmaps instead of raw numbers. ``` from utilities import heatmap heatmap(kmer_distance_matrix, sw_alignment_distance_matrix) ``` ### SECTION 2: CLUSTERING From the heatmaps, it seems like there are a few clusters in the data. <br> First, lets convert the pairwise distances to 2D coordinates. This is possible using Multidimensional scaling (MDS). After we have transformed the distance matrix to 2D coordinates, we can plot it to see if any clusters are evident. ``` from utilities import mds_scatterplot, distance_matrix_to_coordinates_MDS kmer_distances_xy = distance_matrix_to_coordinates_MDS(kmer_distance_matrix) sw_distances_xy = distance_matrix_to_coordinates_MDS(sw_alignment_distance_matrix) mds_scatterplot(kmer_distances_xy) mds_scatterplot(sw_distances_xy) ``` Seems like there is some clustering happening. <br> Let's use some clustering algorithms to define the clusters. in this manner, we can have an objective way to talk about the patterns in the data. Let's implement the k-means algorithm. ``` from utilities import initialise_centroids, average_point, assign_points, plot_kmeans, points_equal, euclidean_distance def calculate_mean_centroids(data, assignments, k): centroids = [] for cluster in range(k): points = [point for point, assignment in zip(data, assignments) if assignment == cluster] centroids.append(average_point(points)) return centroids ``` Place calculate_mean_centroids() in the kmeans function below to complete kmeans ``` def kmeans(data, k): centroids=initialise_centroids(data,k) cluster_assignments=assign_points(centroids,data) centroids=calculate_mean_centroids(data,cluster_assignments,k) return centroids, cluster_assignments ``` You can check your implementation using the cell below: ``` centroids, cluster_assignments = kmeans(kmer_distances_xy, 3) plot_kmeans(kmer_distances_xy, centroids, cluster_assignments, 3) ``` Let's also implement k-medoids while we're at it. <br> The only difference between k-means and k-medoids is the calculate_mean_centroids() step, which will instead be calculate_median_centroids() the median can be taken here as the point in the cluster which has smallest cumulative distance to the other points in the cluster You can use the provided euclidean_distance() function to calculate distances between points write a function which calculates new centroid locations (using the median) ``` def calculate_median_centroids(data, assignments, k): centroids = [] for cluster in range(k): points = [point for point, assignment in zip(data, assignments) if assignment == cluster] centroids.append(tuple(np.median(np.array(points), axis=0))) return centroids ``` Place calculate_median_centroids() in the kmedoids function below to complete kmedoids ``` def kmedoids(data, k): centroids=initialise_centroids(data,k) cluster_assignments=assign_points(centroids,data) centroids=calculate_median_centroids(data,cluster_assignments,k) return centroids, cluster_assignments ``` Here is another check cell, for kmedoids this time: ``` centroids,cluster_assignments = kmedoids(kmer_distances_xy, 3) plot_kmeans(kmer_distances_xy, centroids, cluster_assignments, 3) ```
github_jupyter
``` import tensorflow as tf import numpy as np from copy import deepcopy epoch = 20 batch_size = 64 size_layer = 64 dropout_rate = 0.5 n_hops = 2 class BaseDataLoader(): def __init__(self): self.data = { 'size': None, 'val':{ 'inputs': None, 'questions': None, 'answers': None,}, 'len':{ 'inputs_len': None, 'inputs_sent_len': None, 'questions_len': None, 'answers_len': None} } self.vocab = { 'size': None, 'word2idx': None, 'idx2word': None, } self.params = { 'vocab_size': None, '<start>': None, '<end>': None, 'max_input_len': None, 'max_sent_len': None, 'max_quest_len': None, 'max_answer_len': None, } class DataLoader(BaseDataLoader): def __init__(self, path, is_training, vocab=None, params=None): super().__init__() data, lens = self.load_data(path) if is_training: self.build_vocab(data) else: self.demo = data self.vocab = vocab self.params = deepcopy(params) self.is_training = is_training self.padding(data, lens) def load_data(self, path): data, lens = bAbI_data_load(path) self.data['size'] = len(data[0]) return data, lens def build_vocab(self, data): signals = ['<pad>', '<unk>', '<start>', '<end>'] inputs, questions, answers = data i_words = [w for facts in inputs for fact in facts for w in fact if w != '<end>'] q_words = [w for question in questions for w in question] a_words = [w for answer in answers for w in answer if w != '<end>'] words = list(set(i_words + q_words + a_words)) self.params['vocab_size'] = len(words) + 4 self.params['<start>'] = 2 self.params['<end>'] = 3 self.vocab['word2idx'] = {word: idx for idx, word in enumerate(signals + words)} self.vocab['idx2word'] = {idx: word for word, idx in self.vocab['word2idx'].items()} def padding(self, data, lens): inputs_len, inputs_sent_len, questions_len, answers_len = lens self.params['max_input_len'] = max(inputs_len) self.params['max_sent_len'] = max([fact_len for batch in inputs_sent_len for fact_len in batch]) self.params['max_quest_len'] = max(questions_len) self.params['max_answer_len'] = max(answers_len) self.data['len']['inputs_len'] = np.array(inputs_len) for batch in inputs_sent_len: batch += [0] * (self.params['max_input_len'] - len(batch)) self.data['len']['inputs_sent_len'] = np.array(inputs_sent_len) self.data['len']['questions_len'] = np.array(questions_len) self.data['len']['answers_len'] = np.array(answers_len) inputs, questions, answers = deepcopy(data) for facts in inputs: for sentence in facts: for i in range(len(sentence)): sentence[i] = self.vocab['word2idx'].get(sentence[i], self.vocab['word2idx']['<unk>']) sentence += [0] * (self.params['max_sent_len'] - len(sentence)) paddings = [0] * self.params['max_sent_len'] facts += [paddings] * (self.params['max_input_len'] - len(facts)) for question in questions: for i in range(len(question)): question[i] = self.vocab['word2idx'].get(question[i], self.vocab['word2idx']['<unk>']) question += [0] * (self.params['max_quest_len'] - len(question)) for answer in answers: for i in range(len(answer)): answer[i] = self.vocab['word2idx'].get(answer[i], self.vocab['word2idx']['<unk>']) self.data['val']['inputs'] = np.array(inputs) self.data['val']['questions'] = np.array(questions) self.data['val']['answers'] = np.array(answers) def bAbI_data_load(path, END=['<end>']): inputs = [] questions = [] answers = [] inputs_len = [] inputs_sent_len = [] questions_len = [] answers_len = [] for d in open(path): index = d.split(' ')[0] if index == '1': fact = [] if '?' in d: temp = d.split('\t') q = temp[0].strip().replace('?', '').split(' ')[1:] + ['?'] a = temp[1].split() + END fact_copied = deepcopy(fact) inputs.append(fact_copied) questions.append(q) answers.append(a) inputs_len.append(len(fact_copied)) inputs_sent_len.append([len(s) for s in fact_copied]) questions_len.append(len(q)) answers_len.append(len(a)) else: tokens = d.replace('.', '').replace('\n', '').split(' ')[1:] + END fact.append(tokens) return [inputs, questions, answers], [inputs_len, inputs_sent_len, questions_len, answers_len] train_data = DataLoader(path='qa5_three-arg-relations_train.txt',is_training=True) test_data = DataLoader(path='qa5_three-arg-relations_test.txt',is_training=False, vocab=train_data.vocab, params=train_data.params) START = train_data.params['<start>'] END = train_data.params['<end>'] def hop_forward(question, memory_o, memory_i, response_proj, inputs_len, questions_len, is_training): match = tf.matmul(question, memory_i, transpose_b=True) match = pre_softmax_masking(match, inputs_len) match = tf.nn.softmax(match) match = post_softmax_masking(match, questions_len) response = tf.matmul(match, memory_o) return response_proj(tf.concat([response, question], -1)) def pre_softmax_masking(x, seq_len): paddings = tf.fill(tf.shape(x), float('-inf')) T = tf.shape(x)[1] max_seq_len = tf.shape(x)[2] masks = tf.sequence_mask(seq_len, max_seq_len, dtype=tf.float32) masks = tf.tile(tf.expand_dims(masks, 1), [1, T, 1]) return tf.where(tf.equal(masks, 0), paddings, x) def post_softmax_masking(x, seq_len): T = tf.shape(x)[2] max_seq_len = tf.shape(x)[1] masks = tf.sequence_mask(seq_len, max_seq_len, dtype=tf.float32) masks = tf.tile(tf.expand_dims(masks, -1), [1, 1, T]) return (x * masks) def shift_right(x): batch_size = tf.shape(x)[0] start = tf.to_int32(tf.fill([batch_size, 1], START)) return tf.concat([start, x[:, :-1]], 1) def embed_seq(x, vocab_size, zero_pad=True): lookup_table = tf.get_variable('lookup_table', [vocab_size, size_layer], tf.float32) if zero_pad: lookup_table = tf.concat((tf.zeros([1, size_layer]), lookup_table[1:, :]), axis=0) return tf.nn.embedding_lookup(lookup_table, x) def position_encoding(sentence_size, embedding_size): encoding = np.ones((embedding_size, sentence_size), dtype=np.float32) ls = sentence_size + 1 le = embedding_size + 1 for i in range(1, le): for j in range(1, ls): encoding[i-1, j-1] = (i - (le-1)/2) * (j - (ls-1)/2) encoding = 1 + 4 * encoding / embedding_size / sentence_size return tf.convert_to_tensor(np.transpose(encoding)) def input_mem(x, vocab_size, max_sent_len, is_training): x = embed_seq(x, vocab_size) x = tf.layers.dropout(x, dropout_rate, training=is_training) pos = position_encoding(max_sent_len, size_layer) x = tf.reduce_sum(x * pos, 2) return x def quest_mem(x, vocab_size, max_quest_len, is_training): x = embed_seq(x, vocab_size) x = tf.layers.dropout(x, dropout_rate, training=is_training) pos = position_encoding(max_quest_len, size_layer) return (x * pos) class QA: def __init__(self, vocab_size): self.questions = tf.placeholder(tf.int32,[None,None]) self.inputs = tf.placeholder(tf.int32,[None,None,None]) self.questions_len = tf.placeholder(tf.int32,[None]) self.inputs_len = tf.placeholder(tf.int32,[None]) self.answers_len = tf.placeholder(tf.int32,[None]) self.answers = tf.placeholder(tf.int32,[None,None]) self.training = tf.placeholder(tf.bool) max_sent_len = train_data.params['max_sent_len'] max_quest_len = train_data.params['max_quest_len'] max_answer_len = train_data.params['max_answer_len'] lookup_table = tf.get_variable('lookup_table', [vocab_size, size_layer], tf.float32) lookup_table = tf.concat((tf.zeros([1, size_layer]), lookup_table[1:, :]), axis=0) with tf.variable_scope('questions'): question = quest_mem(self.questions, vocab_size, max_quest_len, self.training) with tf.variable_scope('memory_o'): memory_o = input_mem(self.inputs, vocab_size, max_sent_len, self.training) with tf.variable_scope('memory_i'): memory_i = input_mem(self.inputs, vocab_size, max_sent_len, self.training) with tf.variable_scope('interaction'): response_proj = tf.layers.Dense(size_layer) for _ in range(n_hops): answer = hop_forward(question, memory_o, memory_i, response_proj, self.inputs_len, self.questions_len, self.training) question = answer with tf.variable_scope('memory_o', reuse=True): embedding = tf.get_variable('lookup_table') cell = tf.nn.rnn_cell.LSTMCell(size_layer) vocab_proj = tf.layers.Dense(vocab_size) state_proj = tf.layers.Dense(size_layer) init_state = state_proj(tf.layers.flatten(answer)) init_state = tf.layers.dropout(init_state, dropout_rate, training=self.training) helper = tf.contrib.seq2seq.TrainingHelper( inputs = tf.nn.embedding_lookup(embedding, shift_right(self.answers)), sequence_length = tf.to_int32(self.answers_len)) encoder_state = tf.nn.rnn_cell.LSTMStateTuple(c=init_state, h=init_state) decoder = tf.contrib.seq2seq.BasicDecoder(cell = cell, helper = helper, initial_state = encoder_state, output_layer = vocab_proj) decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder = decoder, maximum_iterations = tf.shape(self.inputs)[1]) self.outputs = decoder_output.rnn_output helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding = embedding, start_tokens = tf.tile( tf.constant([START], dtype=tf.int32), [tf.shape(self.inputs)[0]]), end_token = END) decoder = tf.contrib.seq2seq.BasicDecoder( cell = cell, helper = helper, initial_state = encoder_state, output_layer = vocab_proj) decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode( decoder = decoder, maximum_iterations = max_answer_len) self.logits = decoder_output.sample_id correct_pred = tf.equal(self.logits, self.answers) self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) self.cost = tf.reduce_mean(tf.contrib.seq2seq.sequence_loss(logits = self.outputs, targets = self.answers, weights = tf.ones_like(self.answers, tf.float32))) self.optimizer = tf.train.AdamOptimizer().minimize(self.cost) tf.reset_default_graph() sess = tf.InteractiveSession() model = QA(train_data.params['vocab_size']) sess.run(tf.global_variables_initializer()) batching = (train_data.data['val']['inputs'].shape[0] // batch_size) * batch_size for i in range(epoch): total_cost, total_acc = 0, 0 for k in range(0, batching, batch_size): batch_questions = train_data.data['val']['questions'][k:k+batch_size] batch_inputs = train_data.data['val']['inputs'][k:k+batch_size] batch_inputs_len = train_data.data['len']['inputs_len'][k:k+batch_size] batch_questions_len = train_data.data['len']['questions_len'][k:k+batch_size] batch_answers_len = train_data.data['len']['answers_len'][k:k+batch_size] batch_answers = train_data.data['val']['answers'][k:k+batch_size] acc, cost, _ = sess.run([model.accuracy,model.cost,model.optimizer], feed_dict={model.questions:batch_questions, model.inputs:batch_inputs, model.inputs_len:batch_inputs_len, model.questions_len:batch_questions_len, model.answers_len:batch_answers_len, model.answers:batch_answers, model.training:True}) total_cost += cost total_acc += acc total_cost /= (train_data.data['val']['inputs'].shape[0] // batch_size) total_acc /= (train_data.data['val']['inputs'].shape[0] // batch_size) print('epoch %d, avg cost %f, avg acc %f'%(i+1,total_cost,total_acc)) testing_size = 32 batch_questions = test_data.data['val']['questions'][:testing_size] batch_inputs = test_data.data['val']['inputs'][:testing_size] batch_inputs_len = test_data.data['len']['inputs_len'][:testing_size] batch_questions_len = test_data.data['len']['questions_len'][:testing_size] batch_answers_len = test_data.data['len']['answers_len'][:testing_size] batch_answers = test_data.data['val']['answers'][:testing_size] logits = sess.run(model.logits, feed_dict={model.questions:batch_questions, model.inputs:batch_inputs, model.inputs_len:batch_inputs_len, model.questions_len:batch_questions_len, model.answers_len:batch_answers_len, model.training:False}) for i in range(testing_size): print('QUESTION:',' '.join([train_data.vocab['idx2word'][k] for k in batch_questions[i]])) print('REAL:',train_data.vocab['idx2word'][batch_answers[i,0]]) print('PREDICT:',train_data.vocab['idx2word'][logits[i,0]],'\n') ```
github_jupyter
# Deep Learning Toolkit for Splunk - Notebook for STL - Seasonality and Trend Decomposition This notebook contains a barebone example workflow how to work on custom containerized code that seamlessly interfaces with the Deep Learning Toolkit for Splunk. Note: By default every time you save this notebook the cells are exported into a python module which is then invoked by Splunk MLTK commands like <code> | fit ... | apply ... | summary </code>. Please read the Model Development Guide in the Deep Learning Toolkit app for more information. ## Stage 0 - import libraries At stage 0 we define all imports necessary to run our subsequent code depending on various libraries. ``` # this definition exposes all python module imports that should be available in all subsequent commands import json import numpy as np import pandas as pd from statsmodels.tsa.seasonal import STL import statsmodels as sm # ... # global constants MODEL_DIRECTORY = "/srv/app/model/data/" # THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes print("numpy version: " + np.__version__) print("pandas version: " + pd.__version__) print("statsmodels version: " + sm.__version__) ``` ## Stage 1 - get a data sample from Splunk In Splunk run a search to pipe a dataset into your notebook environment. Note: mode=stage is used in the | fit command to do this. | inputlookup cyclical_business_process.csv<br> | fit MLTKContainer mode=stage algo=seasonality_and_trend_decomposition _time logons After you run this search your data set sample is available as a csv inside the container to develop your model. The name is taken from the into keyword ("barebone_model" in the example above) or set to "default" if no into keyword is present. This step is intended to work with a subset of your data to create your custom model. ``` # this cell is not executed from MLTK and should only be used for staging data into the notebook environment def stage(name): with open("data/"+name+".csv", 'r') as f: df = pd.read_csv(f) with open("data/"+name+".json", 'r') as f: param = json.load(f) return df, param # THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes df, param = stage("default") print(df.describe()) print(param) ``` ## Stage 2 - create and initialize a model ``` # initialize your model # available inputs: data and parameters # returns the model object which will be used as a reference to call fit, apply and summary subsequently def init(df,param): model = {} return model # THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes print(init(df,param)) model=init(df,param) ``` ## Stage 3 - fit the model ``` # train your model # returns a fit info json object and may modify the model object def fit(model,df,param): return "info" # THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes print(fit(model,df,param)) ``` ## Stage 4 - apply the model ``` # apply your model # returns the calculated results def apply(model,df,param): data=df data['_time']=pd.to_datetime(data['_time']) data = data.set_index('_time') # Set the index to datetime object. data=data.asfreq('H') res=STL(data).fit() results=pd.DataFrame({"seasonality": res.seasonal, "trend": res.trend, "residual": res.resid}) results.reset_index(level=0, inplace=True) return results # THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes apply(model,df,param) ``` ## Stage 5 - save the model ``` # save model to name in expected convention "<algo_name>_<model_name>" def save(model,name): return model ``` ## Stage 6 - load the model ``` # load model from name in expected convention "<algo_name>_<model_name>" def load(name): return model ``` ## Stage 7 - provide a summary of the model ``` # return a model summary def summary(model=None): returns = {"version": {"numpy": np.__version__, "pandas": pd.__version__} } return returns ``` ## End of Stages All subsequent cells are not tagged and can be used for further freeform code
github_jupyter
# Intro [PyTorch](https://pytorch.org/) is a very powerful machine learning framework. Central to PyTorch are [tensors](https://pytorch.org/docs/stable/tensors.html), a generalization of matrices to higher ranks. One intuitive example of a tensor is an image with three color channels: A 3-channel (red, green, blue) image which is 64 pixels wide and 64 pixels tall is a $3\times64\times64$ tensor. You can access the PyTorch framework by writing `import torch` near the top of your code, along with all of your other import statements. This guide will help introduce you to the functionality of PyTorch, but don't worry too much about memorizing it: the assignments will link to relevant documentation where necessary. ``` import torch ``` # Why PyTorch? One important question worth asking is, why is PyTorch being used for this course? There is a great breakdown by [the Gradient](https://thegradient.pub/state-of-ml-frameworks-2019-pytorch-dominates-research-tensorflow-dominates-industry/) looking at the state of machine learning frameworks today. In part, as highlighted by the article, PyTorch is generally more pythonic than alternative frameworks, easier to debug, and is the most-used language in machine learning research by a large and growing margin. While PyTorch's primary alternative, Tensorflow, has attempted to integrate many of PyTorch's features, Tensorflow's implementations come with some inherent limitations highlighted in the article. Notably, while PyTorch's industry usage has grown, Tensorflow is still (for now) a slight favorite in industry. In practice, the features that make PyTorch attractive for research also make it attractive for education, and the general trend of machine learning research and practice to PyTorch makes it the more proactive choice. # Tensor Properties One way to create tensors from a list or an array is to use `torch.Tensor`. It'll be used to set up examples in this notebook, but you'll never need to use it in the course - in fact, if you find yourself needing it, that's probably not the correct answer. ``` example_tensor = torch.Tensor( [ [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 0], [1, 2]] ] ) ``` You can view the tensor in the notebook by simple printing it out (though some larger tensors will be cut off) ``` example_tensor ``` ## Tensor Properties: Device One important property is the device of the tensor - throughout this notebook you'll be sticking to tensors which are on the CPU. However, throughout the course you'll also be using tensors on GPU (that is, a graphics card which will be provided for you to use for the course). To view the device of the tensor, all you need to write is `example_tensor.device`. To move a tensor to a new device, you can write `new_tensor = example_tensor.to(device)` where device will be either `cpu` or `cuda`. ``` example_tensor.device ``` ## Tensor Properties: Shape And you can get the number of elements in each dimension by printing out the tensor's shape, using `example_tensor.shape`, something you're likely familiar with if you've used numpy. For example, this tensor is a $3\times2\times2$ tensor, since it has 3 elements, each of which are $2\times2$. ``` example_tensor.shape ``` You can also get the size of a particular dimension $n$ using `example_tensor.shape[n]` or equivalently `example_tensor.size(n)` ``` print("shape[0] =", example_tensor.shape[0]) print("size(1) =", example_tensor.size(1)) ``` Finally, it is sometimes useful to get the number of dimensions (rank) or the number of elements, which you can do as follows ``` print("Rank =", len(example_tensor.shape)) print("Number of elements =", example_tensor.numel()) ``` # Indexing Tensors As with numpy, you can access specific elements or subsets of elements of a tensor. To access the $n$-th element, you can simply write `example_tensor[n]` - as with Python in general, these dimensions are 0-indexed. ``` example_tensor[1] ``` In addition, if you want to access the $j$-th dimension of the $i$-th example, you can write `example_tensor[i, j]` ``` example_tensor[1, 1, 0] ``` Note that if you'd like to get a Python scalar value from a tensor, you can use `example_scalar.item()` ``` example_scalar = example_tensor[1, 1, 0] example_scalar.item() ``` In addition, you can index into the ith element of a column by using `x[:, i]`. For example, if you want the top-left element of each element in `example_tensor`, which is the `0, 0` element of each matrix, you can write: ``` example_tensor[:, 0, 0] ``` # Initializing Tensors There are many ways to create new tensors in PyTorch, but in this course, the most important ones are: [`torch.ones_like`](https://pytorch.org/docs/master/generated/torch.ones_like.html): creates a tensor of all ones with the same shape and device as `example_tensor`. ``` torch.ones_like(example_tensor) ``` [`torch.zeros_like`](https://pytorch.org/docs/master/generated/torch.zeros_like.html): creates a tensor of all zeros with the same shape and device as `example_tensor` ``` torch.zeros_like(example_tensor) ``` [`torch.randn_like`](https://pytorch.org/docs/stable/generated/torch.randn_like.html): creates a tensor with every element sampled from a [Normal (or Gaussian) distribution](https://en.wikipedia.org/wiki/Normal_distribution) with the same shape and device as `example_tensor` ``` torch.randn_like(example_tensor) ``` Sometimes (though less often than you'd expect), you might need to initialize a tensor knowing only the shape and device, without a tensor for reference for `ones_like` or `randn_like`. In this case, you can create a $2x2$ tensor as follows: ``` torch.randn(2, 2, device='cpu') # Alternatively, for a GPU tensor, you'd use device='cuda' ``` # Basic Functions There are a number of basic functions that you should know to use PyTorch - if you're familiar with numpy, all commonly-used functions exist in PyTorch, usually with the same name. You can perform element-wise multiplication / division by a scalar $c$ by simply writing `c * example_tensor`, and element-wise addition / subtraction by a scalar by writing `example_tensor + c` Note that most operations are not in-place in PyTorch, which means that they don't change the original variable's data (However, you can reassign the same variable name to the changed data if you'd like, such as `example_tensor = example_tensor + 1`) ``` (example_tensor - 5) * 2 ``` You can calculate the mean or standard deviation of a tensor using [`example_tensor.mean()`](https://pytorch.org/docs/stable/generated/torch.mean.html) or [`example_tensor.std()`](https://pytorch.org/docs/stable/generated/torch.std.html). ``` print("Mean:", example_tensor.mean()) print("Stdev:", example_tensor.std()) ``` You might also want to find the mean or standard deviation along a particular dimension. To do this you can simple pass the number corresponding to that dimension to the function. For example, if you want to get the average $2\times2$ matrix of the $3\times2\times2$ `example_tensor` you can write: ``` example_tensor.mean(0) # Equivalently, you could also write: # example_tensor.mean(dim=0) # example_tensor.mean(axis=0) # torch.mean(example_tensor, 0) # torch.mean(example_tensor, dim=0) # torch.mean(example_tensor, axis=0) ``` PyTorch has many other powerful functions but these should be all of PyTorch functions you need for this course outside of its neural network module (`torch.nn`). # PyTorch Neural Network Module (`torch.nn`) PyTorch has a lot of powerful classes in its `torch.nn` module (Usually, imported as simply `nn`). These classes allow you to create a new function which transforms a tensor in specific way, often retaining information when called multiple times. ``` import torch.nn as nn ``` ## `nn.Linear` To create a linear layer, you need to pass it the number of input dimensions and the number of output dimensions. The linear object initialized as `nn.Linear(10, 2)` will take in a $n\times10$ matrix and return an $n\times2$ matrix, where all $n$ elements have had the same linear transformation performed. For example, you can initialize a linear layer which performs the operation $Ax + b$, where $A$ and $b$ are initialized randomly when you generate the [`nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) object. ``` linear = nn.Linear(10, 2) example_input = torch.randn(3, 10) example_output = linear(example_input) example_output ``` ## `nn.ReLU` [`nn.ReLU()`](https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html) will create an object that, when receiving a tensor, will perform a ReLU activation function. This will be reviewed further in lecture, but in essence, a ReLU non-linearity sets all negative numbers in a tensor to zero. In general, the simplest neural networks are composed of series of linear transformations, each followed by activation functions. ``` relu = nn.ReLU() relu_output = relu(example_output) relu_output ``` ## `nn.BatchNorm1d` [`nn.BatchNorm1d`](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm1d.html) is a normalization technique that will rescale a batch of $n$ inputs to have a consistent mean and standard deviation between batches. As indicated by the `1d` in its name, this is for situations where you expects a set of inputs, where each of them is a flat list of numbers. In other words, each input is a vector, not a matrix or higher-dimensional tensor. For a set of images, each of which is a higher-dimensional tensor, you'd use [`nn.BatchNorm2d`](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html), discussed later on this page. `nn.BatchNorm1d` takes an argument of the number of input dimensions of each object in the batch (the size of each example vector). ``` batchnorm = nn.BatchNorm1d(2) batchnorm_output = batchnorm(relu_output) batchnorm_output ``` ## `nn.Sequential` [`nn.Sequential`](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html) creates a single operation that performs a sequence of operations. For example, you can write a neural network layer with a batch normalization as ``` mlp_layer = nn.Sequential( nn.Linear(5, 2), nn.BatchNorm1d(2), nn.ReLU() ) test_example = torch.randn(5,5) + 1 print("input: ") print(test_example) print("output: ") print(mlp_layer(test_example)) ``` # Optimization One of the most important aspects of essentially any machine learning framework is its automatic differentiation library. ## Optimizers To create an optimizer in PyTorch, you'll need to use the `torch.optim` module, often imported as `optim`. [`optim.Adam`](https://pytorch.org/docs/stable/optim.html#torch.optim.Adam) corresponds to the Adam optimizer. To create an optimizer object, you'll need to pass it the parameters to be optimized and the learning rate, `lr`, as well as any other parameters specific to the optimizer. For all `nn` objects, you can access their parameters as a list using their `parameters()` method, as follows: ``` import torch.optim as optim adam_opt = optim.Adam(mlp_layer.parameters(), lr=1e-1) ``` ## Training Loop A (basic) training step in PyTorch consists of four basic parts: 1. Set all of the gradients to zero using `opt.zero_grad()` 2. Calculate the loss, `loss` 3. Calculate the gradients with respect to the loss using `loss.backward()` 4. Update the parameters being optimized using `opt.step()` That might look like the following code (and you'll notice that if you run it several times, the loss goes down): ``` train_example = torch.randn(100,5) + 1 adam_opt.zero_grad() # We'll use a simple loss function of mean distance from 1 # torch.abs takes the absolute value of a tensor cur_loss = torch.abs(1 - mlp_layer(train_example)).mean() cur_loss.backward() adam_opt.step() print(cur_loss) ``` ## `requires_grad_()` You can also tell PyTorch that it needs to calculate the gradient with respect to a tensor that you created by saying `example_tensor.requires_grad_()`, which will change it in-place. This means that even if PyTorch wouldn't normally store a grad for that particular tensor, it will for that specified tensor. ## `with torch.no_grad():` PyTorch will usually calculate the gradients as it proceeds through a set of operations on tensors. This can often take up unnecessary computations and memory, especially if you're performing an evaluation. However, you can wrap a piece of code with `with torch.no_grad()` to prevent the gradients from being calculated in a piece of code. ## `detach():` Sometimes, you want to calculate and use a tensor's value without calculating its gradients. For example, if you have two models, A and B, and you want to directly optimize the parameters of A with respect to the output of B, without calculating the gradients through B, then you could feed the detached output of B to A. There are many reasons you might want to do this, including efficiency or cyclical dependencies (i.e. A depends on B depends on A). # New `nn` Classes You can also create new classes which extend the `nn` module. For these classes, all class attributes, as in `self.layer` or `self.param` will automatically treated as parameters if they are themselves `nn` objects or if they are tensors wrapped in `nn.Parameter` which are initialized with the class. The `__init__` function defines what will happen when the object is created. The first line of the init function of a class, for example, `WellNamedClass`, needs to be `super(WellNamedClass, self).__init__()`. The `forward` function defines what runs if you create that object `model` and pass it a tensor `x`, as in `model(x)`. If you choose the function signature, `(self, x)`, then each call of the forward function, gets two pieces of information: `self`, which is a reference to the object with which you can access all of its parameters, and `x`, which is the current tensor for which you'd like to return `y`. One class might look like the following: ``` class ExampleModule(nn.Module): def __init__(self, input_dims, output_dims): super(ExampleModule, self).__init__() self.linear = nn.Linear(input_dims, output_dims) self.exponent = nn.Parameter(torch.tensor(1.)) def forward(self, x): x = self.linear(x) # This is the notation for element-wise exponentiation, # which matches python in general x = x ** self.exponent return x ``` And you can view its parameters as follows ``` example_model = ExampleModule(10, 2) list(example_model.parameters()) ``` And you can print out their names too, as follows: ``` list(example_model.named_parameters()) ``` And here's an example of the class in action: ``` input = torch.randn(2, 10) example_model(input) ``` # 2D Operations You won't need these for the first lesson, and the theory behind each of these will be reviewed more in later lectures, but here is a quick reference: * 2D convolutions: [`nn.Conv2d`](https://pytorch.org/docs/master/generated/torch.nn.Conv2d.html) requires the number of input and output channels, as well as the kernel size. * 2D transposed convolutions (aka deconvolutions): [`nn.ConvTranspose2d`](https://pytorch.org/docs/master/generated/torch.nn.ConvTranspose2d.html) also requires the number of input and output channels, as well as the kernel size * 2D batch normalization: [`nn.BatchNorm2d`](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html) requires the number of input dimensions * Resizing images: [`nn.Upsample`](https://pytorch.org/docs/master/generated/torch.nn.Upsample.html) requires the final size or a scale factor. Alternatively, [`nn.functional.interpolate`](https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate) takes the same arguments.
github_jupyter
# Spatially Assign Work In this example, assignments will be assigned to specific workers based on the city district that it falls in. A layer in ArcGIS Online representing the city districts in Palm Springs will be used. * Note: This example requires having Arcpy or Shapely installed in the Python environment. ### Import ArcGIS API for Python Import the `arcgis` library and some modules within it. ``` from datetime import datetime from arcgis.gis import GIS from arcgis.geometry import Geometry from arcgis.mapping import WebMap from arcgis.apps import workforce from datetime import datetime ``` ### Connect to organization and Get the Project Let's connect to ArcGIS Online and get the Project with assignments. ``` gis = GIS("https://arcgis.com", "workforce_scripts") item = gis.content.get("c765482bd0b9479b9104368da54df90d") project = workforce.Project(item) ``` ### Get Layer of City Districts Let's get the layer representing city districts and display it. ``` districts_layer = gis.content.get("8a79535e0dc04410b5564c0e45428a2c").layers[0] districts_map = gis.map("Palm Springs, CA", zoomlevel=10) districts_map.add_layer(districts_layer) districts_map ``` ### Add Assignments to the Map ``` districts_map.add_layer(project.assignments_layer) ``` ### Create a spatially enabled dataframe of the districts ``` districts_df = districts_layer.query(as_df=True) ``` ### Get all of the unassigned assignments ``` assignments = project.assignments.search("status=0") ``` ### Assign Assignments Based on Which District They Intersect¶ Let's fetch the districts layer and query to get all of the districts. Then, for each unassigned assignment intersect the assignment with all districts to determine which district it falls in. Assignments in district 10 should be assigned to James. Assignments in district 9 should be assigned to Aaron. Finally update all of the assignments using "batch_update". ``` aaron = project.workers.get(user_id="aaron_nitro") james = project.workers.get(user_id="james_Nitro") for assignment in assignments: contains = districts_df["SHAPE"].geom.contains(Geometry(assignment.geometry)) containers = districts_df[contains] if not containers.empty: district = containers['ID'].iloc[0] if district == 10: assignment.worker = james assignment.status = "assigned" assignment.assigned_date = datetime.utcnow() elif district == 9: assignment.worker = aaron assignment.status = "assigned" assignment.assigned_date = datetime.utcnow() assignments = project.assignments.batch_update(assignments) ``` ### Verify Assignments are Assigned ``` webmap = gis.map("Palm Springs", zoomlevel=11) webmap.add_layer(project.assignments_layer) webmap ```
github_jupyter
# Quantum Generative Adversarial Networks ## Introduction Generative [adversarial](gloss:adversarial) networks (GANs) [[1]](https://arxiv.org/abs/1406.2661) have swiftly risen to prominence as one of the most widely-adopted methods for unsupervised learning, with showcased abilities in photo-realistic image generation. Given the success of classical GANs, a natural question is whether this success will translate into a quantum computing GAN. In this page, we explore the theory behind quantum generative adversarial networks (QGANs), as well as the practice of implementing one in Qiskit to learn a [Gaussian distribution](gloss:gaussian-distribution). Lastly, we end off with a discussion around the potential use cases of quantum generative adversarial networks and link to relevant research for those who want to read further. ## Classical generative models (theory) ### Generative models Until recently, the success of supervised learning models has completely overshadowed their generative counterparts. So much so, that the popularity of these supervised models might make it difficult to even conceptualize another approach to machine learning. The supervised approach, which feels intuitive to us by now, tries to make accurate predictions on new data, demonstrating that it has learned some underlying relations of the dataset. Generative models are different. Instead of focusing on key relationships between input data and labels, they learn to model the underlying distribution holistically, allowing it to generate new data samples. It's the difference between telling apart cats and dogs, and generating completely new images of cats and dogs. The latter is a richer, but also more difficult task. Why is it more difficult? Adequately discriminating between given data can often be achieved through picking up on a few tell-tale features (like whiskers don't belong on eyes) which help form the strong decision boundaries in the high dimensional space. Consequently, machine learning researchers take great interest in generative models as these learning tasks seem to stab at a deeper notion of learning—trying to reproduce the underlying *creator* function. So given a pool of training data, the goal of a generative model is to learn/reproduce the probability distribution that generated them. A particularly eye-catching application of GANs is generating [high-resolution visuals](https://thispersondoesnotexist.com/) or [composing music](https://magenta.tensorflow.org/gansynth). Below is a generated image of a fake cat. ![computer-generated image of a cat](https://thiscatdoesnotexist.com) <!-- ::: q-block.exercise --> ### Quick quiz <!-- ::: q-quiz(goal="qml-qgan-0") --> <!-- ::: .question --> What would be the most appropriate learning task for a generative model? <!-- ::: --> <!-- ::: .option(correct) --> 1. Producing images of handwritten digits <!-- ::: --> <!-- ::: .option --> 2. Classifying incoming emails as 'spam' or 'not spam' <!-- ::: --> <!-- ::: .option --> 3. Predicting stock prices <!-- ::: --> <!-- ::: .option --> 4. Recommending optimal movies <!-- ::: --> <!-- ::: --> <!-- ::: --> ### Generative adversarial networks A particular class of generative models—generative adversarial networks (GANs)—have witnessed a boom in popularity since they were first proposed in 2014 by Goodfellow I., *et al.* [[1]](https://arxiv.org/abs/1406.2661). To understand the quantum analogue, we first briefly discuss the concept behind classical generative adversarial networks. Briefly put, GANs use a pair of neural networks pitted against each other—the generator and the discriminator. ### The generator The generator's primary aim is to create fake data samples that are convincing enough for the discriminator to label them as real. With each training step, the generator improves at this, until it has near complete overlap to the fixed distribution of real data. To allow the generator to explore a rich space of output non-deterministically, a random noise vector drawn from a [latent space](gloss:latent-space) is fed into the generator as input (usually sampled from a Gaussian distribution). The generator succeeds once it learns to map most points in the latent space (Gaussian noise) onto convincing fake data samples fitting the real distribution. *At the start of training, the latent space is a meaningless n-dimensional Gaussian distribution. But, as the generator evolves, the generator learns to map the noise vectors in the latent space to valid data in the objective dataset.* ### The discriminator The discriminator receives data samples from both the generator and the real distribution (not knowing which is which), and its task is to correctly classify the input data samples as fake or real. Note how the discriminator's objective is directly opposed to its' counterpart. While the discriminator tries to minimize the probability of misclassifying the fake data as real, the generator tries to maximize it. ![Flowchart of a generative adversarial network](images/qgan/gan_general_flow.svg) ### Convergence The GAN finishes training once the generator consistently generates convincing data samples indistinguishable to the real data distribution, leaving the discriminator unable to reasonably decipher between the two. Formally, this point is referred to as the Nash equilibrium (from game theory), at which the generator produces data that corresponds to the real probability distribution, and the *trained* discriminator resorts to guessing between fake or real (50% accuracy). A common analogy between GANs and art theft brings the concept into frame. The generator is often seen as a fake artist trying to produce paintings identical to those found in the museum. The art expert's objective (discriminator) is to tell apart the generator's fake art from the real art. Applied to this analogy, the discriminator assesses the paintings' authenticity while the generator creates the best fakes to fool it. The zero-sum game pushes the two networks to constantly one-up each other. Each improvement of the generator in creating convincing data, is bested by the discriminator's update in improved classification, and vice versa. ![gan_analogy](images/qgan/gan_analogy.png) <!-- ::: q-block.exercise --> ### Quick quiz <!-- ::: q-quiz(goal="qml-qgan-1") --> <!-- ::: .question --> Once the GAN reaches Nash Equilibrium... <!-- ::: --> <!-- ::: .option(correct) --> 1. The discriminator randomly guesses fake/real with equal probability <!-- ::: --> <!-- ::: .option --> 2. The generator returns to producing noise <!-- ::: --> <!-- ::: .option --> 3. The GAN reaches a common failure mode, and the training process must be restarted <!-- ::: --> <!-- ::: .option --> 4. The discriminator guesses that all samples are real <!-- ::: --> <!-- ::: --> <!-- ::: --> ## Quantum Generative Adversarial Networks (theory) In 2018, two companion papers (Ref. [[2]](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.012324), [[3]](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.040502)) brought the idea of GANs to the quantum domain. On a high level, quantum generative adversarial networks (QGANs) equip either the discriminator, the generator, or both with [parameterized quantum circuits](./paramterized-quantum-circuits) with the goal of learning some quantum or classical data. In this chapter, we discuss the fully quantum version of QGANs (quantum generator, quantum discriminator), keeping in mind that the broader principles apply across other types of QGANs. ![qgan_past_work_landscape](images/qgan/past_work_landscape.svg) Image from Ref. [5](https://arxiv.org/abs/1901.00848) There are many analogous concepts, specifically with the adversarial training, between GANs and QGANs. Most importantly, the training structure of GANs largely persists to QGANs. We alternately train the generator & discriminator circuit parameters, while freezing the other's parameters. Through this, the quantum generator learns the target quantum state by proxy of the discriminator's signals, similar to GANs. It's proven that the [stable equilibrium](https://en.wikipedia.org/wiki/Nash_equilibrium) of the quantum adversarial game also occurs when the generator produces data identical to a target distribution [[3]](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.040502). The objective with a fully quantum QGAN is for the quantum generator to reproduce a desired state $|\psi\rangle$, using of course an adversarial training strategy. Similar to other variational quantum algorithms, the quantum generator moves towards this through an iterative update to its parameters directed by a classical optimizer. However, in the case of a QGAN, the generator's cost function landscape itself evolves and becomes better as the discriminator improves at recognizing real samples. Let's look at the general circuit schematics of what we will be building. ![fake_rig](images/qgan/fake_rig.svg) ![real_rig](images/qgan/real_rig.svg) It is worth noting that although we only consider one register each for both the generator and discriminator, we could also add an [auxiliary](gloss:auxiliary) "workspace" register to both the generator and discriminator. The two circuits illustrated above show the generator concatenated with the discriminator and the unitary loading the target data concatenated with the discriminator. The discriminator acts on the output from the generator, respectively, the target data unitary, as well as an additional qubit $|0\rangle$. Finally, the discriminator classification takes place by measuring the last qubit. If the outcome corresponds to $|0\rangle$ respectively $|1\rangle$ the input data is being classified as real or fake respectively. Looking at the first circuit diagram shows us how real data samples are fed into the discriminator. Since we are dealing with a fully quantum QGAN, we need to somehow encode this data of ours into a quantum state to feed into the discriminator. To that end, we prepare the real data through a unitary $\class{u-sub-r}{U_R}$ such that we define: $|\text{Data}_R\rangle= U_R|0\rangle^{\otimes n}$ which is then fed to the parameterized discriminator $\class{u-sub-d}{U}_{D(\class{theta-d}{\vec{\theta_D}})}$ (possibly containing an auxiliary register), and then measured to arrive at the discriminator's score on real data. It is worth noting that $U_{D(\class{theta-d}{\vec{\theta_D}})}$ contains several 2-qubit entangling gates to "transmit" relevant features of the real data to the discriminator's register (workspace). Formalized, the unitary evolution is: $\class{u-sub-d}{U}_{D(\class{theta-d}{\vec{\theta_D}})}(|\text{Data}_R\rangle \otimes |0\rangle)$ where $\class{theta-d}{\vec{\theta_D}}$ is the parameter vector that is updated through a classical optimizer to minimize the [expectation value](gloss:expectation-value) of the last qubit (equivalent to maximizing the probability of the discriminator classifying real data as $|\text{real}\rangle$). In the second circuit, a generated [wave function](gloss:wave-function) aimed to mimic the real one is fed into the discriminator. In other words, the fake quantum state prepared by $U_{G(\class{theta-g}{\vec{\theta_G}})}$, parameterized by $\class{theta-g}{\vec{\theta_G}}$, is applied on the initial state $|0^{\otimes n}\rangle$, giving us: $$|\text{Data}_G\rangle = U_{G(\class{theta-g}{\vec{\theta_G}})}|0^{\otimes n}\rangle$$ $|\text{Data}_G\rangle$ is then fed to the discriminator parameterized by $\class{theta-d}{\vec{\theta_D}}$. So taking the expectation value of the observable $I^{\otimes n}Z$ on $U_{D(\class{theta-d}{\vec{\theta_D}})}(|\text{Data}_G\rangle \otimes |0\rangle)$ gives us the discriminator's score on fake data. It is worth reiterating that $\langle \text{fake} | Z | \text{fake} \rangle = 1$, meaning the discriminator "believes" a given sample to be wholly fake, the expectation value $Z$ with repect to the last qubit will be equal to 1. It then follows naturally that the discriminator would want to correctly "assign" $|0\rangle$ to fake samples and $|1\rangle$ to real samples. The inverse is true for the generator. For it, the optimal scenario would be if the discriminator was completely convinced that its generated quantum state was real, thereby assigning it a $|1\rangle$. We can formalize these adversarial incentives into the following [minimax](gloss:minimax) decision rule (adapted from [reference 2](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.012324)): $\underset{\class{theta-g}{\vec{\theta_G}}}{\min}\underset{\class{theta-d}{\vec{\theta_D}}}{\max} \hspace{3pt} \Bigg(\class{pr}{\text{Pr}}\bigg(\class{d-disc}{D}(\class{theta-d}{\vec{\theta_D}}, R) = |\text{real}\rangle\bigg) + \hspace{2pt} \class{pr}{\text{Pr}}\bigg(\class{d-disc}{D}(\class{theta-d}{\vec{\theta_D}}, G(\class{theta-g}{\vec{\theta_G}})) = |\text{fake}\rangle\bigg)\Bigg)$ <!-- ::: q-block.exercise --> ### Quick quiz <!-- ::: q-quiz(goal="qml-qgan-2") --> <!-- ::: .question --> Quiz question: How do we obtain the probability of a given data sample being real, as assigned by the discriminator? Let $\langle Z \rangle$ be the expectation value of $Z$ with respect to the last qubit. <!-- ::: --> <!-- ::: .option --> 1. $\langle Z\rangle + 1$ <!-- ::: --> <!-- ::: .option --> 2. $\langle Z\rangle + 1/2$ <!-- ::: --> <!-- ::: .option(correct) --> 3. $\frac{\langle Z \rangle + 1}{2}$ <!-- ::: --> <!-- ::: .option --> 4. $2^{\langle Z \rangle}$ <!-- ::: --> <!-- ::: --> Hint: the Z-expectation value is bounded between $[-1, 1]$ <!-- ::: --> ## Full implementation I ### Learning a 2 qubit Bell state Equipped with the adequate theoretical foundation, we can now build an actual QGAN to learn the 2 qubit Bell state through Qiskit! First, we import the standard libraries. ``` import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram ``` ### Defining the real distribution The 2 qubit Bell state is a maximally entangled quantum state, the specific statevector we're interested to reproduce is $|\psi\rangle = \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle) $ Which can be constructed by applying a CNOT gate followed by a Hadamard. ``` # Number of qubits needed to model real distribution REAL_DIST_NQUBITS = 2 real_circuit = QuantumCircuit(REAL_DIST_NQUBITS) real_circuit.h(0) real_circuit.cx(0, 1); ``` <!--- TODO: Widget: mini composer Have them compose Bell state of interest defined above. Stops when constructs properly ---> ### Defining the variational quantum generator and discriminator We now define the generator ansatz. Given the primal nature of existing research into QGANs, the community has not yet settled into any optimal generator or discriminator ansatzes. On that note, most of the [hyperparameters](gloss:hyperparameter) chosen in quantum machine learning are still driven by loose [heuristics](gloss:heuristics), and there's a lot still to be explored. It's worth mentioning that whichever ansatz we choose for the generator, it must have enough [capacity](gloss:capacity) and be [expressible](gloss:expressible) enough to fully reproduce the real quantum state $|\psi\rangle$ defined earlier. So, although the ansatz used here is a little arbitrary, we are confident that it is plenty expressive for the Bell state we are trying to model. ``` # Importing qiskit machine learning parameters from qiskit.circuit import Parameter, ParameterVector ``` Here, we use the `TwoLocal` class to create an ansatz for the variational quantum generator with single qubit gates $RY$ and $RZ$, paired with the engtangling gate $CZ$. ``` from qiskit.circuit.library import TwoLocal generator = TwoLocal(REAL_DIST_NQUBITS, # Parameterized single qubit rotations ['ry', 'rz'], 'cz', # Entangling gate 'full', # Entanglement structure: all to all reps=2, # Number of layers parameter_prefix='θ_g', name='Generator') generator = generator.decompose() # decompose into standard gates generator.draw() ``` ### Variational quantum discriminator We now define the ansatz for the discriminator. In this case, instead of using [`TwoLocal`](https://qiskit.org/documentation/stubs/qiskit.circuit.library.TwoLocal.html#qiskit.circuit.library.TwoLocal), we create a custom ansatz with a [`ParameterVector`](https://qiskit.org/documentation/stubs/qiskit.circuit.ParameterVector.html). ``` disc_weights = ParameterVector('θ_d', 12) discriminator = QuantumCircuit(3, name="Discriminator") discriminator.barrier() discriminator.h(0) discriminator.rx(disc_weights[0], 0) discriminator.ry(disc_weights[1], 0) discriminator.rz(disc_weights[2], 0) discriminator.rx(disc_weights[3], 1) discriminator.ry(disc_weights[4], 1) discriminator.rz(disc_weights[5], 1) discriminator.rx(disc_weights[6], 2) discriminator.ry(disc_weights[7], 2) discriminator.rz(disc_weights[8], 2) discriminator.cx(0, 2) discriminator.cx(1, 2) discriminator.rx(disc_weights[9], 2) discriminator.ry(disc_weights[10], 2) discriminator.rz(disc_weights[11], 2) discriminator.draw() ``` ### Compiling the QGAN With all of our components in place, we now construct the two circuits forming the QGAN. The first feeds generated quantum state into the discriminator and the second is comprised of the discriminator applied on the real state. *It is easy to see how this circuit fulfills the general schematic we outlined earlier.* ``` N_GPARAMS = generator.num_parameters N_DPARAMS = discriminator.num_parameters # Need extra qubit for the discriminator gen_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS+1) gen_disc_circuit.compose(generator, inplace=True) gen_disc_circuit.compose(discriminator, inplace=True) gen_disc_circuit.draw() ``` A very natural question to ask at this point is: why isn't there any noise fed into the generator? As you may recall, in the classical GAN, the latent space was an essential ingredient. If there was no noise for the classical GAN, then it would be impossible for the generator to represent a complete distribution since with each update to its parameters, it would be restricted to output one sample given its deterministic nature. But consider, that in the quantum case, since we are feeding the whole 'fake' wave function directly to the discriminator, the role that noise would play is much less obvious. With or without noise, the variational quantum generator is capable of directly modelling the wave function of interest, so long as the ansatz is of adequate capacity. With that said, there may still be benefits to equipping the variational quantum generator with a latent space of its own, in fact [reference 5](https://arxiv.org/abs/1901.00848) presents a method to allow the quantum generator to model continuous distributions using a latent space as input. But to keep it simple, we will still omit feeding noise into the varational quantum generator. Below, we define the parameterized circuit linking the target distribution with the variational discriminator. ``` real_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS+1) real_disc_circuit.compose(real_circuit, inplace=True) real_disc_circuit.compose(discriminator, inplace=True) real_disc_circuit.draw() ``` ### Constructing the cost function Remember the minimax decision rule we formulated earlier, $\underset{\class{theta-g}{\vec{\theta_G}}}{\min}\underset{\class{theta-d}{\vec{\theta_D}}}{\max} \hspace{3pt} \Bigg(\class{pr}{\text{Pr}}\bigg(\class{d-theta}{D(\class{theta-d}{\vec{\theta_D}}, R)} = |\text{real}\rangle\bigg) + \hspace{2pt} \class{pr}{\text{Pr}}\bigg(D(\class{theta-d}{\vec{\theta_D}}, G(\class{theta-g}{\vec{\theta_G}})) = |\text{fake}\rangle\bigg)\Bigg)$ Constructing a loss function for both the discriminator and generator is now trivial. Starting with the discriminator, we have $\text{Cost}_D = \class{pr}{\text{Pr}}\bigg(D(\class{theta-d}{\vec{\theta_D}}, G(\class{theta-g}{\vec{\theta_G}})) = |\text{real}\rangle\bigg) - \class{pr}{\text{Pr}}\bigg(D(\class{theta-d}{\vec{\theta_D}}, R) = |\text{real}\rangle\bigg)$. Minimizing this entails maximizing the probability of correctly classifying real data while minimizing the probability of mistakenly classifying fake data. As a hallmark of vanilla GANs, the generator’s cost function will simply be the negation of the discriminator’s cost, where the optimal strategy is to maximize the probability of the discriminator misclassifying fake data. We omit the term concerning the real quantum state since the generator's weights leave no effect on it. $\text{Cost}_G = - \class{pr}{\text{Pr}}\bigg(D(\class{theta-d}{\vec{\theta_D}}, G(\class{theta-g}{\vec{\theta_G}})) = |\text{real}\rangle\bigg)$ We now implement the above cost functions. It is worth noticing that after accessing the respective probabilities of each basis state, we arrive at the total probability of a given sample being classified as $|\text{real}\rangle = |1\rangle$ by summing over each basis state that satisfies $|XX1\rangle$ (any state with last qubit measured as $|1\rangle$). However, do note the reverse ordering given Qiskit's [endian](gloss:endian) resulting in $|1XX\rangle$. ``` # We'll use Statevector to retrieve statevector of given circuit from qiskit.quantum_info import Statevector import tensorflow as tf def generator_cost(gen_params: tf.Tensor) -> float: # .numpy() method extracts numpy array from TF tensor curr_params = np.append(disc_params.numpy(), gen_params.numpy()) state_probs = Statevector(gen_disc_circuit .bind_parameters(curr_params) ).probabilities() # Get total prob of measuring |1> on q2 prob_fake_true = np.sum(state_probs[0b100:]) cost = -prob_fake_true return cost def discriminator_cost(disc_params: tf.Tensor) -> float: # .numpy() method extracts numpy array from TF tensor curr_params = np.append(disc_params.numpy(), gen_params.numpy()) gendisc_probs = Statevector(gen_disc_circuit .bind_parameters(curr_params) ).probabilities() realdisc_probs = Statevector(real_disc_circuit. bind_parameters(disc_params.numpy()) ).probabilities() # Get total prob of measuring |1> on q2 prob_fake_true = np.sum(gendisc_probs[0b100:]) # Get total prob of measuring |1> on q2 prob_real_true = np.sum(realdisc_probs[0b100:]) cost = prob_fake_true - prob_real_true return cost ``` We now define a helper function to calculate the [Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between the model and target distribution. This is a common metric used to track the generator's progress while training since it effectively measures the distance between two distributions. A lower KL divergence indicates that the two distributions are similar, with a KL of 0 implying equivalence. ``` def calculate_KL(model_distribution: dict, target_distribution: dict): """Gauge model performance using Kullback Leibler Divergence""" KL = 0 for bitstring, p_data in target_distribution.items(): if np.isclose(p_data, 0, atol=1e-8): continue if bitstring in model_distribution.keys(): KL += (p_data * np.log(p_data) - p_data * np.log(model_distribution[bitstring])) else: KL += p_data * np.log(p_data) - p_data * np.log(1e-6) return KL ``` ### CircuitQNN For simplicity, we use the [`CircuitQNN`](https://qiskit.org/documentation/machine-learning/stubs/qiskit_machine_learning.neural_networks.CircuitQNN.html) that compiles the parameterized circuit and handles calculation of the gradient recipes. Calling the `forward()` method also directly outputs the probability state vectors of the circuit. ``` from qiskit.utils import QuantumInstance from qiskit_machine_learning.neural_networks import CircuitQNN # define quantum instances (statevector and sample based) qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector')) # specify QNN to update generator weights gen_qnn = CircuitQNN(gen_disc_circuit, # parameterized circuit # frozen input arguements (discriminator weights) gen_disc_circuit.parameters[:N_DPARAMS], # differentiable weights (generator weights) gen_disc_circuit.parameters[N_DPARAMS:], sparse=True, # returns sparse probability vector quantum_instance=qi_sv) # specify QNNs to update discriminator weights disc_fake_qnn = CircuitQNN(gen_disc_circuit, # parameterized circuit # frozen input arguments (generator weights) gen_disc_circuit.parameters[N_DPARAMS:], # differentiable weights (discrim. weights) gen_disc_circuit.parameters[:N_DPARAMS], sparse=True, # get sparse probability vector quantum_instance=qi_sv) disc_real_qnn = CircuitQNN(real_disc_circuit, # parameterized circuit [], # no input parameters # differentiable weights (discrim. weights) gen_disc_circuit.parameters[:N_DPARAMS], sparse=True, # get sparse probability vector quantum_instance=qi_sv) ``` Here, we use [TensorFlow Keras](gloss:tensorflow-keras) to create an ADAM optimizer instance for both the generator and the discriminator. The ADAM optimizer is a widely-used optimizer in classical machine learning that uses momentum-based gradient updates. It is known to far outperform vanilla gradient descent. To us the Keras optimizer, we must store the weights as TF variables, which can be easily done through the `tf.Variable` method. We converting back into a `np.ndarray` using the `.numpy()` instance method on the `tf.Variable`. ``` import tensorflow as tf import pickle # to serialize and deserialize variables # Initialize parameters init_gen_params = np.random.uniform(low=-np.pi, high=np.pi, size=(N_GPARAMS,)) init_disc_params = np.random.uniform(low=-np.pi, high=np.pi, size=(N_DPARAMS,)) gen_params = tf.Variable(init_gen_params) disc_params = tf.Variable(init_disc_params) ``` Let's look at our starting point for the generator created from random weights. ``` init_gen_circuit = generator.bind_parameters(init_gen_params) init_prob_dict = Statevector(init_gen_circuit).probabilities_dict() import matplotlib.pyplot as plt fig, ax1 = plt.subplots(1, 1, sharey=True) ax1.set_title("Initial generator distribution") plot_histogram(init_prob_dict, ax=ax1) # Initialize Adam optimizer from Keras generator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02) ``` ### Training ``` # Initialize variables to track metrics while training best_gen_params = tf.Variable(init_gen_params) gloss = [] dloss = [] kl_div = [] ``` There are a few important points on the following training logic: 1. The discriminator's weights are updated fivefold for each generator update. When dealing with classical GANs, it's also not uncommon to see an unbalanced number of training steps between the two networks. In this case, we arrive at a 5:1 ratio as a best practice through trial and error. 2. The `backward()` method of `CircuitQNN` returns the gradients with respect to each weight for each basis state for each batch. In other words, the return shape of `CircuitQNN.backward(...)[1].todense()` is `(num_batches, num_basis_states, num_weights)`. So to arrive at the gradient for $\text{Cost}_D$, we first sum over all the gradients for each basis state satisfying $|1XX\rangle$, and then subtract them according to the $\text{Cost}_D$ function. Recall that the linearity the derivative allows us to distribute it as implemented below. 3. Due to the instability of GAN training, we store the best generator parameters. ``` table_headers = "Epoch / Generator cost / Discriminator cost / KL Div" print(table_headers) for epoch in range(100): """Quantum discriminator parameter updates""" d_steps = 5 # N discriminator updates per generator update for disc_train_step in range(d_steps): # Partial derivatives wrt θ_D d_fake = disc_fake_qnn.backward(gen_params, disc_params )[1].todense()[0, 0b100:] d_fake = np.sum(d_fake, axis=0) d_real = disc_real_qnn.backward([], disc_params )[1].todense()[0, 0b100:] d_real = np.sum(d_real, axis=0) # Recall Cost_D structure grad_dcost = [d_fake[i] - d_real[i] for i in range(N_DPARAMS)] grad_dcost = tf.convert_to_tensor(grad_dcost) # Update disc params with gradient discriminator_optimizer.apply_gradients(zip([grad_dcost], [disc_params])) # Track discriminator loss if disc_train_step % d_steps == 0: dloss.append(discriminator_cost(disc_params)) """Quantum generator parameter updates""" for gen_train_step in range(1): # Compute partial derivatives of prob(fake|true) wrt each # generator weight grads = gen_qnn.backward(disc_params, gen_params) grads = grads[1].todense()[0][0b100:] # Recall Cost_G structure and the linearity of # the derivative operation grads = -np.sum(grads, axis=0) grads = tf.convert_to_tensor(grads) # Update gen params with gradient generator_optimizer.apply_gradients(zip([grads], [gen_params])) gloss.append(generator_cost(gen_params)) """Tracking KL and saving best performing generator weights""" # Create test circuit with updated gen parameters gen_checkpoint_circuit = generator.bind_parameters(gen_params.numpy()) # Retrieve probability distribution of current generator gen_prob_dict = Statevector(gen_checkpoint_circuit ).probabilities_dict() # Constant real probability distribution real_prob_dict = Statevector(real_circuit).probabilities_dict() current_kl = calculate_KL(gen_prob_dict, real_prob_dict) kl_div.append(current_kl) if np.min(kl_div) == current_kl: # New best # serialize+deserialize to simply ensure zero links best_gen_params = pickle.loads(pickle.dumps(gen_params)) if epoch % 10 == 0: # print table for every 10 epochs for header, val in zip(table_headers.split('/'), (epoch, gloss[-1], dloss[-1], kl_div[-1])): print(f"{val:.3g} ".rjust(len(header)+1), end="") print() ``` ### Results visualized We plot the collected metrics to examine how the QGAN learned. ``` fig, (loss, kl) = plt.subplots(2, sharex=True, gridspec_kw={'height_ratios': [0.75, 1]}, figsize=(6,4)) fig.suptitle('QGAN training stats') fig.supxlabel('Training step') loss.plot(range(len(gloss)), gloss, label="Generator loss") loss.plot(range(len(dloss)), dloss, label="Discriminator loss", color="C3") loss.legend() loss.set(ylabel='Loss') kl.plot(range(len(kl_div)), kl_div, label="KL Divergence (zero is best)", color="C1") kl.set(ylabel='KL Divergence') kl.legend() fig.tight_layout(); # Create test circuit with new parameters gen_checkpoint_circuit = generator.bind_parameters( best_gen_params.numpy()) gen_prob_dict = Statevector(gen_checkpoint_circuit).probabilities_dict() real_prob_dict = Statevector(real_circuit).probabilities_dict() # constant fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,3)) plot_histogram(gen_prob_dict, ax=ax1) ax1.set_title("Trained generator distribution") plot_histogram(real_prob_dict, ax=ax2) ax2.set_title("Real distribution") fig.tight_layout() ``` With just 100 [epoch](gloss:epoch)s, we see that the generator has approximated the Bell state $|\psi\rangle$ quite well! Note that reproducing results from above may take a few runs. Due to the fragile nature of training two competing models at once, generative adversarial networks as a whole are notorious for failing to converge—and it is only amplified for QGANs given the lack of best practices. GANs (QGANs inclusive) often suffer from vanishing gradients, often caused by a discriminator that is too good. Another drawback of the adversarial training structure—albeit less prevalant with fully quantum QGANs—is mode collapse, the failure mode of GANs when the generator and discriminator get caught in a cat and mouse chase. The generator spams a certain sample that has a tendency to fool the discriminator, to which the discriminator adapts to over time, but the generator swiftly follows up yet again with another sample. [Learn more on remedies to GAN failure modes](https://developers.google.com/machine-learning/gan/problems). ## Full implementation II ### Learning a normal distribution with OpFlowQNN In the following section, we build a QGAN to learn a 3 qubit normal distribution, while changing a few previous methods along the way. 1. Learning a more complex distribution 2. Using [OpFlowQNN](gloss:opflowqnn) to retrieve expectation values directly 3. Amalgamating the discriminator output qubit to the generator's register ### Defining the real distribution Here we define the real distribution using the `qiskit_finance` module and the generator ansatz that'll be used to model the [Gaussian](gloss:gaussian-distribution). ``` from qiskit_finance.circuit.library import NormalDistribution REAL_DIST_NQUBITS = 3 real_circuit = NormalDistribution(REAL_DIST_NQUBITS, mu=0, sigma=0.15) real_circuit = real_circuit.decompose().decompose().decompose() real_circuit.draw() ``` ### Defining the variational quantum discriminator and generator ``` generator = TwoLocal(REAL_DIST_NQUBITS, # Parameterized single qubit rotations ['ry', 'rz'], 'cz', # Entangling gate 'full', # Entanglement structure - all to all reps=2, # Number of layers parameter_prefix='θ_g', name='Generator') generator = generator.decompose() generator.draw() ``` Now, we define a similar ansatz as before for the discriminator, just with the output qubit defined on `q2` instead of `q3` as one might have expected from the previous example. It's important to note that the qubit used to measure $\class{}{\langle Z\rangle_{\text{out}}}$ is largely irrelevant since the discriminator ansatz can universally transform any given quantum state to a desired one. Previously, we defined the output qubit to be one a separate register to make it more intuitive but there exists no true justification with respect to QGAN performance. ``` disc_weights = ParameterVector('θ_d', 12) discriminator = QuantumCircuit(REAL_DIST_NQUBITS, name="Discriminator") discriminator.barrier() discriminator.h(0) discriminator.rx(disc_weights[0], 0) discriminator.ry(disc_weights[1], 0) discriminator.rz(disc_weights[2], 0) discriminator.h(1) discriminator.rx(disc_weights[3], 1) discriminator.ry(disc_weights[4], 1) discriminator.rz(disc_weights[5], 1) discriminator.h(2) discriminator.rx(disc_weights[6], 2) discriminator.ry(disc_weights[7], 2) discriminator.rz(disc_weights[8], 2) discriminator.cx(1,2) discriminator.cx(0,2) discriminator.rx(disc_weights[9], 2) discriminator.ry(disc_weights[10], 2) discriminator.rz(disc_weights[11], 2) discriminator.draw() ``` Then we construct the complete circuits. ``` N_GPARAMS = generator.num_parameters N_DPARAMS = discriminator.num_parameters ``` ### Compiling the QGAN ``` gen_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS) gen_disc_circuit.compose(generator, inplace=True) gen_disc_circuit.compose(discriminator, inplace=True) gen_disc_circuit.draw() real_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS) real_disc_circuit.compose(real_circuit, inplace=True) real_disc_circuit.compose(discriminator, inplace=True) real_disc_circuit.draw() ``` ### OpflowQNN We employ the [`OpflowQNN`](https://qiskit.org/documentation/machine-learning/stubs/qiskit_machine_learning.neural_networks.OpflowQNN.html) from Qiskit which takes a (parameterized) operator and leverages Qiskit's gradient framework to complete the backward passes. The operator defined here is equivalent to the expectation value of $Z$ with respect to the last qubit. ``` from qiskit.providers.aer import QasmSimulator from qiskit.opflow import (StateFn, PauliSumOp, ListOp, Gradient, AerPauliExpectation) from qiskit_machine_learning.neural_networks import OpflowQNN # set method to calculcate expected values expval = AerPauliExpectation() # define gradient method gradient = Gradient() # define quantum instances (statevector) qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector')) # Circuit wave function gen_disc_sfn = StateFn(gen_disc_circuit) real_disc_sfn = StateFn(real_disc_circuit) # construct operator to retrieve Pauli Z expval of the last qubit H1 = StateFn(PauliSumOp.from_list([('ZII', 1.0)])) # combine operator and circuit to objective function gendisc_op = ~H1 @ gen_disc_sfn realdisc_op = ~H1 @ real_disc_sfn # construct OpflowQNN with the two operators, the input parameters, # the weight parameters, the expected value, and quantum instance. """|fake> => |0> => 1 ; |real> => |1> => -1""" gen_opqnn = OpflowQNN(gendisc_op, # input parameters (discriminator weights) gen_disc_circuit.parameters[:N_DPARAMS], # differentiable weights (generator weights) gen_disc_circuit.parameters[N_DPARAMS:], expval, gradient, qi_sv) # gen wants to to minimize this expval disc_fake_opqnn = OpflowQNN(gendisc_op, # input parameters (generator weights) gen_disc_circuit.parameters[N_DPARAMS:], # differentiable weights (discrim. weights) gen_disc_circuit.parameters[:N_DPARAMS], expval, gradient, qi_sv) # disc wants to maximize this expval disc_real_opqnn = OpflowQNN(realdisc_op, [], # differentiable weights (discrim. weights) gen_disc_circuit.parameters[:N_DPARAMS], expval, gradient, qi_sv) # disc wants to minimize this expval ``` First we initialize the training parameters and define the optimizer ``` ### START init_gen_params = tf.Variable(np.random.uniform(low=-np.pi, high=np.pi, size=(N_GPARAMS))) init_disc_params = tf.Variable(np.random.uniform(low=-np.pi, high=np.pi, size=(N_DPARAMS))) gen_params = init_gen_params disc_params = init_disc_params generator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02) ``` ### Reconstructing the cost function Now we construct the training logic. There are a few key differences to the cost function here that impacts the gradient rule. Since a forward pass now returns the direct expectation value and not a probability statevector, it's important to remind ourselves that $\langle \text{real} |Z| \text{real} \rangle = -1$ and $\langle \text{fake} |Z| \text{fake} \rangle = 1$. Applying similar logic to before, we arrive at the intuition that the discriminator would want to maximize $\langle \text{fake} |Z| \text{fake} \rangle $ when fed fake data and minimize $\langle \text{real} |Z| \text{real}\rangle$ when receiving the real quantum state. In contrast to that, the generator wishes to minimize $\langle \text{fake} |Z| \text{fake}\rangle $, which is akin to the maximizing the probability of the discriminator classifying fake samples as $|\text{real}\rangle = |1\rangle$ We now cement these ideas into the following minimax decision rule defined by the proper expectation values. Let $\rho^{DR}$ and $\rho^{GR}$ be the density matrix representations of $\bigg(U_{D(\class{theta-d}{\vec{\theta_D}})}U_R|0\rangle^{\otimes n+1}\bigg)$ and $\bigg(U_{D(\class{theta-d}{\vec{\theta_D}})} U_{G(\class{theta-g}{\vec{\theta_G}})}|0\rangle^{\otimes n+1}\bigg)$, respectively. Also recall that the expectation value of $\class{sigma-p}{\sigma^P}$ with respect to an arbitrary density matrix $\rho$ is defined as $\text{tr}(\rho \sigma^P)$ (relevant [chapter](/course/quantum-hardware/density-matrix)). While remembering the linearity of the trace operation, we arrive at $\underset{\class{theta-g}{\vec{\theta_G}}}{\min} \hspace{2pt} \underset{\class{theta-d}{\vec{\theta_D}}}{\max} \hspace{3pt} \text{tr}\bigg(\big(\rho^{DG}(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) - \rho^{DR}(\class{theta-d}{\vec{\theta_D}})\Big) Z\bigg)$ Which leads us to the following cost functions (optimum is minimum), $\text{Cost}_D(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) = \text{tr}\bigg(Z\rho^{DR}(\class{theta-d}{\vec{\theta_D}}) \bigg) - \text{tr}\bigg(Z\rho^{DG}(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}})\bigg)$ $\text{Cost}_G(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) = \text{tr}\bigg(Z \rho^{DG}(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) \bigg)$ Meaning that the gradients are, $\nabla _ {\class{theta-d}{\vec{\theta_D}}}\ \text{Cost}_D(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) = \nabla _ {\class{theta-d}{\vec{\theta_D}}}\ \text{tr}\bigg(Z\rho^{DR}(\class{theta-d}{\vec{\theta_D}}) \bigg) - \nabla _ {\class{theta-d}{\vec{\theta_D}}}\ \text{tr}\bigg(Z\rho^{DG}(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}})\bigg)$ $\nabla _ {\class{theta-g}{\vec{\theta_G}}} \ \text{Cost}_G(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) = \nabla _ {\class{theta-g}{\vec{\theta_G}}}\ \text{tr}\bigg(Z \rho^{DG}(\class{theta-d}{\vec{\theta_D}}, \class{theta-g}{\vec{\theta_G}}) \bigg)$ and we're complete! We now have all the information needed to implement it since the `OpFlowQNN.backward()` method computes the constituent gradients for us. Let's implement this. *Keep in mind that the above formulations rely upon our initial definition that $|\text{real}\rangle = |1\rangle$ and $|\text{fake}\rangle = |0\rangle$.* ### Training ``` best_gen_params = init_gen_params gloss = [] dloss = [] kl_div = [] table_headers = "Epoch / Gen. cost / Discrim. cost / KL Div / New best?" print(table_headers) for epoch in range(300): d_steps = 5 """Quantum discriminator parameter update""" for disc_train_step in range(d_steps): grad_dcost_fake = disc_fake_opqnn.backward(gen_params, disc_params)[1][0,0] grad_dcost_real = disc_real_opqnn.backward([], disc_params)[1][0,0] grad_dcost = grad_dcost_real - grad_dcost_fake # as formulated above grad_dcost = tf.convert_to_tensor(grad_dcost) # update disc_params discriminator_optimizer.apply_gradients(zip([grad_dcost], [disc_params])) if disc_train_step % d_steps == 0: dloss.append(discriminator_cost(disc_params)) """Quantum generator parameter update""" for gen_train_step in range(1): # as formulated above grad_gcost = gen_opqnn.backward(disc_params, gen_params)[1][0,0] grad_gcost = tf.convert_to_tensor(grad_gcost) # update gen_params generator_optimizer.apply_gradients(zip([grad_gcost], [gen_params])) gloss.append(generator_cost(gen_params)) """Tracking KL and saving best performing generator weights""" # Create test circuit with updated gen parameters gen_checkpoint_circuit = generator.bind_parameters(gen_params.numpy()) # Retrieve probability distribution of current generator gen_prob_dict = Statevector(gen_checkpoint_circuit ).probabilities_dict() # Constant real probability distribution real_prob_dict = Statevector(real_circuit).probabilities_dict() current_kl = calculate_KL(gen_prob_dict, real_prob_dict) kl_div.append(current_kl) new_best = (np.min(kl_div) == current_kl) if new_best: # Store new best generator weights # serialize+deserialize to just zero links best_gen_params = pickle.loads(pickle.dumps(gen_params)) if epoch % 30 == 0: # print table for header, val in zip(table_headers.split('/'), (epoch, gloss[-1], dloss[-1], kl_div[-1], new_best)): print(f"{val:.3g} ".rjust(len(header)+1), end="") print() ``` ### Results visualized ``` import matplotlib.pyplot as plt fig, (loss, kl) = plt.subplots(2, sharex=True, gridspec_kw={'height_ratios': [0.75, 1]}, figsize=(6,4)) fig.suptitle('QGAN training stats') fig.supxlabel('Training step') loss.plot(range(len(gloss)), gloss, label="Generator loss") loss.plot(range(len(dloss)), dloss, label="Discriminator loss", color="C3") loss.legend() loss.set(ylabel='Loss') kl.plot(range(len(kl_div)), kl_div, label="KL Divergence (zero is best)", color="C1") kl.set(ylabel='KL Divergence') kl.legend() fig.tight_layout(); # Create test circuit with new parameters gen_checkpoint_circuit = generator.bind_parameters(best_gen_params.numpy()) gen_prob_dict = Statevector(gen_checkpoint_circuit).probabilities_dict() real_prob_dict = Statevector(real_circuit).probabilities_dict() # constant fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(9,3)) plot_histogram(gen_prob_dict, ax=ax1) ax1.set_title("Trained generator distribution") plot_histogram(real_prob_dict, ax=ax2) ax2.set_title("Real distribution") ax2.set_ylim([0,.5]) fig.tight_layout() ``` Impressive! <!-- ::: q-block.exercise --> ### Quick quiz Drag and drop the lines of pseudocode into their correct order to complete the program. q-drag-and-drop-code .line For n:=0 to N_EPOCHS do: .line For d:=0 to num_disc_steps do: .line Compute Z expectation value of d_out qubit when fed fake and real data .line.md Update $\vec{\theta}_{D}$ according to $\nabla_{\vec{\theta}_{D}}\text{Cost}_D(\class{theta-d}{\vec{\theta_D}},\class{theta-g}{\vec{\theta_G}})$ using ADAM optimizer .line For g:=0 to num_gen_steps do .line Compute Z-expectation value of d_out qubit when fed fake data .line.md Update $\vec{\theta}_{G}$ according to $\nabla_{\vec{\theta}_G}\text{Cost}_G(\class{theta-d}{\vec{\theta_D}},\class{theta-g}{\vec{\theta_G}})$ using ADAM optimizer .line Compute KL divergence between G and R .line If current KL divergence is the lowest yet do .line Save current generator weights <!-- ::: --> ## Potential applications The development of QGANs is still emerging, so there remains much more research to be done on potential applications. However, there is hope that QGANs will enable sampling and manipulation of classically intractable probability distributions (difficult to sample from classically). One particularly interesting application of QGANs is efficient, approximate data loading. In order to see a quantum advantage in data processing - using, e.g., quantum amplitude estimation [6] — we need to load the input data onto a quantum state. However, loading classical data into a quantum circuit is often expensive, and generally even exponentially expensive [7, 8]. Therefore, the data loading complexity can easily impair any potential quantum advantage. As shown in reference [4], QGANs offer an interesting approach to efficiently learn and load approximations of generic probability distributions, as demonstrated in this [tutorial](https://qiskit.org/documentation/machine-learning/tutorials/04_qgans_for_loading_random_distributions.html). Once the probability distribution is loaded into a quantum state, a quantum algorithm such as quantum amplitude estimation can process the data. As shown in this [tutorial](https://qiskit.org/documentation/tutorials/finance/10_qgan_option_pricing.html), this workflow may then be used to, e.g., price options with a potential quadratic quantum speedup. Additionally, in quantum chemistry, quantum computers are believed to have an intrinsic advantage in being able to represent and manipulate correlated [fermionic](gloss:fermionic) states (molecules). A natural question one could ask is: given an adequate ansatz, could QGANs be used to generate new types of molecules that fit the mould of an inputted set of materials/molecules possibly obtained through VQE? That would involve extending QGANs into the conditional realm (inputting a conditional label to both the generator and discriminator, see [conditional GANs](https://arxiv.org/abs/1411.1784) but as of now, it remains an open question. <!-- ::: q-block.exercise --> ### Try it To extend the ideas you've just learned, create a QGAN to learn a 3 qubit normal distribution but with a classical discriminator. [Reference 4](https://arxiv.org/abs/1904.00043) will be helpful. You may use the same generator ansatz we've used above, but ensure the discriminator's neural network is adequately sized to match the quantum generator's power. [Try in IBM Quantum Lab](https://quantum-computing.ibm.com/lab) <!-- ::: --> ## References 1. I. J. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D.Warde-Farley, S. Ozair, A. Courville, and Y. Bengio, in *Proceedings of the 27th International Conference on Neural Information Processing Systems* (MIT Press, Cambridge, MA, 2014), Vol. 2, pp. 2672–2680, [arXiv:1406.2661](https://arxiv.org/abs/1406.2661). 2. P.-L. Dallaire-Demers, & N. Killoran, *Quantum generative adversarial networks,* Phys. Rev. A 98, 012324 (2018), [doi.org:10.1103/PhysRevA.98.012324](https://doi.org/10.1103/PhysRevA.98.012324), [arXiv:1804.08641](https://arxiv.org/abs/1804.08641) 3. S. Lloyd, & C. Weedbrook, *Quantum generative adversarial learning*. Phys. Rev. Lett. 121, 040502 (2018), [doi.org:10.1103/PhysRevLett.121.040502](https://doi.org/10.1103/PhysRevLett.121.040502), [arXiv:1804.09139](https://arxiv.org/abs/1804.09139) 4. C. Zoufal, A. Lucchi, and S. Woerner, *Quantum generative adversarial networks for learning and loading random distributions,* npj Quantum Information, 5, Article number: 103 (2019), [doi.org/10.1038/s41534-019-0223-2](https://doi.org/10.1038/s41534-019-0223-2), [arXiv:1904.00043](https://arxiv.org/abs/1904.00043) 5. J. Romero, A. Aspuru-Guzik, *Variational quantum generators: Generative adversarial quantum machine learning for continuous distributions* (2019), [arxiv.org:1901.00848](https://arxiv.org/abs/1901.00848) 6. Brassard, G., Hoyer, P., Mosca, M. & Tapp, A. *Quantum amplitude amplification and estimation*. Contemp. Math. 305, 53–74 (2002), [doi.org/10.1090/conm/305/05215](http://www.ams.org/books/conm/305/), [arXiv:quant-ph/0005055](https://arxiv.org/abs/quant-ph/0005055) 7. L. K. Grover. *Synthesis of quantum superpositions by quantum computation*. Phys. Rev. Lett., 85, (2000), [doi.org/10.1103/PhysRevLett.85.1334](https://link.aps.org/doi/10.1103/PhysRevLett.85.1334) 8. M. Plesch and ˇC. Brukner. *Quantum-state preparation with universal gate decompositions*. Phys. Rev. A, 83, (2010), [doi.org/10.1103/PhysRevA.83.032302](https://doi.org/10.1103/PhysRevA.83.032302) ``` import qiskit.tools.jupyter %qiskit_version_table ```
github_jupyter
## Working with filter pipelines This Jupyter notebook explains the workflow of setting up and configuring a ground point filtering pipeline. This is an advanced workflow for users that want to define their own filtering workflows. For basic use, preconfigured pipelines are (or rather: will be) provided by `adaptivefiltering`. As always, we first need to import our library: ``` import adaptivefiltering ``` Also, we need to load at least one data set which we will use to interactively preview our filter settings. Note that for a good interactive experience with no downtimes, you should restrict your datasets to a reasonable size (see the [Working with datasets](datasets.ipynb) notebook for how to do it). ``` dataset = adaptivefiltering.DataSet(filename="500k_NZ20_Westport.laz") ``` ### Filtering backends `adaptivefiltering` does not implement its own ground point filtering algorithms. Instead, algorithms from existing packages are accessible through a common interface. Currently, the following backends are available: * [PDAL](https://pdal.io/): The Point Data Abstraction Library is an open source library for point cloud processing. * [OPALS](https://opals.geo.tuwien.ac.at/html/stable/index.html) is a proprietary library for processing Lidar data. It can be tested freely for datasets <1M points. * [LASTools](https://rapidlasso.com/) has a proprietary tool called `lasground_new` that can be used for ground point filtering. PDAL is always available when using `adaptivefiltering` and is used internally for many tasks that are not directly related to ground point filtering. In order to enable the OPALS backend, `adaptivefiltering` needs to be given the information where your OPALS installation (potentially including your license key) is located. This can either be done by setting the environment variable `OPALS_DIR` or by setting the path at runtime: ``` adaptivefiltering.set_opals_directory("/path/to/opals") ``` Similarly, you can set the path to your installation of LASTools either through the environment variable `LASTOOLS_DIR` or at runtime: ``` adaptivefiltering.set_lastools_directory("/path/to/lastools") ``` Please note that LASTools only ships Windows binaries. Therefore, you will need [Wine](https://www.winehq.org/) installed on your system to successfully use the LASTools backend. ### Configuring a filter pipeline The main pipeline configuration is done by calling the `pipeline_tuning` function with your dataset as the parameter. This will open the interactive user interface which waits for your user input until you hit the *Finalize* button. The configured filter is then accessible as the Python object `pipeline`: ``` pipeline = adaptivefiltering.pipeline_tuning(dataset) ``` If you want to inspect multiple data sets in parallel while tuning a pipeline, you can do so by passing a list of datasets to the `pipeline_tuning` function. Note that `adaptivefiltering` does currently not parallelize the execution of filter pipeline execution which may have a negative impact on wait times while tuning with multiple parameters. ``` pipeline2 = adaptivefiltering.pipeline_tuning(datasets=[dataset, dataset]) ``` ### Storing and reloading filter pipelines Pipeline objects can be stored on disk with the `save_filter` command from `adaptivefiltering`. We typically use the extension `json` for filters. It stands for *JavaScript Object Notation* and is a widely used format for storing custom data structures: ``` adaptivefiltering.save_filter(pipeline, "myfilter.json") ``` The appropriate counterpart is `load_filter`, which restores the pipeline object from a file: ``` old_pipeline = adaptivefiltering.load_filter("myfilter.json") ``` A filter pipeline loaded from a file can be edited using the `pipeline_tuning` command by passing it to the function. As always, the pipeline object returned by `pipeline_tuning` will be a new object - no implicit changes of the loaded pipeline object will occur: ``` edited_pipeline = adaptivefiltering.pipeline_tuning(dataset, pipeline=old_pipeline) ``` ### Applying filter pipelines to data Pipeline objects can also be used to transform data sets by applying the ground point filtering algorithms. This is one of the core tasks of the `adaptivefiltering` library, but this will rarely be done in this manual fashion, as we will provide additional interfaces for (locally adaptive) application of filter pipelines: ``` filtered = pipeline.execute(dataset) ```
github_jupyter
``` %matplotlib inline ``` (beta) Building a Convolution/Batch Norm fuser in FX ******************************************************* **Author**: `Horace He <https://github.com/chillee>`_ In this tutorial, we are going to use FX, a toolkit for composable function transformations of PyTorch, to do the following: 1) Find patterns of conv/batch norm in the data dependencies. 2) For the patterns found in 1), fold the batch norm statistics into the convolution weights. Note that this optimization only works for models in inference mode (i.e. `mode.eval()`) We will be building the fuser that exists here: https://github.com/pytorch/pytorch/blob/orig/release/1.8/torch/fx/experimental/fuser.py First, let's get some imports out of the way (we will be using all of these later in the code). ``` from typing import Type, Dict, Any, Tuple, Iterable import copy import torch.fx as fx import torch import torch.nn as nn ``` For this tutorial, we are going to create a model consisting of convolutions and batch norms. Note that this model has some tricky components - some of the conv/batch norm patterns are hidden within Sequentials and one of the BatchNorms is wrapped in another Module. ``` class WrappedBatchNorm(nn.Module): def __init__(self): super().__init__() self.mod = nn.BatchNorm2d(1) def forward(self, x): return self.mod(x) class M(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 1, 1) self.bn1 = nn.BatchNorm2d(1) self.conv2 = nn.Conv2d(1, 1, 1) self.nested = nn.Sequential( nn.BatchNorm2d(1), nn.Conv2d(1, 1, 1), ) self.wrapped = WrappedBatchNorm() def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.conv2(x) x = self.nested(x) x = self.wrapped(x) return x model = M() model.eval() ``` Fusing Convolution with Batch Norm ----------------------------------------- One of the primary challenges with trying to automatically fuse convolution and batch norm in PyTorch is that PyTorch does not provide an easy way of accessing the computational graph. FX resolves this problem by symbolically tracing the actual operations called, so that we can track the computations through the `forward` call, nested within Sequential modules, or wrapped in an user-defined module. ``` traced_model = torch.fx.symbolic_trace(model) print(traced_model.graph) ``` This gives us a graph representation of our model. Note that both the modules hidden within the sequential as well as the wrapped Module have been inlined into the graph. This is the default level of abstraction, but it can be configured by the pass writer. More information can be found at the FX overview https://pytorch.org/docs/master/fx.html#module-torch.fx Fusing Convolution with Batch Norm ---------------------------------- Unlike some other fusions, fusion of convolution with batch norm does not require any new operators. Instead, as batch norm during inference consists of a pointwise add and multiply, these operations can be "baked" into the preceding convolution's weights. This allows us to remove the batch norm entirely from our model! Read https://nenadmarkus.com/p/fusing-batchnorm-and-conv/ for further details. The code here is copied from https://github.com/pytorch/pytorch/blob/orig/release/1.8/torch/nn/utils/fusion.py clarity purposes. ``` def fuse_conv_bn_eval(conv, bn): """ Given a conv Module `A` and an batch_norm module `B`, returns a conv module `C` such that C(x) == B(A(x)) in inference mode. """ assert(not (conv.training or bn.training)), "Fusion only for eval!" fused_conv = copy.deepcopy(conv) fused_conv.weight, fused_conv.bias = \ fuse_conv_bn_weights(fused_conv.weight, fused_conv.bias, bn.running_mean, bn.running_var, bn.eps, bn.weight, bn.bias) return fused_conv def fuse_conv_bn_weights(conv_w, conv_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b): if conv_b is None: conv_b = torch.zeros_like(bn_rm) if bn_w is None: bn_w = torch.ones_like(bn_rm) if bn_b is None: bn_b = torch.zeros_like(bn_rm) bn_var_rsqrt = torch.rsqrt(bn_rv + bn_eps) conv_w = conv_w * (bn_w * bn_var_rsqrt).reshape([-1] + [1] * (len(conv_w.shape) - 1)) conv_b = (conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b return torch.nn.Parameter(conv_w), torch.nn.Parameter(conv_b) ``` FX Fusion Pass ---------------------------------- Now that we have our computational graph as well as a method for fusing convolution and batch norm, all that remains is to iterate over the FX graph and apply the desired fusions. ``` def _parent_name(target : str) -> Tuple[str, str]: """ Splits a qualname into parent path and last atom. For example, `foo.bar.baz` -> (`foo.bar`, `baz`) """ *parent, name = target.rsplit('.', 1) return parent[0] if parent else '', name def replace_node_module(node: fx.Node, modules: Dict[str, Any], new_module: torch.nn.Module): assert(isinstance(node.target, str)) parent_name, name = _parent_name(node.target) setattr(modules[parent_name], name, new_module) def fuse(model: torch.nn.Module) -> torch.nn.Module: model = copy.deepcopy(model) # The first step of most FX passes is to symbolically trace our model to # obtain a `GraphModule`. This is a representation of our original model # that is functionally identical to our original model, except that we now # also have a graph representation of our forward pass. fx_model: fx.GraphModule = fx.symbolic_trace(model) modules = dict(fx_model.named_modules()) # The primary representation for working with FX are the `Graph` and the # `Node`. Each `GraphModule` has a `Graph` associated with it - this # `Graph` is also what generates `GraphModule.code`. # The `Graph` itself is represented as a list of `Node` objects. Thus, to # iterate through all of the operations in our graph, we iterate over each # `Node` in our `Graph`. for node in fx_model.graph.nodes: # The FX IR contains several types of nodes, which generally represent # call sites to modules, functions, or methods. The type of node is # determined by `Node.op`. if node.op != 'call_module': # If our current node isn't calling a Module then we can ignore it. continue # For call sites, `Node.target` represents the module/function/method # that's being called. Here, we check `Node.target` to see if it's a # batch norm module, and then check `Node.args[0].target` to see if the # input `Node` is a convolution. if type(modules[node.target]) is nn.BatchNorm2d and type(modules[node.args[0].target]) is nn.Conv2d: if len(node.args[0].users) > 1: # Output of conv is used by other nodes continue conv = modules[node.args[0].target] bn = modules[node.target] fused_conv = fuse_conv_bn_eval(conv, bn) replace_node_module(node.args[0], modules, fused_conv) # As we've folded the batch nor into the conv, we need to replace all uses # of the batch norm with the conv. node.replace_all_uses_with(node.args[0]) # Now that all uses of the batch norm have been replaced, we can # safely remove the batch norm. fx_model.graph.erase_node(node) fx_model.graph.lint() # After we've modified our graph, we need to recompile our graph in order # to keep the generated code in sync. fx_model.recompile() return fx_model ``` <div class="alert alert-info"><h4>Note</h4><p>We make some simplifications here for demonstration purposes, such as only matching 2D convolutions. View https://github.com/pytorch/pytorch/blob/master/torch/fx/experimental/fuser.py for a more usable pass.</p></div> Testing out our Fusion Pass ----------------------------------------- We can now run this fusion pass on our initial toy model and verify that our results are identical. In addition, we can print out the code for our fused model and verify that there are no more batch norms. ``` fused_model = fuse(model) print(fused_model.code) inp = torch.randn(5, 1, 1, 1) torch.testing.assert_allclose(fused_model(inp), model(inp)) ``` Benchmarking our Fusion on ResNet18 ---------- We can test our fusion pass on a larger model like ResNet18 and see how much this pass improves inference performance. ``` import torchvision.models as models import time rn18 = models.resnet18() rn18.eval() inp = torch.randn(10, 3, 224, 224) output = rn18(inp) def benchmark(model, iters=20): for _ in range(10): model(inp) begin = time.time() for _ in range(iters): model(inp) return str(time.time()-begin) fused_rn18 = fuse(rn18) print("Unfused time: ", benchmark(rn18)) print("Fused time: ", benchmark(fused_rn18)) ``` As we previously saw, the output of our FX transformation is (Torchscriptable) PyTorch code, we can easily `jit.script` the output to try and increase our performance even more. In this way, our FX model transformation composes with Torchscript with no issues. ``` jit_rn18 = torch.jit.script(fused_rn18) print("jit time: ", benchmark(jit_rn18)) ############ # Conclusion # ---------- # As we can see, using FX we can easily write static graph transformations on # PyTorch code. # # Since FX is still in beta, we would be happy to hear any # feedback you have about using it. Please feel free to use the # PyTorch Forums (https://discuss.pytorch.org/) and the issue tracker # (https://github.com/pytorch/pytorch/issues) to provide any feedback # you might have. ```
github_jupyter
``` import torch import torch.nn as nn import torch.optim as optim import torchtext import torchtext.data as data import torch.nn.functional as F import matplotlib.pyplot as plt import os import random %matplotlib inline %config Completer.use_jedi = False ``` ```bash bash ./preprocess.sh dump-tokenized cat ~/data/tokenized/wiki_ko_mecab.txt ~/data/tokenized/ratings_mecab.txt ~/data/tokenized/korquad_mecab.txt > ~/data/tokenized/corpus_mecab.txt ``` <h1>2-1. Neural Probabilistic Language Model<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Create-dataset" data-toc-modified-id="Create-dataset-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Create dataset</a></span></li><li><span><a href="#Build-the-model" data-toc-modified-id="Build-the-model-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Build the model</a></span></li><li><span><a href="#Train-the-model" data-toc-modified-id="Train-the-model-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Train the model</a></span></li><li><span><a href="#Embedding-result" data-toc-modified-id="Embedding-result-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Embedding result</a></span></li></ul></div> ## Create dataset * write each sample as a CSV file ``` n_gram = 3 corpus_path = os.path.join(os.getenv("HOME"), "data/tokenized/corpus_mecab.txt") csv_path = os.path.join(os.getenv("HOME"), "data/csv/") ngram_path = os.path.join(csv_path, f"{n_gram}gram_corpus_mecab.csv") ``` ```python import tqdm import csv with open(corpus_path) as r: if not os.path.isdir(csv_path): os.mkdir(csv_path) with open(ngram_path, "w", encoding='utf-8') as w: fieldnames = ['text', 'label'] writer = csv.DictWriter(w, fieldnames=fieldnames) #writer.writeheader() for idx, sample in tqdm.tqdm(enumerate(r)): sentence = sample.split(" ") for i in range(len(sentence)-n_gram): text = " ".join(sentence[i:i+n_gram]) target = sentence[i+n_gram] writer.writerow({"text": text, "label": target}) ``` ```bash # `gsplit` if on macOS split -d -l 1000000 ~/data/csv/3gram_corpus_mecab.csv ~/data/csv/3gram_corpus_mecab_ --additional-suffix=.csv ``` * build custom torchtext dataset with `torchtext.data.TabularDataset`. ``` TEXT = data.Field() LABEL = data.Field() datafiles = [fname for fname in os.listdir(csv_path) if fname.startswith("3gram_corpus_mecab_")] dataset = data.TabularDataset( os.path.join(csv_path, datafiles[0]), format="csv", skip_header=True, fields=[ ("text", TEXT), ("label", LABEL) ] ) ``` * train only on small portion (for speed) ``` trainset, testset = dataset.split(0.1, random_state=random.seed(0)) trainset, validationset = trainset.split(0.9, random_state=random.seed(0)) ``` * Build vocabulary ``` MAX_VOCAB_SIZE = 100_000 TEXT.build_vocab(trainset, max_size=MAX_VOCAB_SIZE) LABEL.build_vocab(trainset) ``` * Now we build a `BucketIterator` for our model. ``` BATCH_SIZE = 64 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device trainiter, validationiter, testiter = torchtext.data.BucketIterator.splits( (trainset, validationset, testset), batch_size=BATCH_SIZE, device=device ) ``` ## Build the model ![bengio et al.png](https://miro.medium.com/max/2408/1*EqKiy4-6tuLSoPP_kub33Q.png) ``` VOCAB_SIZE = len(TEXT.vocab) N_GRAM = 3 EMBEDDING_DIM = 128 HIDDEN_DIM = 128 class NPLM(nn.Module): def __init__(self, vocab_size, n_gram, embedding_dim, hidden_dim): super(NPLM, self).__init__() self.vocab_size = vocab_size self.n_gram = n_gram self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim # embedding self.embedding = nn.Embedding(vocab_size, embedding_dim) # affine layers for tanh self.linear1 = nn.Linear(n_gram * embedding_dim, hidden_dim) self.linear2 = nn.Linear(hidden_dim, vocab_size, bias=False) # affine layer for residual connection self.linear3 = nn.Linear(n_gram * embedding_dim, vocab_size) def forward(self, x): x = self.embedding(x) #print(x.shape) x = x.view(-1, self.embedding_dim * self.n_gram) #print(x.shape) x1 = torch.tanh(self.linear1(x)) x1 = self.linear2(x1) x2 = self.linear3(x) x = x1 + x2 #print(x.shape) return x ``` ## Train the model * train the model ``` model = NPLM(VOCAB_SIZE, N_GRAM, EMBEDDING_DIM, HIDDEN_DIM) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9) model = model.to(device) criterion = criterion.to(device) def accuracy(pred, target): pred = torch.argmax(torch.softmax(pred, dim=1), dim=1) correct = (pred == target).float() #print(pred.shape, correct.shape) return correct.sum() / len(correct) def train(model, iterator, criterion, optimizer): loss_epoch = 0. acc_epoch = 0. for batch in trainiter: model.zero_grad() out = model(batch.text) #print("output:", out.shape) out = out.squeeze(0) #print("output (squeezed):", out.shape) target = batch.label.squeeze(0) #print("target:", target.shape) loss = criterion(out, target) loss.backward() optimizer.step() loss_epoch += loss.item() acc_epoch += accuracy(out, target).item() return loss_epoch, acc_epoch N_EPOCH = 200 losses = [] accs = [] for i in range(1, N_EPOCH+1): loss_epoch, acc_epoch = train(model, trainiter, criterion, optimizer) losses.append(loss_epoch) accs.append(acc_epoch) if i % 5 == 0: print(f"epoch: {i:03}, loss: {loss_epoch/len(trainiter): .3f}, acc: {acc_epoch/len(trainiter): .4f}") ``` * save the intermediate model ``` torch.save(model.state_dict(), "./NPLM_SGD_lr0.01_momentum0.9_epoch200.pth") ``` ## Embedding result * load the pre-trained final model ``` model = NPLM(VOCAB_SIZE, N_GRAM, EMBEDDING_DIM, HIDDEN_DIM) model.load_state_dict(torch.load("./NPLM_SGD_lr0.01+0.005+0.001_momentum0.9_epoch200+115+50.pth")) model.eval() embedding = model.embedding ``` * plot the embeddings ``` from sklearn.manifold import TSNE test_words = TEXT.vocab.freqs.most_common(1000) test_words_raw = [w for w, _ in test_words if len(w) > 1] test_words = [TEXT.vocab.stoi[w] for w in test_words_raw] with torch.no_grad(): embed_xy = embedding(torch.tensor(test_words)).detach().numpy() embed_xy = TSNE(n_components=2).fit_transform(embed_xy) embed_x, embed_y = list(zip(*embed_xy)) plt.figure(figsize=(16,16)) for xy, word in zip(embed_xy, test_words_raw): plt.annotate(word, xy, clip_on=True) plt.title("Word Embedding") plt.scatter(embed_x, embed_y, alpha=.3) plt.axhline([0], ls=":", c="grey") plt.axvline([0], ls=":", c="grey") ```
github_jupyter
<a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/numpyexercises.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # 100 numpy exercises <https://github.com/rougier/numpy-100> にあったもののコピー。 とりあえず使い方がわからない。まあいいか。やってみよう。 (1) numpyをインポートする。 ``` import numpy as np ``` # (2) numpy のバージョンと configuration を print する。 ``` print (np.__version__) # np.show_config() # 実験: numpy がどんな関数やメソッドを持っているかは dir(np) とすればわかる。version も、show_config もある。 # dir(np) ``` (3) サイズ $10$ の null ベクトルを作る。 ``` import numpy as np Z = np.zeros(10) print(Z) # 実験 print (type(Z)) print(Z == [0,0,0,0,0,0,0,0,0,0]) print(len(Z)) print(len([0,0,0,0,0,0,0,0,0,0])) print(list(Z) == [0,0,0,0,0,0,0,0,0,0]) print(np.array([1,2,3]) == np.array([1,2,3])) print(np.array((1,2,3))) ``` #### (4) 配列 array のメモリーサイズを調べる方法。 ``` Z = np.zeros((10,10)) print("%d bytes" % (Z.size * Z.itemsize)) # 実験 print (Z.size) print(Z.itemsize) ``` #### (5) numpy の add 関数のドキュメントを得る。 次のコメントアウトした %run `python "import numpy; numpy.info(numpy.add)"` は使えなかった。 help(np.add) でいいと思う。 ``` # %run `python "import numpy; numpy.info(numpy.add)"` # 実験 # np.info(np.add) help(np.add) ``` #### (6) 5番目のアイテムの値を 1 にする。 ``` Z[4] = 1 print(Z) ``` #### (7) 値が10から49のベクトルを作る。 ``` Z = np.arange(10,50) print(Z) # 実験 print(range(10,50)) print(list(range(10,50))) # print(np.ndarray(list(range(10,50)))) print(np.array(list(range(10,50)))) print(type(np.array(list(range(10,50))))) ``` #### (8) ベクトルを逆順にする。 ``` Z = np.arange(10) Z = Z[::-1] print(Z) # 実験 Z = list(range(10)) Z.reverse() print(Z) Y = np.array([3,2,1,0,1,1,5]) print(Y) Y = Y[::-1] print(Y) ``` #### (9) 3x3 の行列を作る。 ``` import numpy as np Z = np.arange(9).reshape(3, 3) Z np.array([0,1,2,3,4,5,6,7,8]).reshape(3,3) # 実験 arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) print(arr) mat = np.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) print(mat) print(type(mat)) ``` #### (10) ゼロでない要素のインデクスを見つける。 [1,2,0,0,4,0] ``` import numpy as np nz = np.nonzero([1,2,0,0,4,0]) print(nz) # 実験 print(list(enumerate([1,2,0,0,4,0]))) print([x for (x,y) in list(enumerate([1,2,0,0,4,0])) if y>0]) print([x for (x,y) in list(enumerate([1,2,0,0,-4,0])) if y!=0]) ``` #### (11) 3x3 の単位行列を作る。 ``` Z = np.eye(3) print(Z) # 実験 print(np.identity(3)) ``` #### (12) 要素がランダムな 3x3x3 の行列を作る。 ``` Z = np.random.random((3,3,3)) print(Z) # 実験 help(np.random.random) # 実験 print([int(x*10) for x in np.random.random(9)]) np.array([int(x*10) for x in np.random.random(9)]).reshape(3,3) ``` #### (13) 10x10 のランダムな値の配列を作って、その最大値と最小値を調べる。 ``` Z = np.random.random((10,10)) Zmin, Zmax = Z.min(), Z.max() print(Zmin, Zmax) ``` #### (14) ランダムな値のサイズ 30 のベクトルを作って平均を調べる。 ``` Z = np.random.random(30) m = Z.mean() print(m) # 実験 sum(list(Z)) / 30 # 実験 import numpy as np print(type(np.random.random())) help(np.random.random) ``` #### (15) 上下左右の端が 1 で、中が 0 の配列を作る。 ``` Z = np.ones((10,10)) Z[1:-1,1:-1] = 0 print(Z) # 実験 z = np.array([1 for x in range(100)]).reshape(10,10) z.reshape(10,10) z[1:-1,1:-1] = 0 print(z) ``` #### (16) すでにある配列に 0 で縁をつける。 ``` Z = np.ones((5,5)) Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0) print(Z) # # Using fancy indexing # Z = np.ones((5,5)) # Z[:, [0, -1]] = 0 # Z[[0, -1], :] = 0 # print(Z) # 実験 Z = np.ones((5,5)) Z=[[0]+list(l)+[0] for l in Z] Z= [[0]*len(Z[0])]+Z+[[0]*len(Z[0])] Z ``` #### (17) np.nan について調べる。 np.nan は値を持たない float。 欠損値。 NaN = Not a Number ``` import numpy as np print(0*np.nan) #=> nan print(np.nan==np.nan) #=> False print(np.inf > np.nan) #=> False print(np.nan - np.nan) #=> nan print(np.nan in set([np.nan])) #=> True print(0.3 == 3 * 0.1) #=> False # 実験 print() print(np.nan) #=> nan print(type(np.nan)) #=> <class 'float'> print(True if np.nan else False) #=> True print(None) #=> None print(type(None)) #=> <class 'NoneType'> print(True if None else False) #=> False print() print(np.isnan((np.nan))) %%writefile height.csv name,height Ahmad,175.2 Eli, Kobe,180.8 %ls # 実験 import pandas as pd import numpy as np df = pd.read_csv('height.csv') print(df) print() for idx in df.index: print(np.isnan(df.loc[idx, 'height'])) ``` #### (18) 5x5 の行列で、対角線の1つ下に 1,2,3,4 の値を入れる。 ``` Z = np.diag(1+np.arange(4),k=-1) print(Z) # 実験 print(np.diag(np.array([1,2,3,4]), k=-1)) print(np.arange(4)) print(1+np.arange(4)) print(np.array([1+x for x in range(4)])) ``` #### (19) 8x8 のチェッカーボードパターンの行列を作る。 ``` Z = np.zeros((8,8),dtype=int) Z[1::2,::2] = 1 Z[::2,1::2] = 1 print(Z) # 実験 Z = np.zeros((8,8),dtype=int) Z[1::2,0::3] = 1 print(Z) ``` #### (20) 6x7x8 の形の配列の 100 番目の座標 x,y,z を求める。 ``` print(np.unravel_index(99,(6,7,8))) # 実験 print(type(np.unravel_index(99,(6,7,8)))) print(np.where(np.array(range(6*7*8)).reshape(6,7,8) == 99)) tuple([int(x) for x in np.where(np.array(range(6*7*8)).reshape(6,7,8) == 99)]) ``` #### (21) tile 関数を使って 8x8 の行列を作る。 ``` Z = np.tile( np.array([[0,1],[1,0]]), (4,4)) print(Z) # 実験 Z = np.tile( np.array([[0,8],[8,8,8]]), (2,4)) print(Z) print() Z = np.tile( np.array([[0,8],[8,8]]), (2,4)) print(Z) ``` #### (22) 5x5 のランダムな値の行列を正規化 normalize する。 ``` Z = np.random.random((5,5)) Z = (Z - np.mean (Z)) / (np.std (Z)) print(Z) # 実験 Z = np.random.randint(10, size=(5,5)) print(Z) print() Z = (Z - np.mean (Z)) print(Z) ``` #### (23) カスタム dtype を作り、4つの unsigned bytes (RGBA) で色を表現する。 ``` # color = np.dtype([("r", np.ubyte, 1), # ("g", np.ubyte, 1), # ("b", np.ubyte, 1), # ("a", np.ubyte, 1)]) color = np.dtype([("r", np.ubyte), ("g", np.ubyte), ("b", np.ubyte), ("a", np.ubyte)]) print(color) # 実験 a = np.array([1,2,3]) print(a) print(a.dtype) a = np.array([1,2.0,3.5]) print(a.dtype) a = np.array([1,2,3], dtype='int32') print(a.dtype) a = np.array([1,2,3], dtype='float') print(a) print(a.dtype) a = np.array([1,2.0,3.5], dtype='int') print(a) print(a.dtype) f = np.array([0, 3, 0, -1], dtype = 'bool') print(f) ``` #### (24) 5x3 の行列と 3x2 の行列の積を求める。 ``` Z = np.dot(np.ones((5,3)), np.ones((3,2))) print(Z) # Alternative solution, in Python 3.5 and above Z = np.ones((5,3)) @ np.ones((3,2)) print(Z) ``` #### (25) 1次元の配列で、3 と 8 の間の値の要素をマイナスにする。 ``` Z = np.arange(11) Z[(3 < Z) & (Z < 8)] *= -1 print(Z) # 実験 [(-x if (x>3)&(x<8) else x) for x in range(11)] ``` #### (26) 次のプログラムを実行して考察する。 ```python # Author: Jake VanderPlas print(sum(range(5),-1)) #=> 9 from numpy import * print(sum(range(5),-1)) #=> 10 ``` ``` # 実験 print(sum(range(5),-1)) import numpy as np print(np.sum(range(5),-1)) arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) print(arr) print(np.sum(arr)) print(np.sum(arr, -1)) print(np.sum(arr, -2)) ``` #### (27) 整数のベクトル Z について、次の演算は文法的に可能かどうか。 ```python Z**Z #=> [1 4 27] 2 << Z >> 2 #=> [1 2 4] Z <- Z #=> [False False Fale] 1j*Z #=> [0.+1.j 0.+2.j 0.+3.j] Z/1/1 #=> [1. 2. 3.] Z<Z>Z #=> Error ``` ``` import numpy as np Z = np.array([1,2,3]) print(Z) print(Z**Z) print(2 << Z >> 2) print(Z <- Z) print(1j*Z) print(Z/1/1) # Z<Z>Z #=> Error # 実験 print(2 << 3) #=> 16 print(16 >> 2) #=> 4 print(3 < 3) #=> False print(3 <- 3) #=> False print(1/1) #=> 1.1 print(all(Z<(Z + 1))) #=> True ``` #### (28) 次の式を実行して考察する。 ```python np.array(0) / np.array(0) #=> Error np.array(0) // np.array(0) #=> Error np.array([np.nan]).astype(int).astype(float) #=> [-9.22337204e+18] ``` ``` # np.array(0) / np.array(0) #=> Error # np.array(0) // np.array(0) #=> Error print(np.array([np.nan]).astype(int).astype(float)) print(np.array([np.nan]).astype(int)) print(np.array([np.nan])) print(np.array([1,2,3]).astype(int).astype(float)) print(type(np.array([np.nan]))) ``` #### (29) float の配列を絶対値で切り上げる方法 (ゼロから遠くする) ``` # Author: Charles R Harris import numpy as np Z = np.random.uniform(-10,+10,10) print(np.copysign(np.ceil(np.abs(Z)), Z)) # More readable but less efficient print(np.where(Z>0, np.ceil(Z), np.floor(Z))) # 実験 print(np.array([np.ceil(x) if x > 0 else np.floor(x) for x in Z])) # 実験 print(Z) Z= np.random.random(10)*20-10 print(Z) ``` #### (30) 2つの入れるの共通の値をみつける。 How to find common values between two arrays? (★☆☆) ``` Z1 = np.random.randint(0,10,10) Z2 = np.random.randint(0,10,10) print(np.intersect1d(Z1,Z2)) # 実験 print(np.unique([1,2,3,2,3])) s1 = np.array([1,2,3,2,3,4]) s2 = np.array([2,3,4,5,6,7,]) print(np.union1d(s1,s2)) print(np.in1d([3,7], s1)) print(np.intersect1d(s1,s2)) print(np.setdiff1d(s2,s1)) print(np.setxor1d(s1,s2)) ``` #### (31) numpy の警告を無視する方法。 How to ignore all numpy warnings (not recommended)? (★☆☆) ``` # Suicide mode on defaults = np.seterr(all="ignore") Z = np.ones(1) / 0 # Back to sanity _ = np.seterr(**defaults) # Equivalently with a context manager with np.errstate(all="ignore"): np.arange(3) / 0 # 実験 print(np.ones((3,3))) print(np.arange((9)).reshape(3,3)) ``` #### (32) 次の式の真偽を試して考察する。 Is the following expressions true? (★☆☆) ```python np.sqrt(-1) == np.emath.sqrt(-1) #=> False なぜなら np.sqrt(-1) は 複素数を表さないが、np.emath.sqrt(-1) は複素数だから。 ``` ``` # 実験 print(np.emath.sqrt(-1) == 0+1j) print(np.emath.sqrt(-1) == 1j) print((1j)**2) print(np.sqrt(-1)) ``` #### (33) 昨日、今日、明日の日付を表示する。 ``` yesterday = np.datetime64('today') - np.timedelta64(1) today = np.datetime64('today') tomorrow = np.datetime64('today') + np.timedelta64(1) print(yesterday) print(today) print(tomorrow) ``` #### (34) 2016年7月の日付をすべて列挙する。 ``` Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]') print(Z) ``` #### (35) 行列演算 ((A+B)*(-A/2)) を in place で実行する。in place とはコピーを作らずに計算すること。 ``` A = np.ones(3)*1 B = np.ones(3)*2 C = np.ones(3)*3 print(np.add(A,B,out=B)) print(np.divide(A,2,out=A)) print(np.negative(A,out=A)) print(np.multiply(A,B,out=A)) # 実験 A = np.ones(3)*1 B = np.ones(3)*2 C = np.ones(3)*3 print((A+B)*(-A/2)) ``` #### (36) ランダムな正の数の配列から、整数部分をだけにする方法を4通り示す。 ``` Z = np.random.uniform(0,10,10) print(Z - Z%1) print(Z // 1) print(np.floor(Z)) print(Z.astype(int)) print(np.trunc(Z)) ``` #### (37) 5x5 でそれぞれの行が 0 1 2 3 4 である行列を作る。 ``` Z = np.zeros((5,5)) Z += np.arange(5) print(Z) # 実験 import numpy as np Z = np.zeros((5,5)) Z += range(5,10) print(Z) print(np.transpose(Z)) ``` #### (38) 10個の整数を作る generator 関数を作り、配列を作るのに使ってみる。 ``` def generate(): for x in range(10): yield x Z = np.fromiter(generate(),dtype=float,count=-1) print(Z) # 実験 def generate(): for x in range(20): yield x*x Z = np.fromiter(generate(),dtype=int,count=5) print(Z) ``` #### (39) 0 から 1 の値のサイズ 10 のベクトルを作る。0 と 1 は含まれないものとする。 ``` Z = np.linspace(0,1,11,endpoint=False)[1:] print(Z) # 実験 Z = np.linspace(0,1,11) print(Z) Z = np.linspace(0,1,11)[1:-1] print(Z) Z = np.linspace(0,1,12)[1:-1] print(Z) ``` #### (40) ランダムな値のサイズ 10 のベクトルを作り、ソートする。 ``` import numpy as np Z = np.random.random(10) Z.sort() print(Z) ``` #### (41) 小さな配列について、np.sum より速い方法。 ``` # Author: Evgeni Burovski Z = np.arange(10) np.add.reduce(Z) # 実験 import numpy as np from functools import reduce Z = np.arange(10) print(reduce(np.add, Z)) print(reduce(lambda a, b: a+b, Z)) ``` #### (42) A と B の2つの配列が同等 equal かどうかを判別する。 ``` import numpy as np A = np.random.randint(0,2,5) B = np.random.randint(0,2,5) # Assuming identical shape of the arrays and a tolerance for the comparison of values equal = np.allclose(A,B) print(equal) # Checking both the shape and the element values, no tolerance (values have to be exactly equal) equal = np.array_equal(A,B) print(equal) # 実験 C = np.array([0,0,0,1,1]) D = np.array([0,0,0,1,1.000000001]) equal = np.allclose(C, D) print(equal) equal = np.array_equal(C, D) print(equal) ``` #### (43) 配列をイミュータブル(変更不可)にする。 ``` Z = np.zeros(10) Z.flags.writeable = False # Z[0] = 1 #=> ValueError: assignment destination is read-only print(Z) ``` #### (44) デカルト座標を表す 10x2 の行列を極座標に変換する。 ``` Z = np.random.random((10,2)) print(Z) X,Y = Z[:,0], Z[:,1] R = np.sqrt(X**2+Y**2) T = np.arctan2(Y,X) print(R) print(T) # 実験 print(np.rad2deg(np.arctan2(1, 1))) print(np.rad2deg(np.arctan(1))) print(np.array(list (map (np.array, list(zip(R, T)))))) ``` #### (45) ランダムなサイズ 10 のベクトルを作り、最大値を 0 に置き換える。 ``` import numpy as np Z = np.random.random(10) Z[Z.argmax()] = 0 print(Z) # 実験 z = np.array([3, 2, 1, 1, 3]) print(z) print(z.argmax()) print(z.argmin()) y=[3, 2, 1, 1, 3] print(y) print(y.index(max(y))) y[y.index(max(y))] = 0 print(y) ``` #### (46) x 座標と y 座標を持つ構造化配列 structured array を作り、[0,1]x[0,1] の範囲をカバーする。 ``` import numpy as np Z = np.zeros((5,5), [('x',float),('y',float)]) Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), np.linspace(0,1,5)) print(Z) np.linspace(0,1,5) # 実験 dtype = [('x',float),('y',float)] Y = np.zeros((5,5), dtype=dtype) Y['x'] = np.linspace(0,1,5) np.transpose(Y)['y'] = np.linspace(0,1,5) print(Y) ``` #### (47) 行列 X と Y からコーシー Cauchy 行列 C (Cij =1/(xi - yj)) を作る。 ``` # Author: Evgeni Burovski import numpy as np X = np.arange(8) Y = X + 0.5 C = 1.0 / np.subtract.outer(X, Y) print(np.linalg.det(C)) # 実験 X = np.arange(3) Y = X + 0.5 print(X) print(Y) C = 1.0 / np.subtract.outer(X, Y) print(C.size) print(C) print(np.linalg.det(C)) ``` #### (48) numpy のすべてのスカラー型について、最大値、最小値を表示する。 ``` for dtype in [np.int8, np.int32, np.int64]: print(np.iinfo(dtype).min) print(np.iinfo(dtype).max) for dtype in [np.float32, np.float64]: print(np.finfo(dtype).min) print(np.finfo(dtype).max) print(np.finfo(dtype).eps) # machine epsilon? # 実験 print(np.iinfo(np.int8)) print(np.finfo(np.float32)) ``` #### (49) 配列のすべての値を表示する。 ``` import numpy as np np.set_printoptions(threshold=float("inf")) Z = np.zeros((16,16)) print(Z) # 実験 import numpy as np np.set_printoptions(threshold=float("10")) Z = np.zeros((16,16)) print(Z) ``` #### (50) 与えられた値に一番近い値をベクトルの中で探して表示する。 How to find the closest value (to a given scalar) in a vector? (★★☆) ``` Z = np.arange(100) v = np.random.uniform(0,100) index = (np.abs(Z-v)).argmin() print(Z[index]) # 実験 print(Z) print(v) print(index) ``` #### (51) 構造化配列で、場所 position (x,y) と色 color (r,g,b) を表現する。 ``` Z = np.zeros(10, [ ('position', [ ('x', float), ('y', float)]), ('color', [ ('r', float), ('g', float), ('b', float)])]) print(Z) ``` #### (52) 座標を表すランダムな (10,2) の形のベクトルを考え、点と点の間の距離を計算する。 ``` Z = np.random.random((10,2)) X,Y = np.atleast_2d(Z[:,0], Z[:,1]) D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) print(D) # Much faster with scipy import scipy # Thanks Gavin Heverly-Coulson (#issue 1) import scipy.spatial # Z = np.random.random((10,2)) D = scipy.spatial.distance.cdist(Z,Z) print(D) # 実験 # Z = np.random.random((10,2)) X,Y = np.atleast_2d(Z[:,0], Z[:,1]) X = np.array([Z[:,0]]) Y = np.array([Z[:,1]]) D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) print(D) ``` #### (53) 32 ビット float を 32 ビット integer に in place で変換する。 ``` # Thanks Vikas (https://stackoverflow.com/a/10622758/5989906) # & unutbu (https://stackoverflow.com/a/4396247/5989906) Z = (np.random.rand(10)*100).astype(np.float32) Y = Z.view(np.int32) Y[:] = Z print(Y) # 実験 Z=(np.random.rand(10)*100).astype(np.float32) print(Z) # Y=Z.view(np.int32) Y=np.zeros(10).astype(np.int32) print(Y) Y[:] = Z print(Y) ``` #### (54) 次のようなファイルをどう読み込むか。 ``` 1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11 ``` ``` from io import StringIO # Fake file s = StringIO('''1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11 ''') Z = np.genfromtxt(s, delimiter=",", dtype=np.int) print(Z) # 実験 import numpy as np import re def read_data(data): lines = [] for line in data.split('\n'): items = [] for item in re.split(',| ,\s',line): if item == '' or item == ' ': item = -1 items.append(item) line=items lines.append(line) return lines data = '''1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11''' print(read_data(data)) ``` #### (55) numpy の配列で python の enumerate に相当するものは何か。 ``` Z = np.arange(9).reshape(3,3) for index, value in np.ndenumerate(Z): print(index, value) for index in np.ndindex(Z.shape): print(index, Z[index]) # 実験 print(Z) print(list((np.ndenumerate(Z)))) print(np.array(list((np.ndenumerate(Z)))).reshape(3,3,2)) ``` #### (56) 一般的な2Dガウス配列を作る。 ``` import numpy as np X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) D = np.sqrt(X*X+Y*Y) sigma, mu = 1.0, 0.0 G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) print(G) ``` 上の解答の意味がわからない。 問題のガウス配列 Gaussian array というのは正規分布のことで、2D というので普通の正規分布のグラフのことを言っているのかと思うのだが、解答 meshgrid を使っているので 3D グラフを描こうとしているのではないか。 ガウス関数は $$ f(x) = \frac{1}{\sqrt{2\pi\sigma}}\mathrm{exp} \left(- \frac{(x - \mu)^2}{2 \sigma^2}\right)\quad (x \in \mathbb{R}) $$ 特に $\mu=0,\, \sigma^2 = 1$ のとき標準正規分布と呼び、 $$ f(x) = \frac{1}{\sqrt{2\pi\sigma}}\mathrm{exp} \left(- \frac{x^2}{2}\right)\quad (x \in \mathbb{R}) $$ とのこと。 この通りに作ればいいだけだよね。 ``` # 実験 import numpy as np X, Y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) D = np.sqrt(X*X+Y*Y) sigma, mu = 1.0, 0.0 G = np.exp(- 10 * ( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) # print(G) import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X,Y,G, cmap=cm.jet) plt.show() # 実験 import matplotlib.pyplot as plt import numpy as np import math def f(x): return (math.exp(-x**2/2)) / math.sqrt(2*math.pi) n = np.linspace(-5.0, 5.0, 50) p = [] for i in range(len(n)): p.append(f(n[i])) # グラフに表示 plt.plot(n, p) plt.show() ``` #### (57) 2次元の配列で、p 個の要素をランダムに置く。 ``` # Author: Divakar n = 10 p = 3 Z = np.zeros((n,n)) np.put(Z, np.random.choice(range(n*n), p, replace=False),1) print(Z) # 実験 n = 5 p = 5 Z = np.full((n,n),'□') # np.put(Z, np.random.choice(range(n*n), p, replace=False),1) np.put(Z, np.random.choice(25, p, replace=False),'■') print(Z) np.put(Z, np.random.choice(25, p, replace=False),'■') print(Z) np.put(Z, np.random.choice(25, p, replace=False),'■') np.put(Z, np.random.choice(25, p, replace=False),'■') np.put(Z, np.random.choice(25, p, replace=False),'■') print(Z) ``` #### (58) 行列の各行の平均を引く。 ``` # Author: Warren Weckesser X = np.random.rand(5, 10) # Recent versions of numpy Y = X - X.mean(axis=1, keepdims=True) # Older versions of numpy # Y = X - X.mean(axis=1).reshape(-1, 1) print(Y) # 実験 print(X[0] - np.array([np.mean(row) for row in X])[0]) Y = X - X.mean(axis=1, keepdims=True) print(Y[0]) print([[X[n] - np.array([np.mean(row) for row in X])[n]] for n in range(5)]) ``` #### (59) n 番目の列で配列をソートする。 ``` # Author: Steve Tjoa Z = np.random.randint(0,10,(3,3)) print(Z) print(Z[Z[:,1].argsort()]) # 実験 print(Z) a=Z[:,2].argsort() print(a) print(Z[a]) ``` #### (60) 2次元配列について、null 列があるかどうかを判定する。 ``` # Author: Warren Weckesser Z = np.random.randint(0,3,(3,10)) print((~Z.any(axis=0)).any()) # 実験 Z=np.array([0,0,1,0]).reshape(2,2) print(Z) print(Z.any(axis=0)) print(~Z.any(axis=0)) print(~np.array([True, False])) print(np.array(list(map (lambda x: not(x), Z.any(axis=0))))) print(~np.array(list(map (lambda x: not(x), Z.any(axis=0))))) print(np.array(list(map (lambda x: not(x), Z.any(axis=0)))).any()) ``` #### (61) 与えられた値に最も近い値を配列の中からみつける。 Find the nearest value from a given value in an array (★★☆) ``` Z = np.random.uniform(0,1,10) z = 0.5 m = Z.flat[np.abs(Z - z).argmin()] print(m) # 実験 Z = np.random.uniform(0,1,9).reshape(3,3) z = 0.5 m = Z.flat[np.abs(Z - z).argmin()] print(Z) print(np.abs(Z - z).argmin()) print(m) ``` #### (62) 配列のシェープが (1,3) のものと (3,1) のものがあるとして、iterator を使って合計を計算する。 ``` import numpy as np A = np.arange(3).reshape(3,1) B = np.arange(3).reshape(1,3) it = np.nditer([A,B,None]) for x,y,z in it: z[...] = x + y print(it.operands[2]) # 実験 a = [0,1,2] b = [0,1,2] np.array([x+y for x in a for y in b]).reshape(3,3) ``` #### (63) name 属性を持つ配列クラスを作る。 Create an array class that has a name attribute (★★☆) ``` import numpy as np class NamedArray(np.ndarray): def __new__(cls, array, name="no name"): obj = np.asarray(array).view(cls) obj.__class__.name = name return obj def __array_finalize__(self, obj): if obj is None: return self.info = getattr(obj, 'name', "noo name") Z = NamedArray(np.arange(10), "range_10") print(Z.__class__.name) print (Z.name) # 実験 Z = NamedArray(np.arange(10)) Z.name = "range_10" print(Z.__class__.name) print(Z.name) Z = NamedArray(None) Z.name = "range_10" print(Z.__class__.name) print(Z.name) Z = NamedArray("yes", name="no") Z.name = "range_10" print(Z.__class__.name) print(Z.name) type (Z) ``` 通常クラスのインスタンスは何もしないでも、name 属性がある。 ``` # 実験 class MyClass: pass m = MyClass() m.name = "myname" print(m.name) ``` 設問の意味はクラスに name 属性をつけたい、ということか。 でも、解答例の print(Z.name) は、インスタンスの name を調べているだけで、クラスの name を調べているわけではない。 プログラムは、`__init__()` ではなく、`__new__()` で初期化することにより、self ではなく cls に属性をつける風に読める。 ``` python help(np.ndarray.view) #=> New view of array with the same data. ``` なので、view() はなにもしていない。 ``` __array_finalize__(self, obj): if obj is None: return self.info = getattr(obj, 'name', "noo name") ``` は何をしているのか? ``` %%script false help(getattr) ``` #### (64) 与えられたベクトルについて、インデクスのベクトルで指定された要素に 1 を加える。 Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) ``` import numpy as np # Author: Brett Olsen Z = np.ones(10) I = np.random.randint(0,len(Z),20) Z += np.bincount(I, minlength=len(Z)) print(Z) # Another solution # Author: Bartosz Telenczuk np.add.at(Z, I, 1) print(Z) # 実験 Z = np.ones(10) print(Z) I = np.random.randint(0,len(Z),3) print(I) Z += np.bincount(I, minlength=len(Z)) print(np.bincount(I)) print(Z) print() print(Z) print(I) np.add.at(Z, I, 1) print(Z) ``` #### (65) インデクスリスト (I) に基づいて、ベクトル (X) の要素を足しこんで、配列 (F) を作る。 ``` # Author: Alan G Isaac X = [1,2,3,4,5,6] I = [1,3,9,3,4,1] F = np.bincount(I,X) print(F) # 実験 X = [1,2,3,4,5,6] I = [1,3,9,3,4,1] print(np.bincount(I)) F = np.bincount(I,X) print(F) ``` #### (66) (w, h, 3) の配列の形で表される色配列がある。 ユニークな色の数を求める。 (dtype=ubyte) とする Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★) ``` # Author: Nadav Horesh import numpy as np w,h = 16,16 I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte) F = I[...,0]*256*256 + I[...,1]*256 +I[...,2] n = len(np.unique(F)) print(np.unique(I)) ``` この模範解答では、実行結果が [0 1] となってしまうので、解答になっていないと思う。 模範解答では w と h を 16 と置いているので、$16 \times 16 \times 3 = 768$ の場所に、多分仮に、だろうが 0 と 1 を置いている。 ということは、2価なので、例えば赤 1,緑 1, 青 0 とすると、多分黄色になる。 順列組み合わせで 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 で最大 8 種類、もしくはそれ以下の結果になれば正解だと思う。 まず、 `F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]` が機能していない。 やりたいことは、$16 \times 16 \times 3$ の配列について、0 行目に 256 × 256、1 行目に 256 を掛けて、3 行を足すことによって、色の表現を配列から単なるフラットな数字に変換しようとしているのだろう。 しかし、ubyte、である数字に大きな数を掛けて ubyte の範囲を超えると現在の仕様では 0 になってしまう。 その証拠に print(n) とすると、 [0 0], [0 1], [1 0], [0 0] の4つが取り出されている。 ``` print(n) ``` ので、この方法は使えない。 とりあえず 256 を 10 にすると 大丈夫そう。 ``` # 実験 I[...,0]*3 # 実験 I[...,0]*256*256 # 実験 I[...,0]*10*10 # 実験 import numpy as np w,h = 16,16 I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte) F = I[...,0]*10*10 + I[...,1]*10 +I[...,2] n = len(np.unique(F)) print(np.unique(I)) print(n) ``` 上記の結果で print(n) の値が 8 になるのは 8 が最大値で試験回数が多いからなので、仮に w,h = 4.4 として実行すると8も出るし、6とか7も出る。 `print(np.unique(F)) ` の値が [0 1] になってしまうのは、np.unique の仕様が、配列をフラットにして unique をとる。 ``` # 実験 import numpy as np print (np.unique(np.array([1,2,3,2,1]))) print(np.unique(np.array([[1,2],[1,2],[2,3]]))) print(np.unique(np.array([[1,2],[1,2],[2,3]]), axis=0)) ``` 下記の例では、一旦 reshape して、axis を指定して unique をとった。 ``` # 実験 import numpy as np w,h = 4,4 I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte) F = I[...,0]*10*10 + I[...,1]*10 +I[...,2] n = len(np.unique(F)) print(n) print(np.unique(F)) np.unique(np.reshape(I, (w*h, 3)), axis=0) ``` #### (67) 4次元の配列を考え、最後の 2 軸の合計をとる。 Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) ``` import numpy as np A = np.random.randint(0,10,(3,4,3,4)) # solution by passing a tuple of axes (introduced in numpy 1.7.0) sum = A.sum(axis=(-2,-1)) print(sum) # solution by flattening the last two dimensions into one # (useful for functions that don't accept tuples for axis argument) sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) print(sum) ``` 4次元で数字が多いとイメージできないので、少なくして実験してみる。 ``` # 実験 # 3次元にして、それぞれの要素を2にしてみる。 A = np.random.randint(0,10,(2,2,2)) print(A) print() sum = A.sum(axis=(-2,-1)) # これが正解 print(sum) # axis を指定しないとフラットな合計になってしまい、今回の目的に合わない print(A.sum()) print(A.sum(axis=(0,1))) # 頭から足して行くとこうなる print(np.sum([[1,2],[3,4]], axis=(0))) print(np.sum([[1,2],[3,4]], axis=(-1))) print() sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) print(sum) ``` `sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)` の reshape と shape がわからないので以下に実験してみる。 ``` # 実験 import numpy as np A = np.random.randint(0,10,(3,4,5,6,7,8)) print(A.shape[:-2]+(-1,)) print(type(A.shape[:-2])) print((1,)+(2,)+(3,)) print() A = np.random.randint(0,10,(3,4,5)) print(A.reshape((6,10))) print() A.reshape(3,-1) # 実験 A = np.random.randint(0,10,(2,2,2)) print(A) print() A=A.reshape(A.shape[:-2] + (-1,)) print(A) sum = A.sum(axis=-1) print(sum) ``` # いまここ #### (68) 1次元のベクトルDを考え、インデックスのベクトルSを使用して、Dのサブセットの平均を計算する。 Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★) ``` # Author: Jaime Fernández del Río import numpy as np D = np.random.uniform(0,1,100) S = np.random.randint(0,10,100) D_sums = np.bincount(S, weights=D) D_counts = np.bincount(S) D_means = D_sums / D_counts print(D_means) # Pandas solution as a reference due to more intuitive code import pandas as pd print(pd.Series(D).groupby(S).mean()) np.random.uniform(-10,10,10) ``` #### (69) How to get the diagonal of a dot product? (★★★) ``` # Author: Mathieu Blondel A = np.random.uniform(0,1,(5,5)) B = np.random.uniform(0,1,(5,5)) # Slow version np.diag(np.dot(A, B)) # Fast version np.sum(A * B.T, axis=1) # Faster version np.einsum("ij,ji->i", A, B) ``` #### (70) Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) ``` # Author: Warren Weckesser Z = np.array([1,2,3,4,5]) nz = 3 Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) Z0[::nz+1] = Z print(Z0) ``` #### (71) Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★) ``` A = np.ones((5,5,3)) B = 2*np.ones((5,5)) print(A * B[:,:,None]) ``` #### (72) How to swap two rows of an array? (★★★) ``` # Author: Eelco Hoogendoorn A = np.arange(25).reshape(5,5) A[[0,1]] = A[[1,0]] print(A) ``` #### (73) Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) ``` # Author: Nicolas P. Rougier faces = np.random.randint(0,100,(10,3)) F = np.roll(faces.repeat(2,axis=1),-1,axis=1) F = F.reshape(len(F)*3,2) F = np.sort(F,axis=1) G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) G = np.unique(G) print(G) ``` #### (74) Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) ``` # Author: Jaime Fernández del Río C = np.bincount([1,1,2,3,4,4,6]) A = np.repeat(np.arange(len(C)), C) print(A) ``` #### (75) How to compute averages using a sliding window over an array? (★★★) ``` # Author: Jaime Fernández del Río def moving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n Z = np.arange(20) print(moving_average(Z, n=3)) ``` #### (76) Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★) ``` # Author: Joe Kington / Erik Rigtorp from numpy.lib import stride_tricks def rolling(a, window): shape = (a.size - window + 1, window) strides = (a.itemsize, a.itemsize) return stride_tricks.as_strided(a, shape=shape, strides=strides) Z = rolling(np.arange(10), 3) print(Z) ``` #### (77) How to negate a boolean, or to change the sign of a float inplace? (★★★) ``` # Author: Nathaniel J. Smith Z = np.random.randint(0,2,100) np.logical_not(Z, out=Z) Z = np.random.uniform(-1.0,1.0,100) np.negative(Z, out=Z) ``` #### (78) Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★) ``` def distance(P0, P1, p): T = P1 - P0 L = (T**2).sum(axis=1) U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L U = U.reshape(len(U),1) D = P0 + U*T - p return np.sqrt((D**2).sum(axis=1)) P0 = np.random.uniform(-10,10,(10,2)) P1 = np.random.uniform(-10,10,(10,2)) p = np.random.uniform(-10,10,( 1,2)) print(distance(P0, P1, p)) ``` #### (79) Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★) ``` # Author: Italmassov Kuanysh # based on distance function from previous question P0 = np.random.uniform(-10, 10, (10,2)) P1 = np.random.uniform(-10,10,(10,2)) p = np.random.uniform(-10, 10, (10,2)) print(np.array([distance(P0,P1,p_i) for p_i in p])) ``` #### (80) Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★) ``` # Author: Nicolas Rougier Z = np.random.randint(0,10,(10,10)) shape = (5,5) fill = 0 position = (1,1) R = np.ones(shape, dtype=Z.dtype)*fill P = np.array(list(position)).astype(int) Rs = np.array(list(R.shape)).astype(int) Zs = np.array(list(Z.shape)).astype(int) R_start = np.zeros((len(shape),)).astype(int) R_stop = np.array(list(shape)).astype(int) Z_start = (P-Rs//2) Z_stop = (P+Rs//2)+Rs%2 R_start = (R_start - np.minimum(Z_start,0)).tolist() Z_start = (np.maximum(Z_start,0)).tolist() R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist() Z_stop = (np.minimum(Z_stop,Zs)).tolist() r = [slice(start,stop) for start,stop in zip(R_start,R_stop)] z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)] R[r] = Z[z] print(Z) print(R) ``` #### (81) Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★) ``` # Author: Stefan van der Walt Z = np.arange(1,15,dtype=np.uint32) R = stride_tricks.as_strided(Z,(11,4),(4,4)) print(R) ``` #### (82) Compute a matrix rank (★★★) ``` # Author: Stefan van der Walt Z = np.random.uniform(0,1,(10,10)) U, S, V = np.linalg.svd(Z) # Singular Value Decomposition rank = np.sum(S > 1e-10) print(rank) ``` #### (83) How to find the most frequent value in an array? ``` Z = np.random.randint(0,10,50) print(np.bincount(Z).argmax()) ``` #### (84) Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) ``` # Author: Chris Barker Z = np.random.randint(0,5,(10,10)) n = 3 i = 1 + (Z.shape[0]-3) j = 1 + (Z.shape[1]-3) C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) print(C) ``` #### (85) Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) ``` # Author: Eric O. Lebigot # Note: only works for 2d array and value setting using indices class Symetric(np.ndarray): def __setitem__(self, index, value): i,j = index super(Symetric, self).__setitem__((i,j), value) super(Symetric, self).__setitem__((j,i), value) def symetric(Z): return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric) S = symetric(np.random.randint(0,10,(5,5))) S[2,3] = 42 print(S) ``` #### (86) Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★) ``` # Author: Stefan van der Walt p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # It works, because: # M is (p,n,n) # V is (p,n,1) # Thus, summing over the paired axes 0 and 0 (of M ``` #### (87) Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) ``` # Author: Robert Kern Z = np.ones((16,16)) k = 4 S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), np.arange(0, Z.shape[1], k), axis=1) print(S) ``` #### (88) How to implement the Game of Life using numpy arrays? (★★★) ``` # Author: Nicolas Rougier def iterate(Z): # Count neighbours N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + Z[1:-1,0:-2] + Z[1:-1,2:] + Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) # Apply rules birth = (N==3) & (Z[1:-1,1:-1]==0) survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) Z[...] = 0 Z[1:-1,1:-1][birth | survive] = 1 return Z Z = np.random.randint(0,2,(50,50)) for i in range(100): Z = iterate(Z) print(Z) ``` #### (89) How to get the n largest values of an array (★★★) ``` Z = np.arange(10000) np.random.shuffle(Z) n = 5 # Slow print (Z[np.argsort(Z)[-n:]]) # Fast print (Z[np.argpartition(-Z,n)[:n]]) ``` #### (90) Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★) ``` # Author: Stefan Van der Walt def cartesian(arrays): arrays = [np.asarray(a) for a in arrays] shape = (len(x) for x in arrays) ix = np.indices(shape, dtype=int) ix = ix.reshape(len(arrays), -1).T for n, arr in enumerate(arrays): ix[:, n] = arrays[n][ix[:, n]] return ix print (cartesian(([1, 2, 3], [4, 5], [6, 7]))) ``` #### (91) How to create a record array from a regular array? (★★★) ``` Z = np.array([("Hello", 2.5, 3), ("World", 3.6, 2)]) R = np.core.records.fromarrays(Z.T, names='col1, col2, col3', formats = 'S8, f8, i8') print(R) ``` #### (92) Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) ``` # Author: Ryan G. x = np.random.rand(int(5e7)) %timeit np.power(x,3) %timeit x*x*x %timeit np.einsum('i,i,i->i',x,x,x) ``` #### (93) Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★) ``` # Author: Gabe Schwartz A = np.random.randint(0,5,(8,3)) B = np.random.randint(0,5,(2,2)) C = (A[..., np.newaxis, np.newaxis] == B) rows = np.where(C.any((3,1)).all(1))[0] print(rows) ``` #### (94) Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) ``` # Author: Robert Kern Z = np.random.randint(0,5,(10,3)) print(Z) # solution for arrays of all dtypes (including string arrays and record arrays) E = np.all(Z[:,1:] == Z[:,:-1], axis=1) U = Z[~E] print(U) # soluiton for numerical arrays only, will work for any number of columns in Z U = Z[Z.max(axis=1) != Z.min(axis=1),:] print(U) ``` #### (95) Convert a vector of ints into a matrix binary representation (★★★) ``` # Author: Warren Weckesser I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) print(B[:,::-1]) # Author: Daniel T. McDonald I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8) print(np.unpackbits(I[:, np.newaxis], axis=1)) ``` #### (96) Given a two dimensional array, how to extract unique rows? (★★★) ``` # Author: Jaime Fernández del Río Z = np.random.randint(0,2,(6,3)) T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1]))) _, idx = np.unique(T, return_index=True) uZ = Z[idx] print(uZ) # Author: Andreas Kouzelis # NumPy >= 1.13 uZ = np.unique(Z, axis=0) print(uZ) ``` #### (97) Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) ``` # Author: Alex Riley # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/ A = np.random.uniform(0,1,10) B = np.random.uniform(0,1,10) np.einsum('i->', A) # np.sum(A) np.einsum('i,i->i', A, B) # A * B np.einsum('i,i', A, B) # np.inner(A, B) np.einsum('i,j->ij', A, B) # np.outer(A, B) ``` #### (98) Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? ``` # Author: Bas Swinckels phi = np.arange(0, 10*np.pi, 0.1) a = 1 x = a*phi*np.cos(phi) y = a*phi*np.sin(phi) dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths r = np.zeros_like(x) r[1:] = np.cumsum(dr) # integrate path r_int = np.linspace(0, r.max(), 200) # regular spaced path x_int = np.interp(r_int, r, x) # integrate path y_int = np.interp(r_int, r, y) ``` #### (99) Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★) ``` # Author: Evgeni Burovski X = np.asarray([[1.0, 0.0, 3.0, 8.0], [2.0, 0.0, 1.0, 1.0], [1.5, 2.5, 1.0, 0.0]]) n = 4 M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1) M &= (X.sum(axis=-1) == n) print(X[M]) ``` #### (100) Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★) ``` # Author: Jessica B. Hamrick X = np.random.randn(100) # random 1D array N = 1000 # number of bootstrap samples idx = np.random.randint(0, X.size, (N, X.size)) means = X[idx].mean(axis=1) confint = np.percentile(means, [2.5, 97.5]) print(confint) ``` https://github.com/rougier/numpy-100
github_jupyter
# make regional weights files ``` import rhg_compute_tools.kubernetes as rhgk import dask.distributed as dd import dask.dataframe as ddf import geopandas as gpd import pandas as pd import xarray as xr import numpy as np import cartopy.crs as ccrs import cartopy.feature as cfeature %matplotlib inline import os CRS_SUPPORT_BUCKET = os.environ['CRS_SUPPORT_BUCKET'] admin1 = gpd.read_file('https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_states_provinces.zip') admin0 = gpd.read_file('https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_countries.zip') admin1.plot() admin0.plot() from distutils.version import LooseVersion def get_containing_region(df, shapes, feature, x_col='x', y_col='y', crs='epsg:4326', predicate='intersects'): """ Return a feature corresponding to the first polygon to contain each (x, y) point in a dataframe Parameters ---------- df : pd.DataFrame Dataframe with x/y data to assign to geometries shapes : gpd.GeoDataFrame geopandas dataframe with polygon geometries feature : str column name in ``shapes`` to return for each matched feature x_col : str, optional column name in ``df`` to use for x coordinate of points (default 'x') y_col : str, optional column name in ``df`` to use for y coordinate of points (default 'y') crs : str, optional Coordinate reference system code for the projection of the (x, y) points in ``df``. Must be interpretable by ``pyproj``. Default ``'epsg:4326'`` (WGS 84). predicate : str, optional name of the binary predicate to use on the join. Must be a shapely binary predicate. See the geopandas docs on `sjoin <https://geopandas.org/en/stable/docs/reference/api/geopandas.sjoin.html>`_. Default (``'intersects'``) means the first polygon in ``shapes`` to intersect the point (either contain or touch with boundary) will be returned. """ points = gpd.GeoDataFrame( geometry=gpd.points_from_xy(df[x_col], df[y_col], crs=crs), index=df.index, ) if LooseVersion(gpd.__version__) >= LooseVersion('0.10.0'): pred = {'predicate': predicate} else: pred = {'op': predicate} return gpd.sjoin(points, shapes[[feature, 'geometry']], how='left', **pred)[feature] client, cluster = rhgk.get_cluster() cluster.scale(20) cluster gpwv4_unwpp_2020 = ddf.read_parquet( f'gs://{CRS_SUPPORT_BUCKET}/public_datasets/spatial/exposure/GLOBAL/population/' 'gpw-v4-population-count-adjusted-to-2015-unwpp-country-totals-rev11_2020_30_sec_tif/' 'derived_datasets/reformatted/' 'gpw-v4-population-count-adjusted-to-2015-unwpp-country-totals-rev11_2020_30_sec.parquet', chunksize='100MB', ) POP_RASTER_WITH_REGION_ASSIGNMENTS = ( 'gs://downscaled-288ec5ac/diagnostics/rasters/' 'gpw-v4-population-count-adjusted-to-2015-unwpp-country-totals-rev11_2020_30_sec/' 'naturalearth_v5.0.0_adm0_and_adm1_assignments.parquet' ) gpwv4_unwpp_2020 assignments_adm0 = gpwv4_unwpp_2020.map_partitions( get_containing_region, shapes=admin0[['ADM0_A3', 'geometry']], feature='ADM0_A3', meta='str', ) assignments_adm0 = assignments_adm0.persist() dd.progress(assignments_adm0, notebook=False) dd.wait(assignments_adm0) assert not any([f.status == 'error' for f in assignments_adm0.dask.values()]), assignments_adm0.compute() gpwv4_unwpp_2020['ADM0_A3'] = assignments_adm0 assignments_adm1 = gpwv4_unwpp_2020.map_partitions( get_containing_region, shapes=admin1[['adm1_code', 'geometry']], feature='adm1_code', meta='str', ) assignments_adm1 = assignments_adm1.persist() dd.progress(assignments_adm1, notebook=False) dd.wait(assignments_adm1) assert not any([f.status == 'error' for f in assignments_adm1.dask.values()]), assignments_adm1.compute() gpwv4_unwpp_2020['adm1_code'] = assignments_adm1 gpwv4_unwpp_2020 = gpwv4_unwpp_2020.dropna(how='all').compute() gpwv4_unwpp_2020.repartition(npartitions=20).to_parquet(POP_RASTER_WITH_REGION_ASSIGNMENTS) client.restart() cluster.scale(0) client.close() cluster.close() ```
github_jupyter
<a href="https://colab.research.google.com/github/wesleybeckner/technology_fundamentals/blob/main/C2%20Statistics%20and%20Model%20Creation/Tech_Fun_C2_S1_Regression_and_Descriptive_Statistics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Technology Fundamentals Course 2, Session 1: Regression and Descriptive Statistics **Instructor**: Wesley Beckner **Contact**: wesleybeckner@gmail.com **Teaching Assitants**: Varsha Bang, Harsha Vardhan **Contact**: vbang@uw.edu, harshav@uw.edu <br> ## Schedule for this week <p align="center"> <img src="https://raw.githubusercontent.com/wesleybeckner/technology_fundamentals/main/assets/week2.png" width=800></img> </p> --- <br> In this session we will look at fitting data to a curve using **regression**. We will also look at using regression to make **predictions** for new data points by dividing our data into a training and a testing set. Finally we will examine how much error we make in our fit and then in our predictions by computing the mean squared error. <br> --- <a name='x.0'></a> ## 1.0 Preparing Environment and Importing Data [back to top](#top) <a name='x.0.1'></a> ### 1.0.1 Import Packages [back to top](#top) ``` # Import pandas, pyplot, ipywidgets import pandas as pd from matplotlib import pyplot as plt from ipywidgets import interact # Import Scikit-Learn library for the regression models import sklearn from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score # for enrichment topics import seaborn as sns import numpy as np ``` ### 1.0.2 Load Dataset [back to top](#top) For our discussion on regression and descriptive statistics today we will use a well known dataset of different wines and their quality ratings ``` df = pd.read_csv("https://raw.githubusercontent.com/wesleybeckner/"\ "ds_for_engineers/main/data/wine_quality/winequalityN.csv") df.shape df.describe() ``` ## 1.1 What is regression? It is the process of finding a relationship between **_dependent_** and **_independent_** variables to find trends in data. This abstract definition means that you have one variable (the dependent variable) which depends on one or more variables (the independent variables). One of the reasons for which we want to regress data is to understand whether there is a trend between two variables. **Housing Prices Example** We can imagine this scenario with housing prices. Envision a **_mixed_** dataset of **_continuous_** and **_discrete_** independent variables. Some features could be continuous, floating point values like location ranking and housing condition. Others could be descrete like the number of rooms or bathrooms. We could take these features and use them to predict a house value. This would be a **_regression_** model. <p align=center> <img src="https://raw.githubusercontent.com/wesleybeckner/technology_explorers/main/assets/machine_learning/ML3.png" width=1000px></img> ## 1.2 Linear regression fitting with scikit-learn #### Exercise 1: rudimentary EDA What does the data look like? Remember how to visualize data in a pandas dataframe (Sessions 3 and 4) <ol> <li> for every column calculate the * skew: `df.skew()` * kurtosis: `df.kurtosis()` * pearsons correlation with the dependent variable: `df.corr()` * number of missing entries `df.isnull()` and organize this into a new dataframe _note:_ pearsons is just one type of correlation, another available to us **_spearman_** which differs from pearsons in that it depends on ranked values rather than their direct quantities, you can read more [here](https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/) ``` df.isnull().sum() # Cell for Exercise 1 # part A # using df.<method> define the following four variables with the results from # skew(), kurtosis(), corr() (and selecting for quality), and isnull() # for isnull() you'll notice the return is a dataframe of booleans. we would # like to simply know the number of null values for each column. change the # return of isnull() using the sum() method # skew = # kurt = # pear = # null = # part B # on line 13, put these results in a list using square brackets and call # pandas.DataFrame on the list to make your new DataFrame! store it under the # variable name dff # part C # take the transpose of this DataFrame using dff.T. reassign dff to this copy # part D # set the column names to 'skew', 'kurtosis', 'pearsons _quality', and # 'null count' using dff.columns # Now return dff to the output to view your hand work # dff ``` I have gone ahead and repeated this exercise with the red vs white wine types: ``` red = df.loc[df['type'] == 'red'] wht = df.loc[df['type'] == 'white'] def get_summary(df): skew = df.skew() kurt = df.kurtosis() pear = df.corr()['quality'] null = df.isnull().sum() med = df.median() men = df.mean() dff = pd.DataFrame([skew, kurt, pear, null, med, men]) dff = dff.T dff.columns = ['skew', 'kurtosis', 'pearsons _quality', 'null count', 'median', 'mean'] return dff dffr = get_summary(red) dffw = get_summary(wht) desc = pd.concat([dffr, dffw], keys=['red', 'white']) desc def my_fig(metric=desc.columns): fig, ax = plt.subplots(1, 1, figsize=(10,10)) pd.DataFrame(desc[metric]).unstack()[metric].T.plot(kind='barh', ax=ax) interact(my_fig) ``` #### Question 1: Discussion Around EDA Plot What do we think of this plot? > `metric = mean`, the cholrides values <br> `metric = kurtosis`, residual sugar <br> `metric = pearsons _quality`, _magnitudes_ and _directions_ <br> How to improve the plot, what other plots would we like to see? ``` df['chlorides'].describe() fig, ax = plt.subplots(1,1,figsize=(10,10)) df['chlorides'].plot(kind='kde',ax=ax) ax.set_xlim(0,.61) df['chlorides'].sort_values(ascending=False)[:50] ``` ### 1.2.2 Visualizing the data set - motivating regression analysis We can create a scatter plot of fixed acidity vs density of red wine in the dataset using `df.plot()` and see that there appears to be a general trend between the two features: ``` fig, ax = plt.subplots(1, 1, figsize=(5,5)) df.loc[df['type'] == 'red'].plot(x='fixed acidity', y='density', ax=ax, ls='', marker='.') ``` ### 1.2.3 Estimating the regression coefficients It looks like density increases with fixed acidity following a line, maybe something like $$y(x)= m \cdot x + b \;\;\;\;\;\;\;\;\sf{eq. 1}$$ with $y=\sf density$, $x=\sf fixed acidity$, and $m$ the slope and $b$ the intercept. To solve the problem, we need to find the values of $b$ and $m$ in equation 1 to best fit the data. This is called **linear regression**. In linear regression our goal is to minimize the error between computed values of positions $y^{\sf calc}(x_i)\equiv y^{\sf calc}_i$ and known values $y^{\sf exact}(x_i)\equiv y^{\sf exact}_i$, i.e. find $b$ and $m$ which lead to lowest value of $$\epsilon (m,b) =SS_{\sf res}=\sum_{i=1}^{N}\left(y^{\sf exact}_i - y^{\sf calc}_i\right)^2 = \sum_{i=1}^{N}\left(y^{\sf exact}_i - m\cdot x_i - b \right)^2\;\;\;\;\;\;\;\;\;\;\;\sf{eq. 2}$$ To find out more see e.g. https://en.wikipedia.org/wiki/Simple_linear_regression #### Question 2: linear regression loss function > Do we always want *m* and *b* to be large positive numbers so as to minimize eq. 2? Luckily [scikit-learn](https://scikit-learn.org/stable/) contains many functions related to regression including [linear regression](https://scikit-learn.org/stable/modules/linear_model.html). The function we will use is called <code> LinearRegression() </code>. ``` # Create linear regression object model = linear_model.LinearRegression() # Use model to fit to the data, the x values are densities and the y values are fixed acidity # Note that we need to reshape the vectors to be of the shape x - (n_samples, n_features) and y (n_samples, n_targets) x = red['density'].values.reshape(-1, 1) y = red['fixed acidity'].values.reshape(-1, 1) ``` ``` # Create linear regression object model = linear_model.LinearRegression() # Use model to fit to the data, the x values are densities and the y values are fixed acidity # Note that we need to reshape the vectors to be of the shape x - (n_samples, n_features) and y (n_samples, n_targets) x = red['density'].values.reshape(-1, 1) y = red['fixed acidity'].values.reshape(-1, 1) ``` ``` print(red['density'].values.shape, red['fixed acidity'].values.shape) print(x.shape, y.shape) ``` ``` print(red['density'].values.shape, red['fixed acidity'].values.shape) print(x.shape, y.shape) ``` ``` # Fit to the data model.fit(x, y) # Extract the values of interest m = model.coef_[0][0] b = model.intercept_[0] # Print the slope m and intercept b print('Scikit learn - Slope: ', m , 'Intercept: ', b ) ``` What happens when we try to fit the data as is? ``` # Fit to the data # model.fit(x, y) ``` #### Exercise 2: drop Null Values (and practice pandas operations) Let's look back at our dataset description dataframe above, what do we notice, what contains null values? There are several strategies for dealing with null values. For now let's take the simplest case, and drop rows in our dataframe that contain null ``` # Cell for Exercise 2 # For this templated exercise you are going to complete everything in one line # of code, but we are going to break it up into steps. So for each part (A, B, # etc.) paste your answer from the previous part to begin # step A # select the 'density' and 'fixed acidity' columns of red. make sure the return # is a dataframe # step B # now use the dropna() method on axis 0 (the rows) to drop any null values # step B # select column 'density' # step C # select the values # step D # reshape the result with an empty second dimension using .reshape() and store # the result under variable x # repeat the same process with 'fixed acidity' and variable y ``` Now that we have our x and y arrays we can fit using ScikitLearn ``` x = red[['density', 'fixed acidity']].dropna(axis=0)['density'].values.reshape(-1,1) y = red[['density', 'fixed acidity']].dropna(axis=0)['fixed acidity'].values.reshape(-1,1) # Fit to the data model.fit(x, y) # Extract the values of interest m = model.coef_[0][0] b = model.intercept_[0] # Print the slope m and intercept b print('Scikit learn - Slope: ', m , 'Intercept: ', b ) ``` #### Exercise 3: calculating y_pred Estimate the values of $y$ by using your fitted parameters. Hint: Use your <code>model.coef_</code> and <code>model.intercept_</code> parameters to estimate y_pred following equation 1 ``` # define y_pred in terms of m, x, and b # y_pred = fig, ax = plt.subplots(1,1, figsize=(10,10)) ax.plot(x, y_pred, ls='', marker='*') ax.plot(x, y, ls='', marker='.') ``` We can also return predictions directly with the model object using the predict() method ``` # Another way to get this is using the model.predict function y_pred = model.predict(x) fig, ax = plt.subplots(1,1, figsize=(10,10)) ax.plot(x, y_pred, ls='', marker='*') ax.plot(x, y, ls='', marker='.') ``` ## 1.3 Error and topics of model fitting (assessing model accuracy) ### 1.3.1 Measuring the quality of fit #### 1.3.1.1 Mean Squared Error The plot in Section 1.2.3 looks good, but numerically what is our error? What is the mean value of $\epsilon$, i.e. the **Mean Squared Error (MSE)**? $${\sf MSE}=\epsilon_{\sf ave} = \frac{\sum_{i=1}^{N_{\sf times}}\left(y^{\sf exact}_i - m\cdot t_i - b \right)^2}{N_{\sf times}}\;\;\;\;\;\sf eq. 3$$ ``` # The mean squared error print('Mean squared error: %.2f' % mean_squared_error(y, y_pred)) ``` ``` # The mean squared error print('Mean squared error: %.2f' % mean_squared_error(y, y_pred)) ``` #### 1.3.1.2 R-square Another way to measure error is the regression score, $R^2$. $R^2$ is generally defined as the ratio of the total sum of squares $SS_{\sf tot} $ to the residual sum of squares $SS_{\sf res} $: $$SS_{\sf tot}=\sum_{i=1}^{N} \left(y^{\sf exact}_i-\bar{y}\right)^2\;\;\;\;\; \sf eq. 4$$ $$SS_{\sf res}=\sum_{i=1}^{N} \left(y^{\sf exact}_i - y^{\sf calc}_i\right)^2\;\;\;\;\; \sf eq. 5$$ $$R^2 = 1 - {SS_{\sf res}\over SS_{\sf tot}} \;\;\;\;\;\; \sf eq. 6$$ In eq. 4, $\bar{y}=\sum_i y^{\sf exact}_i/N$ is the average value of y for $N$ points. The best value of $R^2$ is 1 but it can also take a negative value if the error is large. See all the different regression metrics [here](https://scikit-learn.org/stable/modules/model_evaluation.html). #### Question 3 > Do we need a large value of $SS_{\sf tot}$ to minimize $R^2$ - is this something which we have the power to control? ``` # Print the coefficient of determination - 1 is perfect prediction print('Coefficient of determination: %.2f' % r2_score(y, y_pred)) ``` ``` # Print the coefficient of determination - 1 is perfect prediction print('Coefficient of determination: %.2f' % r2_score(y, y_pred)) ``` ### 1.3.2 Corollaries with classification models For classification tasks, we typically assess accuracy vs MSE or R-square, since we are dealing with categorical rather than numerical predictions. What is accuracy? It is defined as the ratio of True assignments to all assignments. For a binary positive/negative classification task this can be written as the following: $ Acc = \frac{T_p + T_n}{F_p + F_n + T_p + T_n} $ Where $T$ is True, $F$ is false, $p$ is positive, $n$ is negative Just as a quick example, we can perform this type of task on our wine dataset by predicting on quality, which is a discrete 3-9 quality score: ``` y_train = df['type'].values.reshape(-1,1) x_train = df['quality'].values.reshape(-1,1) # train a logistic regression model on the training set from sklearn.linear_model import LogisticRegression # instantiate model logreg = LogisticRegression() # fit model logreg.fit(x_train, y_train) # make class predictions for the testing set y_pred_class = logreg.predict(x_train) # calculate accuracy from sklearn import metrics print(metrics.accuracy_score(y_train, y_pred_class)) ``` ### 1.3.3 Beyond a single input feature (_also: quick appreciative beat for folding in domain area expertise into our models and features_) The **acidity** of the wine (the dependent variable v) could depend on: * potassium from the soil (increases alkalinity) * unripe grapes (increases acidity) * grapes grown in colder climates or reduced sunshine create less sugar (increases acidity) * preprocessing such as adding tartaric acid to the grape juice before fermentation (increases acidity) * malolactic fermentation (reduces acidity) * \+ others So in our lab today we will look at folding in additional variables in our dataset into the model <hr style="border:1px solid grey"> </hr> ## 1.4 Multivariate regression Let's now turn our attention to wine quality. The value we aim to predict or evaluate is the quality of each wine in our dataset. This is our dependent variable. We will look at how this is related to the 12 other independent variables, also known as *input features*. We're going to do this is just the red wine data ``` red.head() ``` ### 1.4.1 Linear regression with all input fields For this example, notice we have a categorical data variable in the 'type' column. We will ignore this for now, and only work with our red wines. In the future we will discuss how to deal with categorical variable such as this in a mathematical representation. ``` # this is a list of all our features or independent variables features = list(red.columns[1:]) # we're going to remove our target or dependent variable, density from this # list features.remove('density') # now we define X and y according to these lists of names X = red.dropna(axis=0)[features].values y = red.dropna(axis=0)['density'].values red.isnull().sum(axis=0) # we are getting rid of some nasty nulls! ``` ``` # Create linear regression object - note that we are using all the input features model = linear_model.LinearRegression() model.fit(X, y) y_calc = model.predict(X) ``` ``` # Create linear regression object - note that we are using all the input features model = linear_model.LinearRegression() model.fit(X, y) y_calc = model.predict(X) ``` Let's see what the coefficients look like ... ``` print("Fit coefficients: \n", model.coef_, "\nNumber of coefficients:", len(model.coef_)) ``` ``` print("Fit coefficients: \n", model.coef_, "\nNumber of coefficients:", len(model.coef_)) ``` We have 11 !!! That's because we are regressing respect to all **11 independent variables**!!! So now, $$y_{\sf calc}= m_1x_1 +\, m_2x_2 \,+ \,m_3x_3 \,+\,... \,+ \,b =\sum_{i=1}^{13}m_i x_i + b\;\;\;\;\; \sf eq. 7$$ ``` print("We have 13 slopes / weights:\n\n", model.coef_) print("\nAnd one intercept: ", model.intercept_) ``` ``` print("We have 11 slopes / weights:\n\n", model.coef_) print("\nAnd one intercept: ", model.intercept_) ``` ``` # This size should match the number of columns in X if len(X[0]) == len(model.coef_): print("All good! The number of coefficients matches the number of input features.") else: print("Hmm .. something strange is going on.") ``` ``` # This size should match the number of columns in X if len(X[0]) == len(model.coef_): print("All good! The number of coefficients matches the number of input features.") else: print("Hmm .. something strange is going on.") ``` ### 1.4.2 Exercise 4: evaluate the error Let's **evaluate the error** by computing the MSE and $R^2$ metrics (see eq. 3 and 6). ``` # The mean squared error # part A # calculate the MSE using mean_squared_error() # mse = # part B # calculate the R square using r2_score() # r2 = print('Mean squared error: {:.2f}'.format(mse) print('Coefficient of determination: {:.2f}'.format(r2) ``` ``` # The mean squared error # part A # calculate the MSE using mean_squared_error() # mse = # part B # calculate the R square using r2_score() # r2 = print('Mean squared error: {:.2f}'.format(mse) print('Coefficient of determination: {:.2f}'.format(r2) ``` ### 1.4.3 Exercise 5: make a plot of y actual vs y predicted We can also look at how well the computed values match the true values graphically by generating a scatterplot. ``` # generate a plot of y predicted vs y actual using plt.plot() # remember you must set ls to an empty string and marker to some marker style # plt.plot() plt.title("Linear regression - computed values on entire data set", fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() ``` ``` # generate a plot of y predicted vs y actual using plt.plot() # remember you must set ls to an empty string and marker to some marker style # plt.plot() plt.title("Linear regression - computed values on entire data set", fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() ``` ### 1.4.2 **Enrichment**: Splitting into train and test sets To see whether we can predict, we will carry out our regression only on a part, 80%, of the full data set. This part is called the **training** data. We will then test the trained model to predict the rest of the data, 20% - the **test** data. The function which fits won't see the test data until it has to predict it. **We will motivate the use of train/test sets more explicitly in Course 2 Session 1** We start by splitting out data using scikit-learn's <code> train_test_split() </code> function: ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42) ``` ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42) ``` Now we check the size of <code> y_train </code> and <code> y_test </code>, the sum should be the size of y! If this works then we move on and carry out regression but we only use the training data! ``` if len(y_test)+len(y_train) == len(y): print('All good, ready to to go and regress!\n') # Carry out linear regression print('Running linear regression algorithm on the training set\n') model = linear_model.LinearRegression() model.fit(X_train, y_train) print('Fit coefficients and intercept:\n\n', model.coef_, '\n\n', model.intercept_ ) # Predict on the test set y_pred_test = model.predict(X_test) ``` ``` if len(y_test)+len(y_train) == len(y): print('All good, ready to to go and regress!\n') # Carry out linear regression print('Running linear regression algorithm on the training set\n') model = linear_model.LinearRegression() model.fit(X_train, y_train) print('Fit coefficients and intercept:\n\n', model.coef_, '\n\n', model.intercept_ ) # Predict on the test set y_pred_test = model.predict(X_test) ``` Now we can plot our predicted values to see how accurate we are in predicting. We will generate a scatterplot and computing the MSE and $R^2$ metrics of error. ``` sns.scatterplot(x=y_pred_test, y=y_test, color="mediumvioletred", s=50) plt.title("Linear regression - predict test set", fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() print('Mean squared error: %.2f' % mean_squared_error(y_test, y_pred_test)) print('Coefficient of determination: %.2f' % r2_score(y_test, y_pred_test)) ``` ``` sns.scatterplot(x=y_pred_test, y=y_test, color="mediumvioletred", s=50) plt.title("Linear regression - predict test set", fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() print('Mean squared error: %.2f' % mean_squared_error(y_test, y_pred_test)) print('Coefficient of determination: %.2f' % r2_score(y_test, y_pred_test)) ``` #### 1.4.2.1 Other data considerations * Do we need all the independent variables? * Topics of interential statistics covered in a couple sessions * Can we output integer quality scores? * Topics of non-binary classification tasks covered in week 4 ### 1.4.3 **Enrichment**: Other regression algorithms There are many other regression algorithms the two we want to highlight here are Ridge, LASSO, and Elastic Net. They differ by an added term to the loss function. Let's review. Eq. 2 expanded to multivariate form yields: $$\sum_{i=1}^{N}(y_i - \sum_{j=1}^{P}x_{ij}\beta_{j})^2$$ for Ridge regression, we add a **_regularization_** term known as **_L2_** regularization: $$\sum_{i=1}^{N}(y_i - \sum_{j=1}^{P}x_{ij}\beta_{j})^2 + \lambda \sum_{j=1}^{P}\beta_{j}^2$$ for **_LASSO_** (Least Absolute Shrinkage and Selection Operator) we add **_L1_** regularization: $$\sum_{i=1}^{N}(y_i - \sum_{j=1}^{P}x_{ij}\beta_{j})^2 + \lambda \sum_{j=1}^{P}|\beta_{j}|$$ The key difference here is that LASSO will allow coefficients to shrink to 0 while Ridge regression will not. **_Elastic Net_** is a combination of these two regularization methods. ``` model = linear_model.Ridge() model.fit(X_train, y_train) print('Fit coefficients and intercept:\n\n', model.coef_, '\n\n', model.intercept_ ) # Predict on the test set y_calc_test = model.predict(X_test) ``` ``` model = linear_model.Ridge() model.fit(X_train, y_train) print('Fit coefficients and intercept:\n\n', model.coef_, '\n\n', model.intercept_ ) # Predict on the test set y_calc_test = model.predict(X_test) ``` ``` sns.scatterplot(x=y_calc_test, y=y_test, color="lightseagreen", s=50) plt.title("Ridge regression - predict test set",fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() print('Mean squared error: %.2f' % mean_squared_error(y_test, y_calc_test)) print('Coefficient of determination: %.2f' % r2_score(y_test, y_calc_test)) ``` ``` sns.scatterplot(x=y_calc_test, y=y_test, color="lightseagreen", s=50) plt.title("Ridge regression - predict test set",fontsize=16) plt.xlabel("y$^{\sf calc}$") plt.ylabel("y$^{\sf true}$") plt.show() print('Mean squared error: %.2f' % mean_squared_error(y_test, y_calc_test)) print('Coefficient of determination: %.2f' % r2_score(y_test, y_calc_test)) ``` #### Exercise 6: Tune Hyperparameter for Ridge Regression Use the docstring to peak into the hyperparameters for Ridge Regression. What is the optimal value of lambda? Plot the $\beta$ values vs $\lambda$ from the results of your analysis ``` # cell for exercise 3 out_lambdas = [] out_coefs = [] out_scores = [] for i in range(10): lambdas = [] coefs = [] scores = [] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20) for lamb in range(1,110): model = linear_model.Ridge(alpha=lamb/50, normalize=True) model.fit(X_train, y_train) lambdas.append(lamb) coefs.append(model.coef_) scores.append(r2_score(y_test, model.predict(X_test))) # print('MSE: %.4f' % mean_squared_error(y_test, model.predict(X_test))) # print('R2: %.4f' % r2_score(y_test, model.predict(X_test))) out_lambdas.append(lambdas) out_coefs.append(coefs) out_scores.append(scores) coef_means = np.array(out_coefs).mean(axis=0) coef_stds = np.array(out_coefs).std(axis=0) results_means = pd.DataFrame(coef_means,columns=features) results_stds = pd.DataFrame(coef_stds,columns=features) results_means['lambda'] = [i/50 for i in lambdas] fig, ax = plt.subplots(1,1,figsize=(10,10)) for feat in features: ax.errorbar([i/50 for i in lambdas], results_means[feat], yerr=results_stds[feat], label=feat) # results.plot('lambda', 'scores', ax=ax[1]) ax.legend() results = pd.DataFrame(coefs,columns=features) results['lambda'] = [i/50 for i in lambdas] results['scores'] = scores fig, ax = plt.subplots(1,2,figsize=(10,5)) for feat in features: results.plot('lambda', feat, ax=ax[0]) results.plot('lambda', 'scores', ax=ax[1]) ``` ## 1.5 **Enrichment**: Additional Regression Exercises ### Problem 1) Number and choice of input features * Load the red wine dataset and evaluate how the linear regression predictions changes as you change the **number and choice of input features**. The total number of columns in X is 11 and each column represent a specific input feature. * Estimate the MSE ``` print(X_train.shape) ``` ``` print(X_train.shape) ``` If you want to use the first 5 features you could proceed as following: ``` X_train_five = X_train[:,0:5] X_test_five = X_test[:,0:5] ``` ``` X_train_five = X_train[:,0:5] X_test_five = X_test[:,0:5] ``` Check that the new variables have the shape your expect ``` print(X_train_five.shape) print(X_test_five.shape) ``` ``` print(X_train_five.shape) print(X_test_five.shape) ``` Now you can use these to train your linear regression model and repeat for different numbers or sets of input features! Note that you do not need to change the output feature! It's size is independent from the number of input features, yet recall that its length is the same as the number of values per input feature. Questions to think about while you work on this problem - How many input feature variables does one need? Is there a maximum or minimum number? - Could one input feature variable be better than the rest? - What if values are missing for one of the input feature variables - is it still worth using it? - Can you use **_L1_** or **_L2_** to determine these optimum features more quickly? ### Problem 2) Type of regression algorithm Try using other types of linear regression methods on the wine dataset: the LASSO model and the Elastic net model which are described by the <code > sklearn.linear_model.ElasticNet() </code> <br> <code > sklearn.linear_model.Lasso() </code> scikit-learn functions. For more detail see [ElasticNet](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html#sklearn.linear_model.ElasticNet) and [Lasso]( https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html#sklearn.linear_model.Lasso). Questions to think about while you work on this problem - How does the error change with each model? - Which model seems to perform best? - How can you optimize the hyperparameter, $\lambda$ - Does one model do better than the other at determining which input features are more important? - How about non linear regression / what if the data does not follow a line? - How do the bias and variance change for each model ``` from sklearn.linear_model import ElasticNet from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge from sklearn.linear_model import LinearRegression for model in [ElasticNet, Lasso, Ridge, LinearRegression]: model = model() model.fit(X_train, y_train) print('Mean squared error: %.2f' % mean_squared_error(y_test, model.predict(X_test))) print('Coefficient of determination: %.2f' % r2_score(y_test, model.predict(X_test))) ``` <hr style="border:1px solid grey"> </hr> # References * **Linear Regression** To find out more see https://en.wikipedia.org/wiki/Simple_linear_regression * **scikit-learn** * Scikit-learn: https://scikit-learn.org/stable/ * Linear regression in scikit-learn: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html * Metrics of error: https://scikit-learn.org/stable/modules/model_evaluation.html * The Boston dataset: https://scikit-learn.org/stable/datasets/index.html#boston-dataset * **Pearson correlation** To find out more see https://en.wikipedia.org/wiki/Pearson_correlation_coefficient * **Irreducible error, bias and variance** * Great Coursera videos here: https://www.coursera.org/lecture/ml-regression/irreducible-error-and-bias-qlMrZ and here: https://www.coursera.org/lecture/ml-regression/variance-and-the-bias-variance-tradeoff-ZvP40
github_jupyter
## Hosting a Pretrained Model on SageMaker Amazon SageMaker is a service to accelerate the entire machine learning lifecycle. It includes components for building, training and deploying machine learning models. Each SageMaker component is modular, so you're welcome to only use the features needed for your use case. One of the most popular features of SageMaker is [model hosting](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-deployment.html). Using SageMaker Hosting you can deploy your model as a scalable, highly available, multi-process API endpoint with a few lines of code. In this notebook, we will demonstrate how to host a pretrained model (GPT-2) in Amazon SageMaker. SageMaker provides prebuilt containers that can be used for training, hosting, or data processing. The inference containers include a web serving stack, so you don't need to install and configure one. We will be using the SageMaker [PyTorch container](https://github.com/aws/deep-learning-containers), but you may use the [TensorFlow container](https://github.com/aws/deep-learning-containers/blob/master/available_images.md), or bring your own container if needed. This notebook will walk you through how to deploy a pretrained Hugging Face model as a scalable, highly available, production ready API in under 15 minutes. ## Retrieve Model Artifacts First we will download the model artifacts for the pretrained [GPT-2](https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) model. GPT-2 is a popular text generation model that was developed by OpenAI. Given a text prompt it can generate synthetic text that may follow. ``` !pip install transformers==3.3.1 sagemaker==2.15.0 --quiet import os from transformers import GPT2Tokenizer, GPT2LMHeadModel tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2LMHeadModel.from_pretrained('gpt2') model_path = 'model/' code_path = 'code/' if not os.path.exists(model_path): os.mkdir(model_path) model.save_pretrained(save_directory=model_path) tokenizer.save_vocabulary(save_directory=model_path) ``` ## Write the Inference Script Since we are bringing a model to SageMaker, we must create an inference script. The script will run inside our PyTorch container. Our script should include a function for model loading, and optionally functions generating predicitions, and input/output processing. The PyTorch container provides default implementations for generating a prediction and input/output processing. By including these functions in your script you are overriding the default functions. You can find additional [details here](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#serve-a-pytorch-model). In the next cell we'll see our inference script. You will notice that it uses the [transformers library from Hugging Face](https://huggingface.co/transformers/). This Python library is not installed in the container by default, so we will have to add that in the next section. ``` !pygmentize code/inference_code.py ``` ## Package Model For hosting, SageMaker requires that the deployment package be structed in a compatible format. It expects all files to be packaged in a tar archive named "model.tar.gz" with gzip compression. To install additional libraries at container startup, we can add a [requirements.txt](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#using-third-party-libraries) text file that specifies the libraries to be installed using [pip](https://pypi.org/project/pip/). Within the archive, the PyTorch container expects all inference code and requirements.txt file to be inside the code/ directory. See the [guide here](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#for-versions-1-2-and-higher) for a thorough explanation of the required directory structure. ``` import tarfile zipped_model_path = os.path.join(model_path, "model.tar.gz") with tarfile.open(zipped_model_path, "w:gz") as tar: tar.add(model_path) tar.add(code_path) ``` ## Deploy Model Now that we have our deployment package, we can use the [SageMaker SDK](https://sagemaker.readthedocs.io/en/stable/index.html) to deploy our API endpoint with two lines of code. We need to specify an IAM role for the SageMaker endpoint to use. Minimally, it will need read access to the default SageMaker bucket (usually named sagemaker-{region}-{your account number}) so it can read the deployment package. When we call deploy(), the SDK will save our deployment archive to S3 for the SageMaker endpoint to use. We will use the helper function [get_execution_role](https://sagemaker.readthedocs.io/en/stable/api/utility/session.html?highlight=get_execution_role#sagemaker.session.get_execution_role) to retrieve our current IAM role so we can pass it to the SageMaker endpoint. You may specify another IAM role here. Minimally it will require read access to the model artifacts in S3 and the [ECR repository](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) where the container image is stored by AWS. You may notice that we specify our PyTorch version and Python version when creating the PyTorchModel object. The SageMaker SDK uses these parameters to determine which PyTorch container to use. The full size [GPT-2 model has 1.2 billion parameters](https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf). Even though we are using the small version of the model, our endpoint will need to fit millions of parameters in to memory. We'll choose an m5 instance for our endpoint to ensure we have sufficient memory to serve our model. ``` from sagemaker.pytorch import PyTorchModel from sagemaker import get_execution_role endpoint_name = 'GPT2' model = PyTorchModel(entry_point='inference_code.py', model_data=zipped_model_path, role=get_execution_role(), framework_version='1.5', py_version='py3') predictor = model.deploy(initial_instance_count=1, instance_type='ml.m5.xlarge', endpoint_name=endpoint_name) ``` ## Get Predictions Now that our RESTful API endpoint is deployed, we can send it text to get predictions from our GPT-2 model. You can use the SageMaker Python SDK or the [SageMaker Runtime API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html) to invoke the endpoint. ``` import boto3 import json sm = boto3.client('sagemaker-runtime') prompt = "Working with SageMaker makes machine learning " response = sm.invoke_endpoint(EndpointName=endpoint_name, Body=json.dumps(prompt), ContentType='text/csv') response['Body'].read().decode('utf-8') ``` ## Conclusion You have successfully created a scalable, high available, RESTful API that is backed by a GPT-2 model! If you are still interested in learning more, check out some of the more advanced features of SageMaker Hosting, like [model monitoring](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html) to detect concept drift, [autoscaling](https://docs.aws.amazon.com/sagemaker/latest/dg/endpoint-auto-scaling.html) to dynamically adjust the number of instances, or [VPC config](https://docs.aws.amazon.com/sagemaker/latest/dg/host-vpc.html) to control network access to/from your endpoint. You can also look in to the [ezsmdeploy SDK](https://aws.amazon.com/blogs/opensource/deploy-machine-learning-models-to-amazon-sagemaker-using-the-ezsmdeploy-python-package-and-a-few-lines-of-code/) that automates most of this process.
github_jupyter
# Navigation --- You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started! ### 1. Start the Environment Run the next code cell to install a few packages. This line will take a few minutes to run! ``` !pip install numpy --upgrade !pip -q install ./python ``` The environment is already saved in the Workspace and can be accessed at the file path provided below. Please run the next code cell without making any changes. ``` from unityagents import UnityEnvironment from dqn_agent import Agent import torch import numpy as np import random from collections import deque import matplotlib.pyplot as plt %matplotlib inline # please do not modify the line below env = UnityEnvironment(file_name="/data/Banana_Linux_NoVis/Banana.x86_64") ``` Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. ``` # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] ``` ### 2. Examine the State and Action Spaces Run the code cell below to print some information about the environment. ``` # reset the environment env_info = env.reset(train_mode=True)[brain_name] # number of agents in the environment print('Number of agents:', len(env_info.agents)) # number of actions action_size = brain.vector_action_space_size print('Number of actions:', action_size) # examine the state space state = env_info.vector_observations[0] print('States look like:', state) state_size = len(state) print('States have length:', state_size) ``` ### 3. Take Random Actions in the Environment In the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment. Note that **in this coding environment, you will not be able to watch the agent while it is training**, and you should set `train_mode=True` to restart the environment. ``` #Here we are taking random steps env_info = env.reset(train_mode=True)[brain_name] # reset the environment state = env_info.vector_observations[0] # get the current state score = 0 # initialize the score while True: action = np.random.randint(action_size) # select an action env_info = env.step(action)[brain_name] # send the action to the environment next_state = env_info.vector_observations[0] # get the next state reward = env_info.rewards[0] # get the reward done = env_info.local_done[0] # see if episode has finished score += reward # update the score state = next_state # roll over the state to next time step if done: # exit loop if episode finished break print("Score: {}".format(score)) ``` When finished, you can close the environment. ### 4. Train your agent A few **important notes**: - When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following: ```python env_info = env.reset(train_mode=True)[brain_name] ``` - In this coding environment, you will not be able to watch the agent while it is training. However, **_after training the agent_**, you can download the saved model weights to watch the agent on your own machine! ##### 4.1 Learning Algorithm - DQN Deep Q-Networks(DQN) was proposed by Mnih et al. (2015). It takes agent's state as input and outputs Q action values. It uses experience replay and target network to stabilize the model training. <figure> <img src="images/pseudocode-dqn.png" width="400" height="400"> <br> <figcaption style = "text-align:center; font-style:italic">Taken from Human-level control through deep reinforcement learning(Mnih et al. (2015))</figcaption> </figure> ##### 4.2 Model Architecture The model is made of three fully connected layers. The number of neurons in first two layers is 64 and in the last layer it's equal to action size. Each layer's output except the last layer is transformed using the RelU activation function. ##### 4.3 Hyperparameters * BUFFER_SIZE = int(1e5) # replay buffer size * BATCH_SIZE = 64 # minibatch size * GAMMA = 0.99 # discount factor * TAU = 1e-3 # for soft update of target parameters * LR = 5e-4 # learning rate * n_episodes = 2000 # maximum number of training episodes * max_t = 1000 # maximum number of time steps per episode * eps_start = 1.0 # starting value of epsilon, for epsilon-greedy action selection * eps_end = 0.01 # minimum value of epsilon * eps_decay = 0.995 # multiplicative factor (per episode) for decreasing epsilon ``` agent = Agent(state_size=37, action_size=4, seed=0) def dqn(n_episodes = 2000, max_t = 1000, eps_start = 1.0, eps_end = 0.01, eps_decay = 0.995): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of time steps per episode eps_start (float): starting value of epsilon, for epsilon-greedy action selection eps_end (float) : minimum value of epsilon eps_decay (float) : multiplicative factor (per episode) for decreasing epsilon """ scores = [] #list containing scores from each episode scores_window = deque(maxlen = 100) # last 100 scores eps = eps_start #Initialize epsilon for i_episode in range(1, n_episodes+1): env_info = env.reset(train_mode=True)[brain_name] state = env_info.vector_observations[0] score = 0 for t in range(max_t): action = agent.act(state, eps) env_info = env.step(action)[brain_name] next_state = env_info.vector_observations[0] reward = env_info.rewards[0] done = env_info.local_done[0] agent.step(state, action, reward, next_state, done) state = next_state score += reward if done: break scores_window.append(score) # save most recent scores scores.append(score) # save most recent score eps = max(eps_end, eps_decay*eps) # decrease epsilon print("\rEpisode {}\tAverage Score: {:.2f}".format(i_episode, np.mean(scores_window)), end ="") if i_episode % 100 == 0: print("\rEpisode {}\tAverage Score: {:.2f}".format(i_episode, np.mean(scores_window))) if np.mean(scores_window) >= 13.0: print("\nEnvironment solved in {:d} episodes!\t Average score: {:.2f}".format(i_episode, np.mean(scores_window))) torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth') break return scores scores = dqn() fig = plt.figure() ax = fig.add_subplot(111) plt.plot(np.arange(len(scores)), scores) plt.ylabel("Score") plt.xlabel("No of Episodes") plt.show() #Load a trained agent agent.qnetwork_local.load_state_dict(torch.load("checkpoint.pth")) for i in range(3): env_info = env.reset(train_mode=False)[brain_name] state = env_info.vector_observations[0] score = 0 for j in range(1000): action = agent.act(state) env_info = env.step(action)[brain_name] next_state = env_info.vector_observations[0] reward = env_info.rewards[0] done = env_info.local_done[0] agent.step(state, action, reward, next_state, done) state = next_state score += reward if done: break print("\rEpisode {}\t Score: {:.2f}".format(i+1, score)) env.close() ``` ### 5. Future ideas to improve the agent's performance More experiments can be done to increase the performance of agent by applying different extensions of DQN: * Double DQN (DDQN) * Prioritized experience replay * Dueling DQN * A3C * Distributional DQN * Noisy DQN We can also apply all the abobe extensions together. This was done by Deepmind's researchers and they have termed it Rainbow. This algorithm has outperformed each of the extension achieved SOTA results on Atari 2600. <figure> <img src="images/rainbow.png" width="400" height="400"> <br> <figcaption style = "text-align:center; font-style:italic">Taken from Rainbow: Combining Improvements in Deep Reinforcement Learning(Hessel et al. (2017))</figcaption> </figure>
github_jupyter
``` !rm -rf output-*/ ``` ## Test 1: discretize = False ``` !mkdir -p output-1 !docker run -it \ --mount type='bind',src="$(pwd)",target='/datadir' \ fiddle-v020 \ python -m FIDDLE.run \ --data_fname='/datadir/input/data.csv' \ --population_fname='/datadir/input/pop.csv' \ --config_fname='/datadir/input/config-1.yaml' \ --output_dir='/datadir/output-1/' \ --T=4 --dt=1.0 \ --theta_1=0.001 --theta_2=0.001 --theta_freq=1 \ --stats_functions 'min' 'max' 'mean' \ --no_prefilter --no_postfilter import numpy as np import pandas as pd import json import sparse S = sparse.load_npz('output-1/S_all.npz') S_names = json.load(open('output-1/S_all.feature_names.json', 'r')) S_index = pd.read_csv('output-1/S.ID.csv').set_index(['ID']) df_S = pd.DataFrame(S.todense(), columns=S_names, index=S_index.index) X = sparse.load_npz('output-1/X_all.npz') X_names = json.load(open('output-1/X_all.feature_names.json', 'r')) X_index = pd.read_csv('output-1/X.ID,t_range.csv').set_index(['ID', 't_range']) df_X = pd.DataFrame(X.todense().reshape(-1, X.shape[-1]), columns=X_names, index=X_index.index) display(df_S) display(df_X) ``` ## Test 2: discretize = True, use_ordinal_encoding = False ``` !mkdir -p output-2 !docker run -it \ --mount type='bind',src="$(pwd)",target='/datadir' \ fiddle-v020 \ python -m FIDDLE.run \ --data_fname='/datadir/input/data.csv' \ --population_fname='/datadir/input/pop.csv' \ --config_fname='/datadir/input/config-2.yaml' \ --output_dir='/datadir/output-2/' \ --T=4 --dt=1.0 \ --theta_1=0.001 --theta_2=0.001 --theta_freq=1 \ --stats_functions 'min' 'max' 'mean' \ --no_prefilter --no_postfilter import numpy as np import pandas as pd import json import sparse S = sparse.load_npz('output-2/S_all.npz') S_names = json.load(open('output-2/S_all.feature_names.json', 'r')) S_index = pd.read_csv('output-2/S.ID.csv').set_index(['ID']) df_S = pd.DataFrame(S.todense(), columns=S_names, index=S_index.index) X = sparse.load_npz('output-2/X_all.npz') X_names = json.load(open('output-2/X_all.feature_names.json', 'r')) X_index = pd.read_csv('output-2/X.ID,t_range.csv').set_index(['ID', 't_range']) df_X = pd.DataFrame(X.todense().reshape(-1, X.shape[-1]), columns=X_names, index=X_index.index) display(df_S) display(df_X) ``` ## Test 3: discretize = True, use_ordinal_encoding = True ``` !mkdir -p output-3 !docker run -it \ --mount type='bind',src="$(pwd)",target='/datadir' \ fiddle-v020 \ python -m FIDDLE.run \ --data_fname='/datadir/input/data.csv' \ --population_fname='/datadir/input/pop.csv' \ --config_fname='/datadir/input/config-3.yaml' \ --output_dir='/datadir/output-3/' \ --T=4 --dt=1.0 \ --theta_1=0.001 --theta_2=0.001 --theta_freq=1 \ --stats_functions 'min' 'max' 'mean' \ --no_prefilter --no_postfilter import numpy as np import pandas as pd import json import sparse S = sparse.load_npz('output-3/S_all.npz') S_names = json.load(open('output-3/S_all.feature_names.json', 'r')) S_index = pd.read_csv('output-3/S.ID.csv').set_index(['ID']) df_S = pd.DataFrame(S.todense(), columns=S_names, index=S_index.index) X = sparse.load_npz('output-3/X_all.npz') X_names = json.load(open('output-3/X_all.feature_names.json', 'r')) X_index = pd.read_csv('output-3/X.ID,t_range.csv').set_index(['ID', 't_range']) df_X = pd.DataFrame(X.todense().reshape(-1, X.shape[-1]), columns=X_names, index=X_index.index) display(df_S) display(df_X) ```
github_jupyter
``` import numpy as np import torch import gym import pybullet_envs import os import utils import TD3 import OurDDPG import DDPG # Runs policy for X episodes and returns average reward # A fixed seed is used for the eval environment def eval_policy(policy, env_name, seed, eval_episodes=10): eval_env = gym.make(env_name) eval_env.seed(seed + 100) avg_reward = 0. for _ in range(eval_episodes): state, done = eval_env.reset(), False while not done: action = policy.select_action(np.array(state)) state, reward, done, _ = eval_env.step(action) avg_reward += reward avg_reward /= eval_episodes print("---------------------------------------") print(f"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}") print("---------------------------------------") return avg_reward def main(): args = { "policy" : "TD3", # Policy name (TD3, DDPG or OurDDPG) "env" : "AntBulletEnv-v0", # OpenAI gym environment name "seed" : 0, # Sets Gym, PyTorch and Numpy seeds "start_timesteps" : 25e3, # Time steps initial random policy is used "eval_freq" : 5e3, # How often (time steps) we evaluate "max_timesteps" : 2e6, # Max time steps to run environment "expl_noise" : 0.1, # Std of Gaussian exploration noise "batch_size" : 256, # Batch size for both actor and critic "discount" : 0.99, # Discount factor "tau" : 0.005, # Target network update rate "policy_noise" : 0.2, # Noise added to target policy during critic update "noise_clip" : 0.5, # Range to clip target policy noise "policy_freq" : 2, # Frequency of delayed policy updates "save_model" : "store_true", # Save model and optimizer parameters "load_model" : "", # Model load file name, "" doesn't load, "default" uses file_name } file_name = f"{args['policy']}_{args['env']}_{args['seed']}" print("---------------------------------------") print(f"Policy: {args['policy']}, Env: {args['env']}, Seed: {args['seed']}") print("---------------------------------------") if not os.path.exists("./results"): os.makedirs("./results") if args['save_model'] and not os.path.exists("./models"): os.makedirs("./models") env = gym.make(args['env']) # Set seeds env.seed(args['seed']) env.action_space.seed(args['seed']) torch.manual_seed(args['seed']) np.random.seed(args['seed']) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = float(env.action_space.high[0]) kwargs = { "state_dim": state_dim, "action_dim": action_dim, "max_action": max_action, "discount": args['discount'], "tau": args['tau'], } # Initialize policy if args['policy'] == "TD3": # Target policy smoothing is scaled wrt the action scale kwargs["policy_noise"] = args['policy_noise'] * max_action kwargs["noise_clip"] = args['noise_clip'] * max_action kwargs["policy_freq"] = args['policy_freq'] policy = TD3.TD3(**kwargs) elif args['policy'] == "OurDDPG": policy = OurDDPG.DDPG(**kwargs) elif args['policy'] == "DDPG": policy = DDPG.DDPG(**kwargs) if args['load_model'] != "": policy_file = file_name if args['load_model'] == "default" else args['load_model'] policy.load(f"./models/{policy_file}") replay_buffer = utils.ReplayBuffer(state_dim, action_dim) # Evaluate untrained policy evaluations = [eval_policy(policy, args['env'], args['seed'])] state, done = env.reset(), False episode_reward = 0 episode_timesteps = 0 episode_num = 0 for t in range(int(args['max_timesteps'])): episode_timesteps += 1 # Select action randomly or according to policy if t < args['start_timesteps']: action = env.action_space.sample() else: action = ( policy.select_action(np.array(state)) + np.random.normal(0, max_action * args['expl_noise'], size=action_dim) ).clip(-max_action, max_action) # Perform action next_state, reward, done, _ = env.step(action) done_bool = float(done) if episode_timesteps < env._max_episode_steps else 0 # Store data in replay buffer replay_buffer.add(state, action, next_state, reward, done_bool) state = next_state episode_reward += reward # Train agent after collecting sufficient data if t >= args['start_timesteps']: policy.train(replay_buffer, args['batch_size']) if done: # +1 to account for 0 indexing. +0 on ep_timesteps since it will increment +1 even if done=True print(f"Total T: {t+1} Episode Num: {episode_num+1} Episode T: {episode_timesteps} Reward: {episode_reward:.3f}") # Reset environment state, done = env.reset(), False episode_reward = 0 episode_timesteps = 0 episode_num += 1 # Evaluate episode if (t + 1) % args['eval_freq'] == 0: evaluations.append(eval_policy(policy, args['env'], args['seed'])) np.save(f"./results/{file_name}", evaluations) if args['save_model']: policy.save(f"./models/{file_name}") main() ```
github_jupyter
## Dependencies ``` import json, warnings, shutil from tweet_utility_scripts import * from tweet_utility_preprocess_roberta_scripts import * from transformers import TFRobertaModel, RobertaConfig from tokenizers import ByteLevelBPETokenizer from tensorflow.keras.models import Model from tensorflow.keras import optimizers, metrics, losses, layers from tensorflow.keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint SEED = 0 seed_everything(SEED) warnings.filterwarnings("ignore") ``` # Load data ``` database_base_path = '/kaggle/input/tweet-dataset-split-roberta-base-96/' k_fold = pd.read_csv(database_base_path + '5-fold.csv') display(k_fold.head()) # Unzip files !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_1.tar.gz !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_2.tar.gz !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_3.tar.gz # !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_4.tar.gz # !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96/fold_5.tar.gz ``` # Model parameters ``` vocab_path = database_base_path + 'vocab.json' merges_path = database_base_path + 'merges.txt' base_path = '/kaggle/input/qa-transformers/roberta/' config = { "MAX_LEN": 96, "BATCH_SIZE": 32, "EPOCHS": 5, "LEARNING_RATE": 3e-5, "ES_PATIENCE": 1, "question_size": 4, "N_FOLDS": 1, "base_model_path": base_path + 'roberta-base-tf_model.h5', "config_path": base_path + 'roberta-base-config.json' } with open('config.json', 'w') as json_file: json.dump(json.loads(json.dumps(config)), json_file) ``` # Model ``` module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False) def model_fn(MAX_LEN): input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids') attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask') base_model = TFRobertaModel.from_pretrained(config['base_model_path'], config=module_config, name="base_model") sequence_output = base_model({'input_ids': input_ids, 'attention_mask': attention_mask}) last_state = sequence_output[0] x_start = layers.Dropout(0.1)(last_state) x_start = layers.Conv1D(1, 1)(x_start) x_start = layers.Flatten()(x_start) y_start = layers.Activation('softmax', name='y_start')(x_start) x_end = layers.Dropout(0.1)(last_state) x_end = layers.Conv1D(1, 1)(x_end) x_end = layers.Flatten()(x_end) y_end = layers.Activation('softmax', name='y_end')(x_end) model = Model(inputs=[input_ids, attention_mask], outputs=[y_start, y_end]) model.compile(optimizers.Adam(lr=config['LEARNING_RATE']), loss=losses.CategoricalCrossentropy(), metrics=[metrics.CategoricalAccuracy()]) return model ``` # Tokenizer ``` tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path, lowercase=True, add_prefix_space=True) tokenizer.save('./') ``` # Train ``` history_list = [] AUTO = tf.data.experimental.AUTOTUNE for n_fold in range(config['N_FOLDS']): n_fold +=1 print('\nFOLD: %d' % (n_fold)) # Load data base_data_path = 'fold_%d/' % (n_fold) x_train = np.load(base_data_path + 'x_train.npy') y_train = np.load(base_data_path + 'y_train.npy') x_valid = np.load(base_data_path + 'x_valid.npy') y_valid = np.load(base_data_path + 'y_valid.npy') ### Delete data dir shutil.rmtree(base_data_path) # Train model model_path = 'model_fold_%d.h5' % (n_fold) model = model_fn(config['MAX_LEN']) es = EarlyStopping(monitor='val_loss', mode='min', patience=config['ES_PATIENCE'], restore_best_weights=True, verbose=1) checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True, save_weights_only=True) history = model.fit(list(x_train), list(y_train), validation_data=(list(x_valid), list(y_valid)), batch_size=config['BATCH_SIZE'], callbacks=[checkpoint, es], epochs=config['EPOCHS'], verbose=2).history history_list.append(history) # Make predictions train_preds = model.predict(list(x_train)) valid_preds = model.predict(list(x_valid)) k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'train', 'start_fold_%d' % (n_fold)] = train_preds[0].argmax(axis=-1) k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'train', 'end_fold_%d' % (n_fold)] = train_preds[1].argmax(axis=-1) k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'validation', 'start_fold_%d' % (n_fold)] = valid_preds[0].argmax(axis=-1) k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'validation', 'end_fold_%d' % (n_fold)] = valid_preds[1].argmax(axis=-1) k_fold['end_fold_%d' % (n_fold)] = k_fold['end_fold_%d' % (n_fold)].astype(int) k_fold['start_fold_%d' % (n_fold)] = k_fold['start_fold_%d' % (n_fold)].astype(int) k_fold['end_fold_%d' % (n_fold)].clip(0, k_fold['text_len'], inplace=True) k_fold['start_fold_%d' % (n_fold)].clip(0, k_fold['end_fold_%d' % (n_fold)], inplace=True) k_fold['prediction_fold_%d' % (n_fold)] = k_fold.apply(lambda x: decode(x['start_fold_%d' % (n_fold)], x['end_fold_%d' % (n_fold)], x['text'], config['question_size'], tokenizer), axis=1) k_fold['prediction_fold_%d' % (n_fold)].fillna('', inplace=True) k_fold['jaccard_fold_%d' % (n_fold)] = k_fold.apply(lambda x: jaccard(x['text'], x['prediction_fold_%d' % (n_fold)]), axis=1) ``` # Model loss graph ``` sns.set(style="whitegrid") for n_fold in range(config['N_FOLDS']): print('Fold: %d' % (n_fold+1)) plot_metrics(history_list[n_fold]) ``` # Model evaluation ``` display(evaluate_model_kfold(k_fold, config['N_FOLDS']).style.applymap(color_map)) ``` # Visualize predictions ``` display(k_fold[[c for c in k_fold.columns if not (c.startswith('textID') or c.startswith('text_len') or c.startswith('selected_text_len') or c.startswith('text_wordCnt') or c.startswith('selected_text_wordCnt') or c.startswith('fold_') or c.startswith('start_fold_') or c.startswith('end_fold_'))]].head(15)) ```
github_jupyter
# Ramp Optimization Examples This notebook outlines an example to optimize the ramp settings for a few different types of observations. In these types of optimizations, we must consider observations constraints such as saturation levels, SNR requirements, and limits on acquisition time. **Note**: The reported acquisition time does not include obsevatory and instrument-level overheads, such as slew times, filter changes, script compilations, etc. It only includes detector readout times (including reset frames). ``` # Import the usual libraries import numpy as np import matplotlib import matplotlib.pyplot as plt # Enable inline plotting at lower left %matplotlib inline import pynrc from pynrc import nrc_utils from pynrc.nrc_utils import S, jl_poly_fit from pynrc.pynrc_core import table_filter pynrc.setup_logging('WARNING', verbose=False) from astropy.table import Table # Progress bar from tqdm.auto import tqdm, trange ``` ## Example 1: M-Dwarf companion (imaging vs coronagraphy) We want to observe an M-Dwarf companion (K=18 mag) in the vicinity of a brighter F0V (K=13 mag) in the F430M filter. Assume the M-Dwarf flux is not significantly impacted by the brighter PSF (ie., in the background limited regime). In this scenario, the F0V star will saturate much more quickly compared to the fainter companion, so it limits which ramp settings we can use. We will test a couple different types of observations (direct imaging vs coronagraphy). ``` # Get stellar spectra and normalize at K-Band # The stellar_spectrum convenience function creates a Pysynphot spectrum bp_k = S.ObsBandpass('k') sp_M2V = pynrc.stellar_spectrum('M2V', 18, 'vegamag', bp_k)#, catname='ck04models') sp_F0V = pynrc.stellar_spectrum('F0V', 13, 'vegamag', bp_k)#, catname='ck04models') # Initiate a NIRCam observation nrc = pynrc.NIRCam(filter='F430M', wind_mode='WINDOW', xpix=160, ypix=160) # Set some observing constraints # Let's assume we want photometry on the primary to calibrate the M-Dwarf for direct imaging # - Set well_frac_max=0.75 # Want a SNR~100 in the F430M filter # - Set snr_goal=100 res = nrc.ramp_optimize(sp_M2V, sp_bright=sp_F0V, snr_goal=100, well_frac_max=0.75, verbose=True) # Print the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) # Do the same thing, but for coronagraphic mask instead nrc = pynrc.NIRCam(filter='F430M', image_mask='MASK430R', pupil_mask='CIRCLYOT', wind_mode='WINDOW', xpix=320, ypix=320) # We assume that longer ramps will give us the best SNR for time patterns = ['MEDIUM8', 'DEEP8'] res = nrc.ramp_optimize(sp_M2V, sp_bright=sp_F0V, snr_goal=100, patterns=patterns, even_nints=True) # Take the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) ``` **RESULTS** Based on these two comparisons, it looks like direct imaging is much more efficient in getting to the requisite SNR. In addition, direct imaging gives us a photometric comparison source that is inaccessible when occulting the primary with the coronagraph masks. **Of course, this assumes the companion exists in the background limit as opposed to the contrast limit.** ## Example 2: Exoplanet Coronagraphy We want to observe GJ 504 for an hour in the F444W filter using the MASK430R coronagraph. - What is the optimal ramp settings to maximize the SNR of GJ 504b? - What is the final background sensitivity limit? ``` # Get stellar spectra and normalize at K-Band # The stellar_spectrum convenience function creates a Pysynphot spectrum bp_k = pynrc.bp_2mass('ks') sp_G0V = pynrc.stellar_spectrum('G0V', 4, 'vegamag', bp_k) # Choose a representative planet spectrum planet = pynrc.planets_sb12(atmo='hy3s', mass=8, age=200, entropy=8, distance=17.5) sp_pl = planet.export_pysynphot() # Renormalize to F360M = 18.8 bp_l = pynrc.read_filter('F360M') # sp_pl = sp_pl.renorm(18.8, 'vegamag', bp_l) # Initiate a NIRCam observation nrc = pynrc.NIRCam(filter='F444W', pupil_mask='CIRCLYOT', image_mask='MASK430R', wind_mode='WINDOW', xpix=320, ypix=320) # Set even_nints=True assume 2 roll angles res = nrc.ramp_optimize(sp_pl, sp_bright=sp_G0V, tacq_max=3600, tacq_frac=0.05, even_nints=True, verbose=True) # Take the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) # The SHALLOWs, DEEPs, and MEDIUMs are very similar for SNR and efficiency. # Let's go with SHALLOW2 for more GROUPS & INTS # MEDIUM8 would be fine as well. nrc.update_detectors(read_mode='SHALLOW2', ngroup=10, nint=70) keys = list(nrc.multiaccum_times.keys()) keys.sort() for k in keys: print("{:<10}: {: 12.5f}".format(k, nrc.multiaccum_times[k])) # Background sensitivity (5 sigma) sens_dict = nrc.sensitivity(nsig=5, units='vegamag', verbose=True) ``` ## Example 3: Single-Object Grism Spectroscopy Similar to the above, but instead we want to obtain a slitless grism spectrum of a K=12 mag M0V dwarf. Each grism resolution element should have SNR~100. ``` # M0V star normalized to K=12 mags bp_k = S.ObsBandpass('k') sp_M0V = pynrc.stellar_spectrum('M0V', 12, 'vegamag', bp_k) nrc = pynrc.NIRCam(filter='F444W', pupil_mask='GRISMR', wind_mode='STRIPE', ypix=128) # Set a minimum of 10 integrations to be robust against cosmic rays # Also set a minimum of 10 groups for good ramp sampling res = nrc.ramp_optimize(sp_M0V, snr_goal=100, nint_min=10, ng_min=10, verbose=True) # Print the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) # Let's say we choose SHALLOW4, NGRP=10, NINT=10 # Update detector readout nrc.update_detectors(read_mode='SHALLOW4', ngroup=10, nint=10) keys = list(nrc.multiaccum_times.keys()) keys.sort() for k in keys: print("{:<10}: {: 12.5f}".format(k, nrc.multiaccum_times[k])) # Print final wavelength-dependent SNR # For spectroscopy, the snr_goal is the median over the bandpass snr_dict = nrc.sensitivity(sp=sp_M0V, forwardSNR=True, units='mJy', verbose=True) ``` **Mock observed spectrum** Create a series of ramp integrations based on the current NIRCam settings. The gen_exposures() function creates a series of mock observations in raw DMS format by default. By default, it's point source objects centered in the observing window. ``` # Ideal spectrum and wavelength solution wspec, imspec = nrc.calc_psf_from_coeff(sp=sp_M0V, return_hdul=False, return_oversample=False) # Resize to detector window nx = nrc.det_info['xpix'] ny = nrc.det_info['ypix'] # Shrink/expand nx (fill value of 0) # Then shrink to a size excluding wspec=0 # This assumes simulated spectrum is centered imspec = nrc_utils.pad_or_cut_to_size(imspec, (ny,nx)) wspec = nrc_utils.pad_or_cut_to_size(wspec, nx) # Add simple zodiacal background im_slope = imspec + nrc.bg_zodi() # Create a series of ramp integrations based on the current NIRCam settings # Output is a single HDUList with 10 INTs # Ignore detector non-linearity to return output in e-/sec kwargs = { 'apply_nonlinearity' : False, 'apply_flats' : False, } res = nrc.simulate_level1b('M0V Target', 0, 0, '2023-01-01', '12:00:00', im_slope=im_slope, return_hdul=True, **kwargs) res.info() tvals = nrc.Detector.times_group_avg header = res['PRIMARY'].header data_all = res['SCI'].data slope_list = [] for data in tqdm(data_all): ref = pynrc.ref_pixels.NRC_refs(data, header, DMS=True, do_all=False) ref.calc_avg_amps() ref.correct_amp_refs() # Linear fit to determine slope image cf = jl_poly_fit(tvals, ref.data, deg=1) slope_list.append(cf[1]) # Create a master averaged slope image slopes_all = np.array(slope_list) slope_sim = slopes_all.mean(axis=0) * nrc.Detector.gain fig, ax = plt.subplots(1,1, figsize=(12,3)) ax.imshow(slope_sim, vmin=0, vmax=10) fig.tight_layout() ind = wspec>0 # Estimate background emission and subtract from slope_sim bg = np.median(slope_sim[:,~ind]) slope_sim -= bg ind = wspec>0 plt.plot(wspec[ind], slope_sim[63,ind]) # Extract 2 spectral x 5 spatial pixels # First, cut out the central 5 pixels wspec_sub = wspec[ind] sh_new = (5, len(wspec_sub)) slope_sub = nrc_utils.pad_or_cut_to_size(slope_sim, sh_new) slope_sub_ideal = nrc_utils.pad_or_cut_to_size(imspec, sh_new) # Sum along the spatial axis spec = slope_sub.sum(axis=0) spec_ideal = slope_sub_ideal.sum(axis=0) spec_ideal_rebin = nrc_utils.frebin(spec_ideal, scale=0.5, total=False) # Build a quick RSRF from extracted ideal spectral slope sp_M0V.convert('mjy') rsrf = spec_ideal / sp_M0V.sample(wspec_sub*1e4) # Rebin along spectral direction wspec_rebin = nrc_utils.frebin(wspec_sub, scale=0.5, total=False) spec_rebin_cal = nrc_utils.frebin(spec/rsrf, scale=0.5, total=False) # Expected noise per extraction element snr_interp = np.interp(wspec_rebin, snr_dict['wave'], snr_dict['snr']) _spec_rebin = spec_ideal_rebin / snr_interp _spec_rebin_cal = _spec_rebin / nrc_utils.frebin(rsrf, scale=0.5, total=False) fig, ax = plt.subplots(1,1, figsize=(12,8)) ax.plot(sp_M0V.wave/1e4, sp_M0V.flux, label='Input Spectrum') ax.plot(wspec_rebin, spec_rebin_cal, alpha=0.7, label='Extracted Observation') ax.errorbar(wspec_rebin, spec_rebin_cal, yerr=_spec_rebin_cal, zorder=3, fmt='none', label='Expected Error Bars', alpha=0.7, color='C2') ax.set_ylim([0,10]) ax.set_xlim([3.7,5.1]) ax.set_xlabel('Wavelength ($\mu m$)') ax.set_ylabel('Flux (mJy)') ax.set_title('Simulated Spectrum') ax.legend(loc='upper right'); ``` ## Example 4: Exoplanet Transit Spectroscopy Let's say we want to observe an exoplanet transit using NIRCam grisms in the F322W2 filter. We assume a 2.1-hour transit duration for a K6V star (K=8.4 mag). ``` nrc = pynrc.NIRCam('F322W2', pupil_mask='GRISM0', wind_mode='STRIPE', ypix=64) # K6V star at K=8.4 mags bp_k = S.ObsBandpass('k') sp_K6V = pynrc.stellar_spectrum('K6V', 8.4, 'vegamag', bp_k) # Constraints well = 0.5 # Keep well below 50% full tacq = 2.1*3600. # 2.1 hour transit duration ng_max = 30 # Transit spectroscopy allows for up to 30 groups per integrations nint_max = int(1e6) # Effectively no limit on number of integrations # Let's bin the spectrum to R~100 # dw_bin is a passable parameter for specifiying spectral bin sizes R = 100 dw_bin = (nrc.bandpass.avgwave() / 10000) / R res = nrc.ramp_optimize(sp_K6V, tacq_max=tacq, nint_max=nint_max, ng_min=10, ng_max=ng_max, well_frac_max=well, dw_bin=dw_bin, verbose=True) # Print the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) # Even though BRIGHT1 has a slight efficiency preference over RAPID # and BRIGHT2, we decide to choose RAPID, because we are convinced # that saving all data (and no coadding) is a better option. # If APT informs you that the data rates or total data shorage is # an issue, you can select one of the other options. # Update to RAPID, ngroup=30, nint=700 and plot PPM nrc.update_detectors(read_mode='RAPID', ngroup=30, nint=700) snr_dict = nrc.sensitivity(sp=sp_K6V, dw_bin=dw_bin, forwardSNR=True, units='Jy') wave = np.array(snr_dict['wave']) snr = np.array(snr_dict['snr']) # Let assume bg subtraction of something with similar noise snr /= np.sqrt(2.) ppm = 1e6 / snr # NOTE: We have up until now neglected to include a "noise floor" # which represents the expected minimum achievable ppm from # unknown systematics. To first order, this can be added in # quadrature to the calculated PPM. noise_floor = 30 # in ppm ppm_floor = np.sqrt(ppm**2 + noise_floor**2) plt.plot(wave, ppm, marker='o', label='Calculated PPM') plt.plot(wave, ppm_floor, marker='o', label='PPM + Noise Floor') plt.xlabel('Wavelength ($\mu m$)') plt.ylabel('Noise Limit (PPM)') plt.xlim([2.4,4.1]) plt.ylim([20,100]) plt.legend() ``` ## Example 5: Extended Souce Expect some faint galaxies of 25 ABMag/arcsec^2 in our field. What is the best we can do with 10,000 seconds of acquisition time? ``` # Detection bandpass is F200W nrc = pynrc.NIRCam(filter='F200W') # Flat spectrum (in photlam) with ABMag = 25 in the NIRCam bandpass sp = pynrc.stellar_spectrum('flat', 25, 'abmag', nrc.bandpass) res = nrc.ramp_optimize(sp, is_extended=True, tacq_max=10000, tacq_frac=0.05, verbose=True) # Print the Top 2 settings for each readout pattern res2 = table_filter(res, 2) print(res2) # MEDIUM8 10 10 looks like a good option nrc.update_detectors(read_mode='MEDIUM8', ngroup=10, nint=10, verbose=True) # Calculate flux/mag for various nsigma detection limits tbl = Table(names=('Sigma', 'Point (nJy)', 'Extended (nJy/asec^2)', 'Point (AB Mag)', 'Extended (AB Mag/asec^2)')) tbl['Sigma'].format = '.0f' for k in tbl.keys()[1:]: tbl[k].format = '.2f' for sig in [1,3,5,10]: snr_dict1 = nrc.sensitivity(nsig=sig, units='nJy', verbose=False) snr_dict2 = nrc.sensitivity(nsig=sig, units='abmag', verbose=False) tbl.add_row([sig, snr_dict1[0]['sensitivity'], snr_dict1[1]['sensitivity'], snr_dict2[0]['sensitivity'], snr_dict2[1]['sensitivity']]) tbl ```
github_jupyter
# How to separate your credentials, secrets, and configurations from your source code with environment variables ## <a id="intro"></a>Introduction As a modern application, your application always deal with credentials, secrets and configurations to connect to other services like Authentication service, Database, Cloud services, Microservice, ect. It is not a good idea to keep your username, password and other credentials hard code in your source code as your credentials may leak when you share or publish the application. You need to delete or remark those credentials before you share the code which adds extra work for you. And eventually, you may forgot to do it. The services configurations such as API endpoint, Database URL should not be embedded in the source code too. The reason is every time you change or update the configurations you need to modify the code which may lead to more errors. How should we solve this issue? ### <a id=""></a>Store config in the environment The [Twelve-Factor App methodology](https://12factor.net/) which is one of the most influential pattern to designing scalable software-as-a-service application. The methodology [3rd factor](https://12factor.net/config) (aka Config principle) states that configuration information should be kept as environment as environment variables and injected into the application on runtime. >The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard. ### Introduction to .ENV file and dotenv The dotenv method lets the application loads variables from a ```.env``` file into environment/running process the same way as the application load variables from environment variables. The application can load or modify the environment variables from the OS and ```.env``` file with a simple function call. [dotenv](https://github.com/bkeepers/dotenv) is a library that originates from [Ruby](https://www.ruby-lang.org/en/) developers (especially the [Ruby on Rails](https://rubyonrails.org/) framework) and has been widely adopted and ported to many programming languages such as [python-dotenv](https://github.com/theskumar/python-dotenv), [dotenv-java](https://github.com/cdimascio/dotenv-java), [Node.js](https://github.com/motdotla/dotenv), etc. The ```.env``` file is a simple text file locates at the root of the project with a key-value pair setting as the following: ``` # DB DB_USER=User DB_PASSWORD=MyPassword # Cloud CLOUD_URL=192.168.1.1 ``` **Caution**: You *should not* share this ```.env``` file to your peers or commit/push it to the version control. You should add the file to the ```.gitignore``` file to avoid adding it to a version control or public repo accidentally. This notebook application demonstrate how to use python-dotenv library to store and read the [Refinitiv Data Platform (RDP) APIs](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis) credentials and configurations, then request the RDP data. ### <a id="whatis_rdp"></a>What is Refinitiv Data Platform (RDP) APIs? The [Refinitiv Data Platform (RDP) APIs](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis) provide various Refinitiv data and content for developers via easy to use Web based API. RDP APIs give developers seamless and holistic access to all of the Refinitiv content such as Historical Pricing, Environmental Social and Governance (ESG), News, Research, etc and commingled with their content, enriching, integrating, and distributing the data through a single interface, delivered wherever they need it. The RDP APIs delivery mechanisms are the following: * Request - Response: RESTful web service (HTTP GET, POST, PUT or DELETE) * Alert: delivery is a mechanism to receive asynchronous updates (alerts) to a subscription. * Bulks: deliver substantial payloads, like the end of day pricing data for the whole venue. * Streaming: deliver real-time delivery of messages. This example project is focusing on the Request-Response: RESTful web service delivery method only. For more detail regarding Refinitiv Data Platform, please see the following APIs resources: - [Quick Start](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/quick-start) page. - [Tutorials](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/tutorials) page. - [RDP APIs: Introduction to the Request-Response API](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/tutorials#introduction-to-the-request-response-api) page. - [RDP APIs: Authorization - All about tokens](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/tutorials#authorization-all-about-tokens) page. ## Importing Libraries The first step is importing all required libraries including the python-dotenv, requests, Pandas, etc. ``` import os from dotenv import load_dotenv import requests import pandas as pd import numpy as np ``` You should save a text file with **filename** `.env` or Environment Variables having the following configurations: ``` # RDP Core Credentials RDP_USER=<Your RDP username> RDP_PASSWORD=<Your RDP password> RDP_APP_KEY=<Your RDP appkey> # RDP Core Endpoints RDP_BASE_URL = https://api.refinitiv.com RDP_AUTH_URL=/auth/oauth2/v1/token RDP_ESG_URL=/data/environmental-social-governance/v2/views/scores-full ``` You can use the python-dotenv library in IPython environment such as Jupyter Notebook or Jupyter Lab by executing the following Magic statements. ``` %load_ext dotenv # Use find_dotenv to locate the file %dotenv ``` By default, it will use find_dotenv to search for a .env file in a current directory location. Please note that the OS/System's environment variables always override ```.env``` configurations by default as the following example. Let's test with the ```USERNAME``` value which will be loaded from your System's environment variables. ``` %load_ext dotenv %dotenv print('User: ', os.getenv('USERNAME')) ``` Next, the notebook application uses ```os.getenv``` statement to get RDP APIs Auth service endpoint and user's RDP credentials configurations from environment. ``` # Get RDP Token service information from Environment Variables base_URL = os.getenv('RDP_BASE_URL') auth_endpoint = base_URL + os.getenv('RDP_AUTH_URL') # Get RDP Credentials information from Environment Variables username = os.getenv('RDP_USER') password = os.getenv('RDP_PASSWORD') app_key = os.getenv('RDP_APP_KEY') ``` Refinitiv Data Platform entitlement check is based on OAuth 2.0 specification. The first step of an application workflow is to get a token from RDP Auth Service, which will allow access to the protected resource, i.e. data REST API's. We create the RDP Auth Service reqeust message with additional variables in the next step. ``` # RDP Auth Services request message variables client_secret = '' scope = 'trapi' auth_obj = None # -- Init and Authenticate Session auth_request_msg = { 'username': username , 'password': password , 'grant_type': "password", 'scope': scope, 'takeExclusiveSignOnControl': "true" } ``` Now notebook is ready to send the HTTP request message with the *requests* library. It keeps the response JSON message which contains the RDP Access Token information in the *auth_obj* variable. ``` # Authentication with RDP Auth Service try: response = requests.post(auth_endpoint, headers = {'Accept':'application/json'}, data = auth_request_msg, auth = (app_key, client_secret)) except Exception as exp: print('Caught exception: %s' % str(exp)) if response.status_code == 200: # HTTP Status 'OK' print('Authentication success') auth_obj = response.json() else: print('RDP authentication result failure: %s %s' % (response.status_code, response.reason)) print('Text: %s' % (response.text)) ``` After the application received the Access Token (an authorization token) from RDP Auth Service, all subsequent REST API calls will use this token to get the data. The application needs to input Access Token via *Authorization* HTTP request message header as shown below. - Header: * Authorization = ```Bearer <RDP Access Token>``` Please notice *the space* between the ```Bearer``` and ```RDP Access Token``` values. The next step is requesting ESG (Environmental, Social, and Governance) data from RDP. We use the ESG scores-full API endpoint which provides full coverage of Refinitiv's proprietary ESG Scores with full history for consumers as an example API. We get the RDP ESG Service API endpoint from a ```.env``` file. ``` # Get RDP Token service information from Environment Variables esg_url = base_URL + os.getenv('RDP_ESG_URL') # ESG Score Full request messages variables universe = 'TSLA.O' payload = {'universe': universe} esg_object = None # Request data for ESG Score Full Service try: response = requests.get(esg_url, headers={'Authorization': 'Bearer {}'.format(auth_obj['access_token'])}, params = payload) except Exception as exp: print('Caught exception: %s' % str(exp)) if response.status_code == 200: # HTTP Status 'OK' print('Receive ESG Data from RDP APIs success') #print(response.json()) esg_object=response.json() else: print('RDP APIs: ESG data request failure: %s %s' % (response.status_code, response.reason)) print('Text: %s' % (response.text)) ``` Once the we receive ESG Data from RDP, we can convert the data from JSON object to a Pandas Dataframe by the following steps: 1. Gets the data and column name from JSON object and then re-constructs it as a new map object. 2. Converts the JSON's data field to the numpy array. 3. Create a new Pandas Dataframe from the numpy data array and headers map. ``` headers=esg_object['headers'] #Get column headers/titles using lambda titles=map(lambda header:header['title'], headers) dataArray=np.array(esg_object['data']) df=pd.DataFrame(data=dataArray,columns=titles) df.head() ``` ## Plotting Graph Then we can plot a graph of the ESG Dataframe object using [matplotlib library](https://matplotlib.org/). ``` # Import matplotlib from matplotlib import pyplot as plt ``` The ESG Data from RDP contains a lot of information, so we will create a new Dataframe object from the original Dataframe to compare only *ESG Score*, *ESG Combined Score* and *ESG Controversies Score* fields. ``` df_plot=pd.DataFrame(df,columns=['Instrument','Period End Date','ESG Score','ESG Combined Score','ESG Controversies Score']) df_plot.head() ``` The data for the Y-axis is the *Period End Date* field and the X-axis is the ESG scores fields. We want to display only the year (eg "2017", "2016") therefore we reformat the data in "Period End Date" column using below codes. ``` df_plot['Period End Date']= df_plot['Period End Date'].str.split('-').str[0] df_plot.head(2) ``` Then sort data as ascending order. ``` df_plot.sort_values('Period End Date',ascending=True,inplace=True) # Plotting a Graph fig = plt.figure() plt.ticklabel_format(style = 'plain') plt.title('%s ESG Data' % (universe), color='black',fontsize='x-large') ax = fig.gca() df_plot.plot(kind='line', ax = fig.gca(),x='Period End Date', y=['ESG Score','ESG Combined Score','ESG Controversies Score'],figsize=(14,7) ) plt.show() ``` ## Conclusion The above code shows that you do not need to change the code if the RDP credentials or service endpoint is changed (example update the API version). We can just update the configurations in a ```.env``` file (or System environment variables) and re-run the application.
github_jupyter
# Training a Custom TensorFlow.js Audio Model In this notebook, we show how to train a custom audio model based on the model topology of the [TensorFlow.js Speech Commands model](https://www.npmjs.com/package/@tensorflow-models/speech-commands). The training is done in Python by using a set of audio examples stored as .wav files. The trained model is convertible to the [TensorFlow.js LayersModel](https://js.tensorflow.org/api/latest/#loadLayersModel) format for inference and further fine-tuning in the browser. It may also be converted to the [TFLite](https://www.tensorflow.org/lite) format for inference on mobile devices. This example uses a small subset of the [Speech Commands v0.02](https://arxiv.org/abs/1804.03209) dataset, and builds a model that detects two English words ("yes" and "no") against background noises. But the methodology demonstrated here is general and can be applied to other sounds, as long as they are stored in the same .wav file format as in this example. ## Data format The training procedure in this notebook makes the following assumption about the raw audio data: 1. The root data directory contains a number of folders. The name of each folder is the name of the audio class. You can select any subset of the folders (i.e., classes) to train the model on. 2. Within each folder, there are a number of .wav files. Each .wav file corresponds to an example. Each .wav file is mono (single-channel) and has the typical pulse-code modulation (PCM) encoding. The duration of each wave file should be 1 second or slightly longer. 3. There can be a special folder called "_background_noise_" that contains .wav files for audio samples that fall into the background noise class. Each of these .wav files can be much longer than 1 second in duration. This notebook contains code that extracts 1-second snippets from these .wav files The Speech Commands v0.3 dataset used in this notebook meets these data format requirements. ``` !pip install librosa tensorflowjs import glob import json import os import random import librosa import matplotlib.pyplot as plt import numpy as np from scipy import signal from scipy.io import wavfile import tensorflow as tf import tensorflowjs as tfjs import tqdm print(tf.__version__) print(tfjs.__version__) # Download the TensorFlow.js Speech Commands model and the associated # preprocesssing model. !mkdir -p /tmp/tfjs-sc-model !curl -o /tmp/tfjs-sc-model/metadata.json -fsSL https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/v0.3/browser_fft/18w/metadata.json !curl -o /tmp/tfjs-sc-model/model.json -fsSL https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/v0.3/browser_fft/18w/model.json !curl -o /tmp/tfjs-sc-model/group1-shard1of2 -fSsL https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/v0.3/browser_fft/18w/group1-shard1of2 !curl -o /tmp/tfjs-sc-model/group1-shard2of2 -fsSL https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/v0.3/browser_fft/18w/group1-shard2of2 !curl -o /tmp/tfjs-sc-model/sc_preproc_model.tar.gz -fSsL https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/conversion/sc_preproc_model.tar.gz !cd /tmp/tfjs-sc-model/ && tar xzvf sc_preproc_model.tar.gz # Download Speech Commands v0.02 dataset. The dataset contains 30+ word and # sound categories, but we will only use a subset of them !mkdir -p /tmp/speech_commands_v0.02 !curl -o /tmp/speech_commands_v0.02/speech_commands_v0.02.tar.gz -fSsL http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz !cd /tmp/speech_commands_v0.02 && tar xzf speech_commands_v0.02.tar.gz # Load the preprocessing model, which transforms audio waveform into # spectrograms (2D image-like representation of sound). # This preprocessing model replicates WebAudio's AnalyzerNode.getFloatFrequencyData # (https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getFloatFrequencyData). # It performs short-time Fourier transform (STFT) using a length-2048 Blackman # window. It opeartes on mono audio at the 44100-Hz sample rate. preproc_model_path = '/tmp/tfjs-sc-model/sc_preproc_model' preproc_model = tf.keras.models.load_model(preproc_model_path) preproc_model.summary() preproc_model.input_shape # Create some constants to be used later. # Target sampling rate. It is required by the audio preprocessing model. TARGET_SAMPLE_RATE = 44100 # The specific audio tensor length expected by the preprocessing model. EXPECTED_WAVEFORM_LEN = preproc_model.input_shape[-1] # Where the Speech Commands v0.02 dataset has been downloaded. DATA_ROOT = "/tmp/speech_commands_v0.02" WORDS = ("_background_noise_snippets_", "no", "yes") # Unlike word examples, the noise samples in the Speech Commands v0.02 dataset # are not divided into 1-second snippets. Instead, they are stored as longer # recordings. Therefore we need to cut them up in to 1-second snippet .wav # files. noise_wav_paths = glob.glob(os.path.join(DATA_ROOT, "_background_noise_", "*.wav")) snippets_dir = os.path.join(DATA_ROOT, "_background_noise_snippets_") os.makedirs(snippets_dir, exist_ok=True) def extract_snippets(wav_path, snippet_duration_sec=1.0): basename = os.path.basename(os.path.splitext(wav_path)[0]) sample_rate, xs = wavfile.read(wav_path) assert xs.dtype == np.int16 n_samples_per_snippet = int(snippet_duration_sec * sample_rate) i = 0 while i + n_samples_per_snippet < len(xs): snippet_wav_path = os.path.join(snippets_dir, "%s_%.5d.wav" % (basename, i)) snippet = xs[i : i + n_samples_per_snippet].astype(np.int16) wavfile.write(snippet_wav_path, sample_rate, snippet) i += n_samples_per_snippet for noise_wav_path in noise_wav_paths: print("Extracting snippets from %s..." % noise_wav_path) extract_snippets(noise_wav_path, snippet_duration_sec=1.0) def resample_wavs(dir_path, target_sample_rate=44100): """Resample the .wav files in an input directory to given sampling rate. The resampled waveforms are written to .wav files in the same directory with file names that ends in "_44100hz.wav". 44100 Hz is the sample rate required by the preprocessing model. It is also the most widely supported sample rate among web browsers and mobile devices. For example, see: https://developer.mozilla.org/en-US/docs/Web/API/AudioContextOptions/sampleRate https://developer.android.com/ndk/guides/audio/sampling-audio Args: dir_path: Path to a directory that contains .wav files. target_sapmle_rate: Target sampling rate in Hz. """ wav_paths = glob.glob(os.path.join(dir_path, "*.wav")) resampled_suffix = "_%shz.wav" % target_sample_rate for i, wav_path in tqdm.tqdm(enumerate(wav_paths)): if wav_path.endswith(resampled_suffix): continue sample_rate, xs = wavfile.read(wav_path) xs = xs.astype(np.float32) xs = librosa.resample(xs, sample_rate, TARGET_SAMPLE_RATE).astype(np.int16) resampled_path = os.path.splitext(wav_path)[0] + resampled_suffix wavfile.write(resampled_path, target_sample_rate, xs) for word in WORDS: word_dir = os.path.join(DATA_ROOT, word) assert os.path.isdir(word_dir) resample_wavs(word_dir, target_sample_rate=TARGET_SAMPLE_RATE) @tf.function def read_wav(filepath): file_contents = tf.io.read_file(filepath) return tf.expand_dims(tf.squeeze(tf.audio.decode_wav( file_contents, desired_channels=-1, desired_samples=TARGET_SAMPLE_RATE).audio, axis=-1), 0) @tf.function def filter_by_waveform_length(waveform, label): return tf.size(waveform) > EXPECTED_WAVEFORM_LEN @tf.function def crop_and_convert_to_spectrogram(waveform, label): cropped = tf.slice(waveform, begin=[0, 0], size=[1, EXPECTED_WAVEFORM_LEN]) return tf.squeeze(preproc_model(cropped), axis=0), label @tf.function def spectrogram_elements_finite(spectrogram, label): return tf.math.reduce_all(tf.math.is_finite(spectrogram)) def get_dataset(input_wav_paths, labels): """Get a tf.data.Dataset given input .wav files and their labels. The returned dataset emits 2-tuples of `(spectrogram, label)`, wherein - `spectrogram` is a tensor of dtype tf.float32 and shape [43, 232, 1]. It is z-normalized (i.e., have a mean of ~0.0 and variance of ~1.0). - `label` is a tensor of dtype tf.int32 and shape [] (scalar). Args: input_wav_paths: Input audio .wav file paths as a list of string. labels: integer labels (class indices) of the input .wav files. Must have the same lengh as `input_wav_paths`. Returns: A tf.data.Dataset object as described above. """ ds = tf.data.Dataset.from_tensor_slices(input_wav_paths) # Read audio waveform from the .wav files. ds = ds.map(read_wav) ds = tf.data.Dataset.zip((ds, tf.data.Dataset.from_tensor_slices(labels))) # Keep only the waveforms longer than `EXPECTED_WAVEFORM_LEN`. ds = ds.filter(filter_by_waveform_length) # Crop the waveforms to `EXPECTED_WAVEFORM_LEN` and convert them to # spectrograms using the preprocessing layer. ds = ds.map(crop_and_convert_to_spectrogram) # Discard examples that contain infinite or NaN elements. ds = ds.filter(spectrogram_elements_finite) return ds input_wav_paths_and_labels = [] for i, word in enumerate(WORDS): wav_paths = glob.glob(os.path.join(DATA_ROOT, word, "*_%shz.wav" % TARGET_SAMPLE_RATE)) print("Found %d examples for class %s" % (len(wav_paths), word)) labels = [i] * len(wav_paths) input_wav_paths_and_labels.extend(zip(wav_paths, labels)) random.shuffle(input_wav_paths_and_labels) input_wav_paths, labels = ([t[0] for t in input_wav_paths_and_labels], [t[1] for t in input_wav_paths_and_labels]) dataset = get_dataset(input_wav_paths, labels) # Show some example spectrograms for inspection. fig = plt.figure(figsize=(40, 100)) dataset_iter = iter(dataset) num_spectrograms_to_show = 10 for i in range(num_spectrograms_to_show): ax = fig.add_subplot(1, num_spectrograms_to_show, i + 1) spectrogram, label = next(dataset_iter) spectrogram = spectrogram.numpy() label = label.numpy() plt.imshow(np.flipud(np.squeeze(spectrogram, -1).T), aspect=0.2) ax.set_title("Example of \"%s\"" % WORDS[label]) ax.set_xlabel("Time frame #") if i == 0: ax.set_ylabel("Frequency bin #") # The amount of data we have is relatively small. It fits into typical host RAM # or GPU memory. For better training performance, we preload the data and # put it into numpy arrays: # - xs: The audio features (normalized spectrograms). # - ys: The labels (class indices). print( "Loading dataset and converting data to numpy arrays. " "This may take a few minutes...") xs_and_ys = list(dataset) xs = np.stack([item[0] for item in xs_and_ys]) ys = np.stack([item[1] for item in xs_and_ys]) print("Done.") tfjs_model_json_path = '/tmp/tfjs-sc-model/model.json' # Load the Speech Commands model. Weights are loaded along with the topology, # since we train the model from scratch. Instead, we will perform transfer # learning based on the model. orig_model = tfjs.converters.load_keras_model(tfjs_model_json_path, load_weights=True) # Remove the top Dense layer and add a new Dense layer of which the output # size fits the number of sound classes we care about. model = tf.keras.Sequential(name="TransferLearnedModel") for layer in orig_model.layers[:-1]: model.add(layer) model.add(tf.keras.layers.Dense(units=len(WORDS), activation="softmax")) # Freeze all but the last layer of the model. The last layer will be fine-tuned # during transfer learning. for layer in model.layers[:-1]: layer.trainable = False model.compile(optimizer="sgd", loss="sparse_categorical_crossentropy", metrics=["acc"]) model.summary() # Train the model. model.fit(xs, ys, batch_size=256, validation_split=0.3, shuffle=True, epochs=50) # Convert the model to TensorFlow.js Layers model format. tfjs_model_dir = "/tmp/tfjs-model" tfjs.converters.save_keras_model(model, tfjs_model_dir) # Create the metadata.json file. metadata = {"words": ["_background_noise_"] + WORDS[1:], "frameSize": model.input_shape[-2]} with open(os.path.join(tfjs_model_dir, "metadata.json"), "w") as f: json.dump(metadata, f) !ls -lh /tmp/tfjs_model ``` To deploy this model to the web, you can use the [speech-commands NPM package](https://www.npmjs.com/package/@tensorflow-models/speech-commands). The model.json and metadata.json should be hosted together with the two weights (.bin) files in the same HTTP/HTTPS directory. Then the custom model can be loaded in JavaScript with: ```js import * as tf from '@tensorflow/tfjs'; import * as speechCommands from '@tensorflow-models/speech-commands'; const recognizer = speechCommands.create( 'BROWSER_FFT', null, 'http://test.com/my-audio-model/model.json', // URL to the custom model's model.json 'http://test.com/my-audio-model/metadata.json' // URL to the custom model's metadata.json ); ``` ``` # Convert the model to TFLite. # We need to combine the preprocessing model and the newly trained 3-class model # so that the resultant model will be able to preform STFT and spectrogram # calculation on mobile devices (i.e., without web browser's WebAudio). combined_model = tf.keras.Sequential(name='CombinedModel') combined_model.add(preproc_model) combined_model.add(model) combined_model.build([None, EXPECTED_WAVEFORM_LEN]) combined_model.summary() tflite_output_path = '/tmp/tfjs-sc-model/combined_model.tflite' converter = tf.lite.TFLiteConverter.from_keras_model(combined_model) converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS ] with open(tflite_output_path, 'wb') as f: f.write(converter.convert()) print("Saved tflite file at: %s" % tflite_output_path) ```
github_jupyter
``` # designed to be run after 03-clinical_variables_final. this notebook does some data cleaning/processing. run before -___ notebook. ## cleans many aspects of the raw clinical variables. ## collapses and formats all of the various categorical variables into discrete variables as well. import pandas as pd import matplotlib.pyplot as plt import os from pathlib import Path import seaborn as sns import numpy as np import glob from sklearn.externals.joblib import Memory memory = Memory(cachedir='/tmp', verbose=0) #@memory.cache above any def fxn. %matplotlib inline plt.style.use('ggplot') from notebook.services.config import ConfigManager cm = ConfigManager() cm.update('livereveal', { 'width': 1024, 'height': 768, 'scroll': True, }) %load_ext autotime #patients of interest from rotation_cohort_generation from parameters import final_pt_df_v, date, repository_path #patients of interest from rotation_cohort_generation final_pt_df2 = final_pt_df_v del(final_pt_df_v) patients= list(final_pt_df2['subject_id'].unique()) hadm_id= list(final_pt_df2['hadm_id'].unique()) icustay_id= list(final_pt_df2['icustay_id'].unique()) icustay_id= [int(x) for x in icustay_id] final_pt_df2['final_bin'].value_counts() ``` # extracting clinical data for our patients ## IMPORTANT, USE THIS TO TUNE TIMEWINDOW OF EXTRACTION AND FOLDER TO SAVE IN #NOTE ON MY DF NAMING CONVENTION: origionally when I coded this workbook, it was for 72 hour timewindows, so every dataframe had _72 at the end. this was changed on 6/5/19 and was made more generalizable by finding name of each corresponding df in the df list and using this variable. ``` from parameters import lower_window, upper_window, folder, date, time_col, time_var, patient_df, save_boolean ``` ### begin pipeline: # changing my code structure to be a dictionary of dataframes ``` #folder to save files to: save_path= str(repository_path)+'/data/cleaned/' #folder=None def save_df(df, df_name='default', save_path=save_path, add_subfolder=False): #uses the date and supplied df name and saves to the savepath specified above. if df_name == 'default': df_name= "%s"%(df) address=save_path+'%s/'%(folder) if not os.path.exists(address): print(address) os.makedirs(address) pd.DataFrame(df).to_csv(Path(address+'%s_%s_prepped.csv' %(date, df_name))) save_path+'%s/'%(folder) ##folder with all clinical variable csv's allFiles = glob.glob(str(repository_path)+ '/data/raw/%s/'%(folder) + "{}_*.csv".format(date)) allFiles #making a dictionary of all my dataframes for easier cycling through df_list=[] for element in allFiles: df_list.append(element.split('{}_'.format(date))[1].split('.csv')[0]) #making an list of all my dataframes in order they appear in file dfs = {} i=0 for name in df_list: dfs[name] = pd.read_csv(allFiles[i], index_col=0) i+=1 df_list #assigning the appropriate name to each df in a flexible way indices = [i for i, s in enumerate(df_list) if 'bg' in s] bg_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'cancer' in s] cancer_elix_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'uti' in s] uti_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'vent' in s] vent_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'vitals' in s] vitals_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'vaso' in s] vaso_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'pt_info' in s] pt_info_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'gcs' in s] gcs_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'sum_elix' in s] sum_elix_df = df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'sofa' in s] sofa_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'weight' in s] weight_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'labs' in s] labs_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'height' in s] height_df= df_list[indices[0]] indices = [i for i, s in enumerate(df_list) if 'rrt' in s] rrt_df= df_list[indices[0]] #adding a t_0 to each df that doesn't currently have it for element in df_list: #print(element,':',list(dfs[element])) if ('t_0' in list(dfs[element]))==False and 'icustay_id' in list(dfs[element]) : #print("true") dfs[element]= pd.merge(dfs[element], final_pt_df2[['icustay_id','t_0']], how='left') elif ('t_0' in list(dfs[element]))==False and 'hadm_id' in list(dfs[element]) : #print("true") dfs[element]= pd.merge(dfs[element], final_pt_df2[['hadm_id','t_0']], how='left') else: print("false") for element in df_list: print(element,':',list(dfs[element])) from parameters import time_var, value_fill, delta_fill, uom_fill def yn_convert(df, #df in format where each row corresponds to a test, and a patient can have many rows label_fill, # value that will be filled to na's pt= final_pt_df2, time_var=time_var,#'t_0', # value_fill=value_fill,#0, delta_fill=delta_fill,# pd.to_timedelta('0 days'), uom_fill=uom_fill):#'y/n'): """ description: collapses (binarizes) a dataframe where each row corresponds to a test, and a patient can have many rows -> 1 row per patient where value is binary variable yes or no a patient has any value within the timewindow (specified in data collection). said a different way, for patient this fxn collapses values down to does pt have a non NA value in the clinical time window y/n? label_fill: the variable name in the label column of the specified dataframe that will considered for y/n value within timewindow. if any non NA value is present it will be considered positive. pt: the by patient spreadsheet be be used to supply patient information. time_var: the variable used to create the time window of interest. value_fill: the variable value that missing values will be filled if the value is not present (default =0) in the origional dataset delta_fill: the time delta value that will be filled in if a patient doesn't have any instances of the label_fill. uom_fill: fills in the unit of measurement to this for missing values. returns a flat 1 row per icustay_id of 1 or 0 if any value was present for the patient. """ yn_df = pd.merge(pt[['icustay_id', time_var]], df[['icustay_id','value','label','uom','delta']], left_on= 'icustay_id', right_on= 'icustay_id', how='left') #merging all icustay_id's with time_var, where value,label,uom, and delta are nan's if no value exists for that icustay. #the idea is that if any value exists then it is pos. yn_df['value']= yn_df['value'].fillna(value_fill) #converts na to 0 in above na rows. yn_df.loc[yn_df.loc[:,'value']!=value_fill, 'value']= 1 #squashes all other values into a binary 1 = yes yn_df['delta']= yn_df['delta'].fillna(delta_fill) yn_df['delta']= pd.to_timedelta(yn_df['delta']) #filling in the time delta to time =0 for filled rows yn_df['uom']= yn_df['uom'].fillna(uom_fill) yn_df.loc[yn_df.loc[:,'uom']!=uom_fill, 'uom']= uom_fill yn_df['label']= yn_df['label'].fillna(label_fill) ##this is new as of 12-12-19L i think i wasn't truely converting to 1row per icustay id by not droping duplicates filtered on value first (desc) then delta (asc) yn_df= yn_df.sort_values(['value','delta'], ascending=[False, True]).drop_duplicates(subset='icustay_id',keep='first') return(yn_df) ``` ## vaso dose ``` # #renaming starttime to charttime and dropping endtime dfs[vaso_df]= dfs[vaso_df].rename( columns={'starttime':'charttime','label':'vaso_type'}) len(dfs[vaso_df]) dfs[vaso_df].head() #removing units/hour because that is a different use of vasopressin dfs[vaso_df] = dfs[vaso_df].loc[dfs[vaso_df].loc[:,'rate_uom']!= 'units/hour',:] dfs[vaso_df] = dfs[vaso_df].loc[dfs[vaso_df].loc[:,'rate_uom']!= 'Uhr',:] len(dfs[vaso_df]) dfs[vaso_df]['rate_uom'].unique() ``` #### removing outliers/extreme values ``` # Use transform to add a column back to the orig df from a groupby aggregation, transform returns a Series with its index aligned to the orig df: def vaso_outlier_removal(df): test_group=(dfs[vaso_df][['vaso_rate','rate_uom','amount_uom','vaso_type']]#.groupby('vaso_type', as_index=False) .groupby(['vaso_type','rate_uom']) ) dfs[vaso_df]['std']=test_group.transform(lambda x : x.std()) dfs[vaso_df]['mean']=test_group.transform(lambda x : x.mean()) normal_high_value= pd.DataFrame({ 'vaso_type' : ['dobutamine','dopamine','epinephrine','norepinephrine','vasopressin','phenylephrine'], 'high_value': [40, 20, 0.5, 1, 0.1, 2] #highest values one might expect to see in a clinic, ie above this is likely erroneous }) #found from literature, see notes dfs[vaso_df] = pd.merge(dfs[vaso_df], normal_high_value, left_on='vaso_type', right_on='vaso_type') vaso_dose_72_rmout =(dfs[vaso_df][ ~((dfs[vaso_df]['vaso_rate'] > dfs[vaso_df]['high_value']) & ((dfs[vaso_df]['vaso_rate']-dfs[vaso_df]['mean'])>= (3*dfs[vaso_df]['std']))) ]) #ie vaso_dose_72_rmout is a dataframe of all rows that excludes rows where vaso rate > literature high value and where vaso_rate >3sd from teh mean return(vaso_dose_72_rmout) dfs[vaso_df]= vaso_outlier_removal(dfs[vaso_df]) len(dfs[vaso_df]) #52976 ->49340 dfs[vaso_df]['vaso_type'].unique() #standardizing names, dropping unneeded columns for analysis dfs[vaso_df]= dfs[vaso_df].drop(['vaso_amount', 'amount_uom','std','mean','high_value'], axis=1) dfs[vaso_df]= dfs[vaso_df].rename(index=str, columns={'vaso_rate': 'value', 'rate_uom':'uom','vaso_type':'label'}) dfs[vaso_df]['label'].unique() dfs[vaso_df].head() epinephrine_df= dfs[vaso_df][dfs[vaso_df]['label']=='epinephrine'] norepinephrine_df= dfs[vaso_df][dfs[vaso_df]['label']=='norepinephrine'] phenylephrine_df= dfs[vaso_df][dfs[vaso_df]['label']=='phenylephrine'] vasopressin_df= dfs[vaso_df][dfs[vaso_df]['label']=='vasopressin'] dopamine_df= dfs[vaso_df][dfs[vaso_df]['label']=='dopamine'] dobutamine_df= dfs[vaso_df][dfs[vaso_df]['label']=='dobutamine'] #making a all vasoactive all_vaso=pd.concat([epinephrine_df, norepinephrine_df,phenylephrine_df, vasopressin_df,dopamine_df,dobutamine_df ], sort=False)#.sort_values(['icustay_id','delta','label','source'], ascending=True) #sorting so that a patient's most positive and earliest cases are kept and everything else droped. all_vaso= all_vaso.sort_values(['value','delta'], ascending=[False, True]).drop_duplicates(subset='icustay_id',keep='first') all_vaso['label']='any_vasoactives' #(could be transfered to a different spdsheet for collapsing values) #y/n convert, seperating out vaso_dose into 6 constitutient dataframes, and for each am collapsing values down to does pt have in time window y/n? epinephrine_df=yn_convert(epinephrine_df, label_fill='epinephrine', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) norepinephrine_df=yn_convert(norepinephrine_df, label_fill='norepinephrine', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) phenylephrine_df=yn_convert(phenylephrine_df, label_fill='phenylephrine', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) vasopressin_df=yn_convert(vasopressin_df, label_fill='vasopressin', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) dopamine_df=yn_convert(dopamine_df, label_fill='dopamine', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) dobutamine_df=yn_convert(dobutamine_df, label_fill='dobutamine', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) all_vaso=yn_convert(all_vaso, label_fill='any_vasoactives', pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) norepinephrine_df[norepinephrine_df['icustay_id']==299654.0] all_vaso['icustay_id'].nunique() #all_vaso=all_vaso.sort_values(['value','delta'], ascending=[False, True]).drop_duplicates(subset='icustay_id',keep='first') len(all_vaso) save_df(all_vaso, df_name='all_vaso') del(all_vaso) save_df(epinephrine_df, df_name='epinephrine') del(epinephrine_df) save_df(norepinephrine_df, df_name='norepinephrine') del(norepinephrine_df) save_df(phenylephrine_df, df_name='phenylephrine') del(phenylephrine_df) save_df(vasopressin_df, df_name='vasopressin') del(vasopressin_df) save_df(dopamine_df, df_name='dopamine') del(dopamine_df) save_df(dobutamine_df, df_name='dobutamine') del(dobutamine_df) del(dfs[vaso_df]) ``` ## ELIX ``` #convert cancer elix to y/n: dfs[cancer_elix_df]= yn_convert(dfs[cancer_elix_df], label_fill=0, pt= final_pt_df2, value_fill=0, delta_fill=0, uom_fill='y/n', time_var=time_var) save_df(dfs[cancer_elix_df], df_name='cancer_elix') del(dfs[cancer_elix_df]) save_df(dfs[sum_elix_df], 'sum_elix') del(dfs[sum_elix_df]) ``` ## vitals - ``` dfs[vitals_df].head() dfs[vitals_df].loc[:,'vitalid'].unique() dfs[bg_df].loc[dfs[bg_df].loc[:,'label']=='fio2_chartevents',:]#unique() dfs[vitals_df] = dfs[vitals_df].rename(index=str, columns={"valueuom":"uom","vitalid":'label', 'valuenum':'value'}) #change valueom to uom dfs[vitals_df] = dfs[vitals_df].loc[dfs[vitals_df]['label'].notnull(),:]#.count() #removing null values dfs[vitals_df].loc[dfs[vitals_df].loc[:,'uom']=='BPM','uom']='bpm' #overall the values are extremely similar and are likely the same thing #i will combine them. dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='RespRate') & (dfs[vitals_df]['uom']=='bpm'),'uom']='insp/min' dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='TempC') & (dfs[vitals_df]['uom']=='?C'),'uom']='Deg. C' dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='TempF') & (dfs[vitals_df]['uom']=='Deg. F'),'uom']='Deg. C' dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='TempF') & (dfs[vitals_df]['uom']=='?F'),'uom']='Deg. C' dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='TempF'),'label']='temperature' dfs[vitals_df].loc[ (dfs[vitals_df]['label']=='TempC'),'label']='temperature' ``` - glucose max - glucose min - diasBP min - heartrate min - meanart pressure min - RespRate min - SYSbp min - TEMPC min ### most likely erroneous value removal ``` #erroneous value cutoff summary ## setting a conservative threshold for erroneous values to not skew my data. (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'icustay_id']==228393.0) & (dfs[vitals_df].loc[:,'label']=='Glucose') & (dfs[vitals_df].loc[:,'value']>99999), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='Glucose') & (dfs[vitals_df].loc[:,'value']>99998), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='Glucose') & (dfs[vitals_df].loc[:,'value']<15), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='DiasBP') & (dfs[vitals_df].loc[:,'value']<15), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='HeartRate') & (dfs[vitals_df].loc[:,'value'].between(1,29)), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='RespRate') & (dfs[vitals_df].loc[:,'value']<4), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='SysBP') & (dfs[vitals_df].loc[:,'value']<40), 'value'])=np.nan (dfs[vitals_df].loc[(dfs[vitals_df].loc[:,'label']=='TempC') & (dfs[vitals_df].loc[:,'value']<28), 'value'])=np.nan dfs[vitals_df] = dfs[vitals_df].loc[dfs[vitals_df]['value'].notnull(),:]#.count() ### saving spo2 for later use in bloodgas 11/25/19 spo2=dfs[vitals_df][dfs[vitals_df]['label']=='SpO2'].copy() ### seperating fio2 out fio2_chart_df = dfs[vitals_df].loc[dfs[vitals_df].loc[:,'label']=='fio2_chartevents',:]#unique() dfs[vitals_df]= dfs[vitals_df].loc[dfs[vitals_df].loc[:,'label']!='fio2_chartevents',:] save_df(dfs[vitals_df], 'vitals') del(dfs[vitals_df]) ``` # labs - ``` dfs[labs_df].head(10) dfs[labs_df]= dfs[labs_df].rename( columns={'valuenum':'value'}) #changing valuenum to value dfs[labs_df].groupby('label')['uom'].value_counts() #looks good ``` ### most likely erroneous value removal ``` #summary value removal- was explored and coded adhoc, difficult to automate (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==261887) & (dfs[labs_df].loc[:,'label']=='CHLORIDE') & (dfs[labs_df].loc[:,'value']==3.4),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==236290) & (dfs[labs_df].loc[:,'label']=='CHLORIDE') & (dfs[labs_df].loc[:,'value']==11.0),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==292769) & (dfs[labs_df].loc[:,'label']=='INR') & (dfs[labs_df].loc[:,'value']==28.1),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==298457) & (dfs[labs_df].loc[:,'label']=='INR') & (dfs[labs_df].loc[:,'value']==48.8),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==234174) & (dfs[labs_df].loc[:,'label']=='INR') & (dfs[labs_df].loc[:,'value']==48.7),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==290264) & (dfs[labs_df].loc[:,'label']=='INR') & (dfs[labs_df].loc[:,'value']==42.0),'value'])=np.nan (dfs[labs_df].loc[ (dfs[labs_df].loc[:,'icustay_id']==290264) & (dfs[labs_df].loc[:,'label']=='INR') & (dfs[labs_df].loc[:,'value']==22.8),'value'])=np.nan dfs[labs_df]= dfs[labs_df].loc[dfs[labs_df].loc[:,'value'].notnull(),:] #removing null values dfs[labs_df].head() #removing unwanted values unwanted_values= ['HEMATOCRIT','ANION GAP','PT','ALBUMIN'] dfs[labs_df]= dfs[labs_df].loc[~dfs[labs_df].loc[:,'label'].isin(unwanted_values),:] ``` # factorizing bands start * converting bands into a categorical variable since it is very sparse ``` #df in format where each row corresponds to a test, and a patient can have many rows def yn_convert_band(df, label_fill="absent", threshold=10, pt= final_pt_df2, time_var='t_0', value_fill=9999, delta_fill=pd.to_timedelta('0 days'), uom_fill='y/n'): """ binarizing bands value since it's extremely sparse. Wrote a new function instead of adjusting yn_convert a while back. on my todo to remove this and add functionality to regular yn_conmert function. """ yn_df = pd.merge(pt[['icustay_id','hadm_id','subject_id', time_var]], df[['icustay_id','value','label','uom','delta']], left_on= 'icustay_id', right_on= 'icustay_id', how='left') #merging all icustay_id's with time_var, where value,label,uom, and delta are nan's if no value exists for that icustay. #the idea is that if any value exists then it is pos. yn_df['value']= yn_df['value'].fillna(value_fill) #converts na to 0 in above na rows. criteria0=yn_df.loc[:,'value']==value_fill criteria1=pd.to_numeric(yn_df.loc[:,'value'])<=threshold criteria2=pd.to_numeric(yn_df.loc[:,'value'])>threshold yn_df.loc[criteria1, 'value']= "<{}".format(threshold) yn_df.loc[criteria2, 'value']= ">{}".format(threshold) yn_df.loc[criteria0, 'value']= "absent" yn_df['delta']= yn_df['delta'].fillna(delta_fill) yn_df['delta']= pd.to_timedelta(yn_df['delta']) #filling in the time delta to time =0 for filled rows yn_df['uom']= yn_df['uom'].fillna(uom_fill) yn_df.loc[yn_df.loc[:,'uom']!=uom_fill, 'uom']= uom_fill yn_df['label']= yn_df['label'].fillna(label_fill) return(yn_df) band_df=dfs[labs_df][dfs[labs_df]['label']=='BANDS'] max_bands=band_df.loc[band_df.groupby('icustay_id', as_index=False)['value'].idxmax(),:] del(band_df) band_cat=yn_convert_band(df=max_bands, label_fill="BANDS", threshold=10, pt= final_pt_df2, time_var='t_0', value_fill=9999, delta_fill=pd.to_timedelta('0 days'), uom_fill='y/n') #drop bands from lab_df dfs[labs_df]=dfs[labs_df].drop(dfs[labs_df][dfs[labs_df]['label']=='BANDS'].index) ##dropping charttime, may be problematic later. dfs[labs_df]=dfs[labs_df].drop('charttime', axis=1) #appending categorical bands dfs[labs_df]=dfs[labs_df].append(band_cat) dfs[labs_df].loc[dfs[labs_df]['label']=='BANDS','value'].value_counts() # pd.DataFrame(dfs[labs_df]).to_csv(Path( # save_path+'/%s_labs_prepped.csv' %(date))) save_df(dfs[labs_df], 'labs') del(dfs[labs_df]) ``` ## vent category - ``` dfs[vent_df]['icustay_id'].nunique() #13978 patients with someform of vent data. dfs[vent_df]['uom']='mech/O2/none category' dfs[vent_df].head() dfs[vent_df]=dfs[vent_df].rename(index=str, columns={'day':'delta'}) dfs[vent_df]['label']='vent_recieved' dfs[vent_df]['delta']=pd.to_timedelta(dfs[vent_df]['delta'], unit='d') #dfs[vent_df]= dfs[vent_df].drop(columns=['day'], axis=1) #removing day column dfs[vent_df].head() #collapsing into 1 column for N days def vent_day_collapser(x): """ collapsing the ventilation days into a single value. Mech> Oxygen > None. """ if 'Mech' in list(x.unique()): x= 'Mech' elif 'Oxygen' in list(x.unique()): x= 'Oxygen' else: x='None' return(x) #collapsing all days into the worst day. ventcategory_1day_df= dfs[vent_df].copy() ventcategory_1day_df['value']=ventcategory_1day_df.groupby('icustay_id',as_index=False)['value'].transform(vent_day_collapser) ventcategory_1day_df= ventcategory_1day_df.drop_duplicates(['icustay_id','value']).sort_values('icustay_id') # ventcategory_1day_df= ventcategory_1day_df.loc[ventcategory_1day_df.loc[:,'icustay_id'].isin(icustay_id),:] #had icustay ids not in final cohort, fail safe mesure ventcategory_1day_df.head() ventcategory_1day_df['value'].value_counts() save_df(ventcategory_1day_df, 'ventcategory') # will be deleted after pao2:fio2 calc ``` ## weight and height firstday - i explored weightdurations and it had more missing values than weightfirstday, so i will use that. we can revisit this if we need longitudinal weights ``` dfs[weight_df]['uom']='kg' dfs[weight_df].head() #weight column is the conglomerate of weight_admin>weight_daily> weight_echoinhosp> weight_echoprehosp dfs[weight_df]= dfs[weight_df][dfs[weight_df]['weight'].notnull()] dfs[weight_df]= dfs[weight_df][['icustay_id','weight','uom']] dfs[weight_df]['label']= 'weight' dfs[weight_df]=dfs[weight_df].rename(index=str, columns={'weight':'value'}) #adding the assumed first day delta column to standardize all columns dfs[weight_df]['delta']=pd.to_timedelta(0,'days') #adding t_0 dfs[weight_df]= pd.merge(dfs[weight_df], final_pt_df2[['icustay_id',time_var]], left_on='icustay_id', right_on='icustay_id') # pd.DataFrame(dfs[weight_df]).to_csv(Path( # save_path+'/%s_weight_prepped.csv' %(date))) save_df(dfs[weight_df], 'weight') del(dfs[weight_df]) dfs[height_df]['uom']='cm' dfs[height_df]= dfs[height_df][dfs[height_df]['height'].notnull()] dfs[height_df]= dfs[height_df][['icustay_id','height','uom']] dfs[height_df]['label']= 'height' dfs[height_df]=dfs[height_df].rename(index=str, columns={'height':'value'}) #adding the assumed first day delta column to standardize all columns dfs[height_df]['delta']=pd.to_timedelta(0,'days') #adding t_0 dfs[height_df]= pd.merge(dfs[height_df], final_pt_df2[['icustay_id',time_var]], left_on='icustay_id', right_on='icustay_id') #heightfirstday save_df(dfs[height_df], 'height') del(dfs[height_df]) ``` # UTI ``` dfs[uti_df]['value'].unique()#seems good #all uti within clinical timewindow dfs[uti_df]= dfs[uti_df].loc[(dfs[uti_df].loc[:,'value']!='NEG')& dfs[uti_df].loc[:,'value'].notnull(),:] #filter to only pos rows dfs[uti_df]= dfs[uti_df].loc[(dfs[uti_df].loc[:,'value']!='COMPUTER NETWORK FAILURE. TEST NOT RESULTED.')& dfs[uti_df].loc[:,'value'].notnull(),:] #filter to only pos rows dfs[uti_df]= dfs[uti_df].drop_duplicates(subset=['hadm_id','value','charttime']) dfs[uti_df].loc[dfs[uti_df].loc[:,'value'].notnull(),'value']= 1 dfs[uti_df].loc[dfs[uti_df].loc[:,'value'].isna(),'value']= 0 dfs[uti_df].head() def uti_categorizer(uti_df): "useful to get all rows of days with positive values for patients (if multiple pos in a day there will be only 1 row for that day). ie more longitudinal format " #gives the max pos or neg value per day for df_timewindow_perday=uti_df.groupby(['hadm_id','delta'], as_index=False)['value'].agg({'value':'max'}) df_timewindow_perday= pd.merge(df_timewindow_perday,final_pt_df2[['icustay_id','hadm_id', time_var]], left_on='hadm_id', right_on='hadm_id', how='left') df_timewindow_perday=df_timewindow_perday.sort_values(['hadm_id','value','delta'], ascending=[True,False,True]) return(df_timewindow_perday) def yn_uti(uti_df, label): "collapsing longitudinal data into 1 value. will return pos or neg if patient has a positive uti in their stay. one row per icustay_id" df_timewindow_perday=uti_df.groupby(['hadm_id','delta'], as_index=False)['value'].agg({'value':'max'}) first_pos= df_timewindow_perday.drop_duplicates(['hadm_id']) collapsed= pd.merge(final_pt_df2[['hadm_id','icustay_id','subject_id', time_var]],first_pos, left_on='hadm_id', right_on='hadm_id', how='left') collapsed['value']= collapsed['value'].fillna(0) collapsed.loc[collapsed.loc[:,'value']==1,'value']= 'pos' collapsed.loc[collapsed.loc[:,'value']==0,'value']= 'Neg/Not_tested' collapsed['delta']= collapsed['delta'].fillna(pd.Timedelta(1, unit='d')) collapsed['label']= label collapsed['uom']='pos/neg category' return(collapsed) uti_nit_pos= dfs[uti_df][dfs[uti_df]['label']=="Nitrite"] uti_leuk_pos= dfs[uti_df][dfs[uti_df]['label']=="Leukocytes"] leuk_collapsed= yn_uti(uti_leuk_pos, 'leukocyte') nit_collapsed= yn_uti(uti_nit_pos, 'nitrite') save_df(leuk_collapsed, 'leuk') del(leuk_collapsed) save_df(nit_collapsed, 'nit') del(nit_collapsed) del(dfs[uti_df]) ``` # bloodgas ``` dfs[bg_df]= dfs[bg_df].loc[dfs[bg_df]['value'].notnull(),:] dfs[bg_df] = dfs[bg_df].rename(index=str, columns={'valueuom':'uom'}) dfs[bg_df]= dfs[bg_df].loc[~(dfs[bg_df].loc[:,'value']=='.'),:] #may need to remove outliers, haven't done as of 10/22/18 dfs[bg_df].head() ``` ### most likely erroneous value removal the code below manually removes values that are a high likelyhood of being erroneous in a way that doesn't follow great programming practices. on my list of things to improve, but it is currently functional. ``` ##calcium #fixing the calcium errors w/o hard coding (dfs[bg_df].loc[ (dfs[bg_df].loc[:,'icustay_id']==249571) & (dfs[bg_df].loc[:,'label']=='CALCIUM') & (dfs[bg_df].loc[:,'valuenum']==94.00),'valuenum'])=0.94#.where('valuenum'==94.00)) (dfs[bg_df].loc[ (dfs[bg_df].loc[:,'icustay_id']==249571) & (dfs[bg_df].loc[:,'label']=='CALCIUM') & (dfs[bg_df].loc[:,'value']=='094'),'value'])=0.94#.where('valuenum'==94.00)) (dfs[bg_df].loc[ (dfs[bg_df].loc[:,'icustay_id']==219600) & (dfs[bg_df].loc[:,'label']=='CALCIUM') & (dfs[bg_df].loc[:,'valuenum']==97.00),'valuenum'])=0.97#.where('valuenum'==94.00)) (dfs[bg_df].loc[ (dfs[bg_df].loc[:,'icustay_id']==219600) & (dfs[bg_df].loc[:,'label']=='CALCIUM') & (dfs[bg_df].loc[:,'value']=='097'),'value'])=0.97#.where('valuenum'==94.00)) ##min chloride #converting it to a null value without hard coding (dfs[bg_df].loc[(dfs[bg_df].loc[:,'icustay_id']==261887.0) & (dfs[bg_df].loc[:,'label']=='CHLORIDE') & (dfs[bg_df].loc[:,'valuenum']==3.4),'value'])=np.nan #converting it to a null value without hard coding (dfs[bg_df].loc[(dfs[bg_df].loc[:,'icustay_id']==261887.0) & (dfs[bg_df].loc[:,'label']=='CHLORIDE') & (dfs[bg_df].loc[:,'valuenum']==3.4),'valuenum'])=np.nan #changing the values without hard coding. (dfs[bg_df].loc[(dfs[bg_df].loc[:,'icustay_id']==236290.0) & (dfs[bg_df].loc[:,'label']=='CHLORIDE') & (dfs[bg_df].loc[:,'valuenum']==11.0),'valuenum'])=np.nan (dfs[bg_df].loc[(dfs[bg_df].loc[:,'icustay_id']==236290.0) & (dfs[bg_df].loc[:,'label']=='CHLORIDE') & (dfs[bg_df].loc[:,'valuenum']==11.0),'value'])=np.nan #peep changes summary: dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='PEEP')& (dfs[bg_df]['valuenum']>38),'valuenum']=np.nan #remove this or set to 50? #temp changes summary: dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='TEMPERATURE')& (dfs[bg_df]['icustay_id']==253821)& (dfs[bg_df]['valuenum']==18.9), 'value']= np.nan dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='TEMPERATURE')& (dfs[bg_df]['icustay_id']==253821)& (dfs[bg_df]['valuenum']==18.9), 'valuenum']= np.nan dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='TEMPERATURE')& (dfs[bg_df]['icustay_id']==251788)& (dfs[bg_df]['valuenum']==10.0), 'value']= np.nan dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='TEMPERATURE')& (dfs[bg_df]['icustay_id']==251788)& (dfs[bg_df]['valuenum']==10.0), 'valuenum']= np.nan #fio2 changes summary: ##converting a few values to null, thus removing them from the dataset dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='FIO2') & (dfs[bg_df].loc[:,'value']=='0'),'value']=np.nan dfs[bg_df].loc[(dfs[bg_df].loc[:,'label']=='FIO2') & (dfs[bg_df].loc[:,'value']=='-'),'value']=np.nan ##removing all fio2 values between 1-20.9 dfs[bg_df].loc[(dfs[bg_df].loc[:,'label'].isin(['FIO2']))& (dfs[bg_df]['valuenum'].between(1.0,20.9)),'valuenum']=np.nan ##values between 0-1 were found to be ratios, not %, so converting these to % dfs[bg_df].loc[(dfs[bg_df].loc[:,'label'].isin(['FIO2']))& (dfs[bg_df]['valuenum'].between(1.0,20.9)),'valuenum']=np.nan fio2_dec= dfs[bg_df].loc[(dfs[bg_df].loc[:,'label'].isin(['FIO2']))& (dfs[bg_df]['valuenum'].between(0.0,1.0)),'valuenum'] dfs[bg_df].loc[(dfs[bg_df].loc[:,'label'].isin(['FIO2']))& (dfs[bg_df]['valuenum'].between(0.0,1.0)),'valuenum'] = fio2_dec *100 del(fio2_dec) ``` #### removing null values annotated abov ``` dfs[bg_df]= dfs[bg_df].loc[dfs[bg_df]['value'].notnull(),:] ``` ### splitting specimen out for vent vs non-vent bg data ``` #adding specimen tag to filter only arterial samples for vent data. specimen_df= dfs[bg_df].loc[dfs[bg_df].loc[:,'label']=='SPECIMEN',['unique_var','label','value']]#unique() specimen_df=specimen_df.rename(index=str, columns={'value':'specimen'}) specimen_df=specimen_df.loc[specimen_df.loc[:,"specimen"]=='ART',:] dfs[bg_df]= pd.merge(dfs[bg_df],specimen_df[['unique_var','specimen']], left_on='unique_var', right_on='unique_var', how='left') bg_ART_nosummary=dfs[bg_df].loc[dfs[bg_df].loc[:,'specimen']=='ART',:].copy() del(specimen_df) bg_labels=['PH','LACTATE','CALCIUM','TEMPERATURE','POTASSIUM', 'GLUCOSE','HEMOGLOBIN','SODIUM','CHLORIDE','BICARBONATE','FIO2'] bg_vent_labels=['PCO2','PaO2','PO2','PEEP','O2FLOW'] #restricting to tests that were chosen to be analysed based on %missingness and clinical relevance dfs[bg_df]= dfs[bg_df].loc[dfs[bg_df].loc[:,'label'].isin(bg_labels),:] bg_ART_nosummary= bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label'].isin(bg_vent_labels),:] dfs[bg_df].head() bg_col=['subject_id','hadm_id','icustay_id','charttime','delta',time_var,'label','valuenum','uom'] bg_ART_nosummary= bg_ART_nosummary[bg_col] dfs[bg_df]= dfs[bg_df][bg_col] del(bg_col) bg_ART_nosummary['label'].unique() ##quickly investingating o2flow o2_pt= list(dfs[vent_df].loc[dfs[vent_df].loc[:,'value']=='Oxygen','icustay_id'].unique()) #o2_pt= list(ventcategory_1day_df.loc[ventcategory_1day_df.loc[:,'value']=='Oxygen','icustay_id'].unique()) bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label']=='O2FLOW',:] #bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'icustay_id']==217847,:] bg_ART_nosummary.loc[(bg_ART_nosummary.loc[:,'label']=='O2FLOW') & (bg_ART_nosummary.loc[:,'icustay_id'].isin(o2_pt)),:] #dfs[vent_df].loc[dfs[vent_df].loc[:,'icustay_id']==217847,:] #converting O2 to y/n o2_flow_df= bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label']=='O2FLOW',:] o2_flow_df=o2_flow_df.rename(index=str, columns={'valuenum':'value'}) o2_flow_df= yn_convert(o2_flow_df, label_fill='o2_flow', time_var=time_var) o2_flow_df['label']="o2_flow" #fixing label #removing o2_flow from bg_ART bg_ART_nosummary= bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label']!='O2FLOW',:] bg_ART_nosummary= bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label']!='PEEP',:] ``` ## PaO2:FiO2 * PaO2: measurement of oxygen pressure in arterial blood * FiO2: % of oxygen in the air a patient is breathing. in normal air this is 21% oxygen * SpO2: Peripheral capillary oxygen saturation, estimate of the amount of oxygen in the blood. this is % of oxygenated haemoglobin compared to total haemoglobin ***requirements: run vitals, ventilation before this to get spo2 & ventilation category. I would modify the criteria to be more strict: * first isolate patients on mech ventilation: these are only patients we calc P:F for * find PaO2: * if no PaO2: * find SpO2 <=97 --> ~PaO2 * SpO2 to estimate and PaO2 equivalent via the equation used by Knox et al to convert to PaO2-equivalent. * once have all PaO2 and estimated PaO2: * find last measured fio2 between t- 6hours :t, where t= time of PaO2 * impute P:F= 476 for every other icustay_id. * Use P:F as a continuous value unless there is a clear need to bucket, and if so use <100,100-200, 200-300, >300 ##### first isolate patients who had mech or oxygen ventilation during their N hours these are only patients we calc P:F for first, filter pao2 and fio2 to only icustay who have ventilation (pf_ratio_icu) ``` vent_icu=list(ventcategory_1day_df[ventcategory_1day_df['value'].isin(['Mech'])]['icustay_id'].unique()) ``` next isolate the pao2 and fio2 from the bg arterial dataframe. * pao2: all pao2 measurements in cohort -> pao2 measurements for icustay with ventilation * fio2: all fio2 measurements (chartevents) in cohort -> fio2 measurements for icustay with ventilation ``` #using bloodgas fio2_chart_df['delta']=pd.to_timedelta(fio2_chart_df['delta']) fio2_chart_df= fio2_chart_df[fio2_chart_df['value'].notnull()].copy() pao2= bg_ART_nosummary.loc[bg_ART_nosummary.loc[:,'label']=='PaO2',:].copy() pao2.rename(index=str, columns={'valuenum':'value'}, inplace=True) pao2_vent= pao2[pao2.loc[:,'icustay_id'].isin(vent_icu)].copy() pao2_vent['delta']=pd.to_timedelta(pao2_vent['delta']).copy() pao2_vent= pao2_vent[pao2_vent['value'].notnull()] #removing some null rows ``` ##### next: find patients with ventilation but no PaO2 and collect their SpO2 values ``` # pao2_icu: icustay_id for pao2 with vent pao2_icu= list(pao2_vent['icustay_id'].unique()) # find people with ventilation but no PaO2 measured (ie those who need it approximatd) vent_but_no_pao2_icu=set(vent_icu).difference(set(pao2_icu)) ## if on vent but no PaO2, then use SpO2 (if 97 or less) -> estimate PaO2 via equation below spo2_filtered= spo2[(spo2['icustay_id'].isin(vent_but_no_pao2_icu)) & (spo2['value']<=97.0)] ##quick qc output print( "total icustay:", len(icustay_id), '\n', 'mech during their 72 hours of clinical data: ', len(vent_icu), '\n', ' -pao2, +vent: ', pao2_vent['icustay_id'].nunique(), '\n', ' +fio2, +vent: ', fio2_chart_df[fio2_chart_df['icustay_id'].isin(vent_icu)]['icustay_id'].nunique(), '\n', '+ vent, - pao2: ', len(vent_but_no_pao2_icu), '\n', '+fio2, +vent, -pao2: ', fio2_chart_df[fio2_chart_df['icustay_id'].isin(vent_but_no_pao2_icu)]['icustay_id'].nunique(), '\n', ) ``` ##### next: estimate PaO2 using SpO2 for patients who have ventilation but no PaO2 measurement $$\text{Ellis Severinghaus inversion}: PaO2_{estimate} =\sqrt[3]{\frac{1}{2} (-y_N + \sqrt{y_N^2 -h^2})} + \sqrt[3]{\frac{1}{2} (-y_N - \sqrt{y_N^2 -h^2})}$$ $$ \begin{cases} h^2 =-500000 \\ y_N = -23400 * \frac{s}{1-s} \\ \end{cases} $$ * s is the fractional oxygen saturation (0–1) and p is the associated oxygen tension in mm Hg. * qc: when s=0.5, p=26.856 * equation source: http://www.nickalls.org/dick/papers/anes/severinghaus.pdf ``` def Ellis_SpO2(S): """ ellis inversion equation to approximate PaO2 from SpO2. where s is the fractional oxygen saturation (SpO2) (0–1) and p is the associated oxygen tension in mm Hg (PaO2). """ if S >1 and S<100: S=S/100. elif S==1: S=0.9999 elif S>0 and S<1: pass h2= -500000. yn= -23400. * (S/(1.-S)) term1= np.sqrt(np.power(yn,2.) - h2) term2= 0.5*(-yn + term1) term3= 0.5*(-yn - term1) term4= np.sign(term2) * np.abs(term2)**(1/3) term5= np.sign(term3) * np.abs(term3)**(1/3) p= term4+term5 return(p) # approximating Pao2 from SpO2: ## only usable for spo2 values <=97 spo2_filtered= spo2[(spo2['icustay_id'].isin(vent_but_no_pao2_icu)) & (spo2['value']<=97.0)] # run the Ellis_SpO2 to approx PaO2. spo2_filtered.loc[:,'value']= spo2_filtered.value.apply(Ellis_SpO2) #note this produces a false positive SettingWithCopyWarning spo2_filtered.loc[:,'label']='PaO2_estimate' spo2_filtered.loc[:,'uom']='mm Hg estimate' #append the pao2 (for those with ventilation) and new approximated pao2 together pao2_appended=pao2_vent.append(spo2_filtered, sort=False).copy() ``` * once have all PaO2 and estimated PaO2: * find fio2 measured between t- 6hours :t, where t= time of PaO2 * use most recent fio2 measure in this time? ``` #quick time conversion to make sure both in timedelta format pao2_appended['delta']=pd.to_timedelta(pao2_appended['delta']) pao2_appended['charttime']=pd.to_datetime(pao2_appended['charttime']) fio2_chart_df['delta']=pd.to_timedelta(fio2_chart_df['delta']) fio2_chart_df['charttime']=pd.to_datetime(fio2_chart_df['charttime']) fio2_chart_df['label']='fio2' #labeling all PaO2 (both measured and approx) with offset column= the delta time offset by the n hours of time we look back for Fio2 values pao2_appended['offset']=pao2_appended['charttime'] - pd.to_timedelta(6, unit='h') #find most recent in this. #left cartesian product of pao2 and fio2 measurements. pao2_fio2_windowed= pd.merge(pao2_appended, fio2_chart_df[['icustay_id','value','label','charttime','delta']].rename(index=str, columns={'value':'value2','label':'label2','charttime':'charttime2','delta':'delta2'}), left_on='icustay_id', right_on='icustay_id', how='left') ##take this left cartesian product and filter to rows where charttime2 (ie fio2 time) is between t-6:t where t= time at pao2 measurement. #now this should be all Pao2 (real and estimated) and Fio2 combinations that pao2_fio2_windowed= pao2_fio2_windowed[pd.to_datetime(pao2_fio2_windowed['charttime2']).between(pd.to_datetime(pao2_fio2_windowed['offset']),pd.to_datetime(pao2_fio2_windowed['charttime']))] ## grabs the most recent FiO2 value for each associated PaO2 ratio_df= pao2_fio2_windowed.sort_values(['icustay_id','charttime','charttime2'], ascending=[True,True, False]).drop_duplicates(['icustay_id','charttime'],keep='first') ratio_df.loc[ratio_df.loc[:,'value2'].isnull(),'value2']= 21 #impute 21 for FiO2 values that are missing (very few of them) ratio_df['ratio']= ratio_df['value']/(ratio_df['value2']/100) #calculate the ratio ratio_df.loc[ratio_df['charttime2'].isnull(),'charttime2']= ratio_df.loc[ratio_df['charttime2'].isnull(),'charttime'] ratio_df['deltadelta']=pd.to_datetime(ratio_df['charttime'])-pd.to_datetime(ratio_df['charttime2']) #optional qc # ratio_df.head() # ratio_df['ratio'].describe() # ratio_df[['icustay_id','ratio']].groupby('icustay_id')['ratio'].apply(max).describe() ### making a copy of ratio_df, merging in all icustay's that are missing, and imputing datetime and value for them. ratio_df2= ratio_df.copy() # making sure all patients have a value ratio_df2= pd.merge(final_pt_df2[['subject_id','hadm_id','icustay_id']], ratio_df2[['icustay_id', 'ratio','delta','uom','label']].rename(index=str, columns={'ratio':'value'}), left_on='icustay_id',right_on='icustay_id', how='outer') ratio_df2['label']='pao2fio2ratio' ratio_df2['uom']='mm HG:%' ratio_df2.loc[ratio_df2['value'].isnull(),'value']=476 ratio_df2.loc[ratio_df2['delta'].isnull(),'delta']=pd.to_timedelta('0 days') #should match the len(icustay_id) ratio_df2['icustay_id'].nunique() ratio_df2.head() ``` # factorizing pco2 start ``` # yn_convert_band(max_bands, #df in format where each row corresponds to a test, and a patient can have many rows def yn_convert_pco2(df, label_fill="absent", threshold=10, pt= final_pt_df2, time_var='t_0', value_fill=9999, delta_fill=pd.to_timedelta('0 days'), uom_fill='y/n'): yn_df = pd.merge(pt[['icustay_id','hadm_id','subject_id', time_var]], df[['icustay_id','value','label','uom','delta']], left_on= 'icustay_id', right_on= 'icustay_id', how='left') #merging all icustay_id's with time_var, where value,label,uom, and delta are nan's if no value exists for that icustay. #the idea is that if any value exists then it is pos. yn_df['value']= yn_df['value'].fillna(value_fill) #converts na to 0 in above na rows. criteria0=yn_df.loc[:,'value']==value_fill criteria1=pd.to_numeric(yn_df.loc[:,'value'])<=threshold criteria2=pd.to_numeric(yn_df.loc[:,'value'])>threshold yn_df.loc[criteria1, 'value']= "<{}".format(threshold) yn_df.loc[criteria2, 'value']= ">{}".format(threshold) yn_df.loc[criteria0, 'value']= "absent" yn_df['delta']= yn_df['delta'].fillna(delta_fill) yn_df['delta']= pd.to_timedelta(yn_df['delta']) #filling in the time delta to time =0 for filled rows yn_df['uom']= yn_df['uom'].fillna(uom_fill) yn_df.loc[yn_df.loc[:,'uom']!=uom_fill, 'uom']= uom_fill yn_df['label']= yn_df['label'].fillna(label_fill) return(yn_df) bg_ART_nosummary= bg_ART_nosummary.rename( columns={'valuenum':'value'}) #changing valuenum to value pco2_df=bg_ART_nosummary[bg_ART_nosummary['label']=='PCO2'] max_pco2=pco2_df.loc[pco2_df.groupby('icustay_id', as_index=False)['value'].idxmax(),:] del(pco2_df) pco2_cat=yn_convert_pco2(df=max_pco2, label_fill="PCO2", threshold=50, pt= final_pt_df2, time_var='t_0', value_fill=9999, delta_fill=pd.to_timedelta('0 days'), uom_fill='y/n') #drop bands from lab_df bg_ART_nosummary=bg_ART_nosummary.drop(bg_ART_nosummary[bg_ART_nosummary['label']=='PCO2'].index) ##dropping charttime, may be problematic later. 06/13/19 bg_ART_nosummary=bg_ART_nosummary.drop('charttime', axis=1) bg_ART_nosummary=bg_ART_nosummary.append(pco2_cat, sort=True) bg_ART_nosummary.loc[bg_ART_nosummary['label']=='PCO2','value'].value_counts() ``` # factorizing bands end ``` save_df(ratio_df2, 'pfRatio') del( pao2_fio2_windowed,pao2_appended, fio2_chart_df, pao2, pao2_icu ) del( ventcategory_1day_df, dfs[vent_df] ) save_df(dfs[bg_df],'bg_all') #all bloodgas del(dfs[bg_df]) save_df(bg_ART_nosummary,'bg_ART') #only ARTERIAL bloodgas del(bg_ART_nosummary) save_df(o2_flow_df,'o2_flow') #need to investigate this more del(o2_flow_df) ``` # RRT ``` #removing null values dfs[rrt_df] = dfs[rrt_df].loc[dfs[rrt_df]['rrt'].notnull(),:] dfs[rrt_df]['uom']='category' dfs[rrt_df]['delta']=pd.to_timedelta( pd.to_datetime(dfs[rrt_df]['first_charttime'])- pd.to_datetime(dfs[rrt_df][time_var]), 'days') dfs[rrt_df]['label']= 'rrt' dfs[rrt_df]=dfs[rrt_df].rename(index=str, columns={'rrt':'value'}) ``` ### converting to yes/no ``` dfs[rrt_df].head() dfs[rrt_df]['icustay_id'].nunique() # rrt_yn= yn_convert(dfs[rrt_df],label_fill='rrt', time_var=time_var) save_df(rrt_yn, 'rrt') del(rrt_yn, dfs[rrt_df]) ``` # GCS_72 ``` dfs[gcs_df]['uom']='GCS_score' list(dfs[gcs_df]) dfs[gcs_df]['label']= 'mingcs' dfs[gcs_df]['uom']='gcs_score' dfs[gcs_df]=dfs[gcs_df].rename(index=str, columns={'mingcs':'value'}) dfs[gcs_df]=dfs[gcs_df][['subject_id','hadm_id','icustay_id','delta','label','value',time_var,'uom']] save_df(dfs[gcs_df], 'gcs') del(dfs[gcs_df]) ``` # SOFA i'm going to remove all sofa variables except daily score, as we have other markers for those in our above data i may later use this as qc check. also added delta ``` dfs[sofa_df]['uom']='daily_sofa_score' #adding day delta column dfs[sofa_df]=dfs[sofa_df].sort_values(['hadm_id','day',time_var]) #good dfs[sofa_df]['day_rank']=dfs[sofa_df].groupby('icustay_id')['day'].rank() dfs[sofa_df]['delta']=pd.to_timedelta((dfs[sofa_df]['day_rank']-1), 'days') dfs[sofa_df]['label']= 'daily_sofa' dfs[sofa_df]=dfs[sofa_df].rename(index=str, columns={'sofa':'value'}) dfs[sofa_df]= dfs[sofa_df][['subject_id','hadm_id','icustay_id','delta','label','value',time_var,'uom']] dfs[sofa_df].head() save_df(dfs[sofa_df], 'sofa') del(dfs[sofa_df]) ``` # patient Demographic variables ``` dfs[pt_info_df] ### gender distribution qc. should be almost entirely/entirely populated #icustay_id #dfs[pt_info_df] model_pts=list(final_pt_df2[final_pt_df2['final_bin'].isin(['C_pos/A_full','C_neg/A_partial'])]['icustay_id'].unique()) model_pts=list(final_pt_df2[final_pt_df2['final_bin'].isin(['C_pos/A_full','C_neg/A_partial'])]['icustay_id'].unique()) dfs[pt_info_df][(dfs[pt_info_df]['label']=='gender')& (dfs[pt_info_df]['icustay_id'].isin(model_pts))]['value'].value_counts() len(model_pts) #### gender qc ##adjusting ages over 90 (which were set to 300 to deidentify) to 90 admit_index=dfs[pt_info_df].loc[(dfs[pt_info_df]['label']=='yearsold')].index age_tf=pd.to_numeric(dfs[pt_info_df].loc[admit_index,'value'])>90 dfs[pt_info_df].loc[(dfs[pt_info_df]['label']=='yearsold')&(age_tf),'value']=90.0 dfs[pt_info_df].loc[admit_index,'value'].value_counts() #dfs[pt_info_df].loc[(dfs[pt_info_df]['label']=='first_admit_age') & (dfs[pt_info_df]['value']>90)] #date= '22102018' save_df(dfs[pt_info_df], 'pt_info') del(dfs[pt_info_df] ) ```
github_jupyter
# `bsym` – a basic symmetry module `bsym` is a basic Python symmetry module. It consists of some core classes that describe configuration vector spaces, their symmetry operations, and specific configurations of objects withing these spaces. The module also contains an interface for working with [`pymatgen`](http://pymatgen.org) `Structure` objects, to allow simple generation of disordered symmetry-inequivalent structures from a symmetric parent crystal structure. API documentation is [here](http://bsym.readthedocs.io). ## Configuration Spaces, Symmetry Operations, and Groups The central object described by `bsym` is the **configuration space**. This defines a vector space that can be occupied by other objects. For example; the three points $a, b, c$ defined by an equilateral triangle, <img src='figures/triangular_configuration_space.pdf'> which can be described by a length 3 vector: \begin{pmatrix}a\\b\\c\end{pmatrix} If these points can be coloured black or white, then we can define a **configuration** for each different colouring (0 for white, 1 for black), e.g. <img src='figures/triangular_configuration_example_1.pdf'> with the corresponding vector \begin{pmatrix}1\\1\\0\end{pmatrix} A specific **configuration** therefore defines how objects are distributed within a particular **configuration space**. The symmetry relationships between the different vectors in a **configuration space** are described by **symmetry operations**. A **symmetry operation** describes a transformation of a **configuration space** that leaves it indistinguishable. Each **symmetry operation** can be describes as a matrix that maps the vectors in a **configuration space** onto each other, e.g. in the case of the equiateral triangle the simplest **symmetry operation** is the identity, $E$, which leaves every corner unchanged, and can be represented by the matrix \begin{equation} E=\begin{pmatrix}1 & 0 & 0\\0 & 1 & 0 \\ 0 & 0 & 1\end{pmatrix} \end{equation} For this triangular example, there are other **symmetry operations**, including reflections, $\sigma$ and rotations, $C_n$: <img src='figures/triangular_example_symmetry_operations.pdf'> In this example reflection operation, $b$ is mapped to $c$; $b\to c$, and $c$ is mapped to $b$; $b\to c$. The matrix representation of this **symmetry operation** is \begin{equation} \sigma_\mathrm{a}=\begin{pmatrix}1 & 0 & 0\\0 & 0 & 1 \\ 0 & 1 & 0\end{pmatrix} \end{equation} For the example rotation operation, $a\to b$, $b\to c$, and $c\to a$, with matrix representation \begin{equation} C_3=\begin{pmatrix}0 & 0 & 1\\ 1 & 0 & 0 \\ 0 & 1 & 0\end{pmatrix} \end{equation} Using this matrix and vector notation, the effect of a symmetry operation on a specific **configuration** can be calculated as the [matrix product](https://en.wikipedia.org/wiki/Matrix_multiplication#Square_matrix_and_column_vector) of the **symmetry operation** matrix and the **configuration** vector: <img src='figures/triangular_rotation_operation.pdf'> In matrix notation this is represented as \begin{equation} \begin{pmatrix}0\\1\\1\end{pmatrix} = \begin{pmatrix}0 & 0 & 1\\ 1 & 0 & 0 \\ 0 & 1 & 0\end{pmatrix}\begin{pmatrix}1\\1\\0\end{pmatrix} \end{equation} or more compactly \begin{equation} c_\mathrm{f} = C_3 c_\mathrm{i}. \end{equation} The set of all symmetry operations for a particular **configuration space** is a **group**. For an equilateral triangle this group is the $C_{3v}$ [point group](https://en.wikipedia.org/wiki/Point_group), which contains six symmetry operations: the identity, three reflections (each with a mirror plane bisecting the triangle and passing through $a$, $b$, or $c$ respectively) and two rotations (120° clockwise and counterclockwise). \begin{equation} C_{3v} = \left\{ E, \sigma_\mathrm{a}, \sigma_\mathrm{b}, \sigma_\mathrm{c}, C_3, C_3^\prime \right\} \end{equation} ## Modelling this using `bsym` ### The `SymmetryOperation` class In `bsym`, a **symmetry operation** is represented by an instance of the `SymmetryOperation` class. A `SymmetryOperation` instance can be initialised from the matrix representation of the corresponding **symmetry operation**. For example, in the trigonal **configuration space** above, a `SymmetryOperation` describing the identify, $E$, can be created with ``` from bsym import SymmetryOperation SymmetryOperation([[ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ]]) ``` Each `SymmetryOperation` has an optional `label` attribute. This can be set at records the matrix representation of the **symmetry operation** and an optional label. We can provide the label when creating a `SymmetryOperation`: ``` SymmetryOperation([[ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ]], label='E' ) ``` or set it afterwards: ``` e = SymmetryOperation([[ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ]]) e.label = 'E' e ``` Or for $C_3$: ``` c_3 = SymmetryOperation( [ [ 0, 0, 1 ], [ 1, 0, 0 ], [ 0, 1, 0 ] ], label='C3' ) c_3 ``` #### Vector representations of symmetry operations The matrix representation of a **symmetry operation** is a [permutation matrix](https://en.wikipedia.org/wiki/Permutation_matrix). Each row maps one position in the corresponding **configuration space** to one other position. An alternative, condensed, representation for each **symmetry operation** matrix uses vector notation, where each element gives the row containing `1` in the equivalent matrix column. e.g. for $C_3$ the vector mapping is given by $\left[2,3,1\right]$, corresponding to the mapping $1\to2$, $2\to3$, $3\to1$. ``` c_3_from_vector = SymmetryOperation.from_vector( [ 2, 3, 1 ], label='C3' ) c_3_from_vector ``` The vector representation of a `SymmetryOperation` can be accessed using the `as_vector()` method. ``` c_3.as_vector() ``` #### Inverting symmetry operations For every **symmetry operation**, $A$, there is an **inverse** operation, $A^{-1}$, such that \begin{equation} A \cdot A^{-1}=E. \end{equation} For example, the inverse of $C_3$ (clockwise rotation by 120°) is $C_3^\prime$ (anticlockwise rotation by 120°): ``` c_3 = SymmetryOperation.from_vector( [ 2, 3, 1 ], label='C3' ) c_3_inv = SymmetryOperation.from_vector( [ 3, 1, 2 ], label='C3_inv' ) print( c_3, '\n' ) print( c_3_inv, '\n' ) ``` The product of $C_3$ and $C_3^\prime$ is the identity, $E$. ``` c_3 * c_3_inv ``` <img src="figures/triangular_c3_inversion.pdf" /> `c_3_inv` can also be generated using the `.invert()` method ``` c_3.invert() ``` The resulting `SymmetryOperation` does not have a label defined. This can be set directly, or by chaining the `.set_label()` method, e.g. ``` c_3.invert( label= 'C3_inv') c_3.invert().set_label( 'C3_inv' ) ``` ### The `SymmetryGroup` class A `SymmetryGroup` is a collections of `SymmetryOperation` objects. A `SymmetryGroup` is not required to contain _all_ the symmetry operations of a particular **configuration space**, and therefore is not necessarily a complete mathematical <a href="https://en.wikipedia.org/wiki/Group_(mathematics)#Definition">group</a>. For convenience `bsym` has `PointGroup` and `SpaceGroup` classes, that are equivalent to the `SymmetryGroup` parent class. ``` from bsym import PointGroup # construct SymmetryOperations for C_3v group e = SymmetryOperation.from_vector( [ 1, 2, 3 ], label='e' ) c_3 = SymmetryOperation.from_vector( [ 2, 3, 1 ], label='C_3' ) c_3_inv = SymmetryOperation.from_vector( [ 3, 1, 2 ], label='C_3_inv' ) sigma_a = SymmetryOperation.from_vector( [ 1, 3, 2 ], label='S_a' ) sigma_b = SymmetryOperation.from_vector( [ 3, 2, 1 ], label='S_b' ) sigma_c = SymmetryOperation.from_vector( [ 2, 1, 3 ], label='S_c' ) ``` <img src="figures/triangular_c3v_symmetry_operations.pdf" /> ``` c3v = PointGroup( [ e, c_3, c_3_inv, sigma_a, sigma_b, sigma_c ] ) c3v ``` ### The `ConfigurationSpace` class A `ConfigurationSpace` consists of a set of objects that represent the **configuration space** vectors, and the `SymmetryGroup` containing the relevant **symmetry operations**. ``` from bsym import ConfigurationSpace c = ConfigurationSpace( objects=['a', 'b', 'c' ], symmetry_group=c3v ) c ``` ### The `Configuration` class A `Configuration` instance describes a particular **configuration**, i.e. how a set of objects are arranged within a **configuration space**. Internally, a `Configuration` is represented as a vector (as a `numpy` array). Each element in a configuration is represented by a single digit non-negative integer. ``` from bsym import Configuration conf_1 = Configuration( [ 1, 1, 0 ] ) conf_1 ``` The effect of a particular **symmetry operation** acting on a **configuration** can now be calculated using the `SymmetryOperation.operate_on()` method, or by direct multiplication, e.g. ``` c1 = Configuration( [ 1, 1, 0 ] ) c_3 = SymmetryOperation.from_vector( [ 2, 3, 1 ] ) c_3.operate_on( c1 ) c_3 * conf_1 ``` <img src="figures/triangular_rotation_operation.pdf" /> ## Finding symmetry-inequivalent permutations. A common question that comes up when considering the symmetry properties of arrangements of objects is: how many ways can these be arranged that are not equivalent by symmetry? As a simple example of solving this problem using `bsym` consider four equivalent sites arranged in a square. <img src="figures/square_configuration_space.pdf"> ``` c = ConfigurationSpace( [ 'a', 'b', 'c', 'd' ] ) # four vector configuration space ``` This `ConfigurationSpace` has been created without a `symmetry_group` argument. The default behaviour in this case is to create a `SymmetryGroup` containing only the identity, $E$. ``` c ``` We can now calculate all symmetry inequivalent arrangements where two sites are occupied and two are unoccupied, using the `unique_configurations()` method. This takes as a argument a `dict` with the numbers of labels to be arranged in the **configuration space**. Here, we use the labels `1` and `0` to represent occupied and unoccupied sites, respectively, and the distribution of sites is given by `{ 1:2, 0:2 }`. ``` c.unique_configurations( {1:2, 0:2} ) ``` Because we have not yet taken into account the symmetry of the **configuration space**, we get \begin{equation} \frac{4\times3}{2} \end{equation} unique configurations (where the factor of 2 comes from the occupied sites being indistinguishable). The configurations generated by `unique_configurations` have a `count` attribute that records the number of *symmetry equivalent* configurations of each case: In this example, each configuration appears once: ``` [ uc.count for uc in c.unique_configurations( {1:2, 0:2} ) ] ``` We can also calculate the result when all symmetry operations of this **configuration space** are included. ``` # construct point group e = SymmetryOperation.from_vector( [ 1, 2, 3, 4 ], label='E' ) c4 = SymmetryOperation.from_vector( [ 2, 3, 4, 1 ], label='C4' ) c4_inv = SymmetryOperation.from_vector( [ 4, 1, 2, 3 ], label='C4i' ) c2 = SymmetryOperation.from_vector( [ 3, 4, 1, 2 ], label='C2' ) sigma_x = SymmetryOperation.from_vector( [ 4, 3, 2, 1 ], label='s_x' ) sigma_y = SymmetryOperation.from_vector( [ 2, 1, 4, 3 ], label='s_y' ) sigma_ac = SymmetryOperation.from_vector( [ 1, 4, 3, 2 ], label='s_ac' ) sigma_bd = SymmetryOperation.from_vector( [ 3, 2, 1, 4 ], label='s_bd' ) c4v = PointGroup( [ e, c4, c4_inv, c2, sigma_x, sigma_y, sigma_ac, sigma_bd ] ) # create ConfigurationSpace with the c4v PointGroup. c = ConfigurationSpace( [ 'a', 'b', 'c', 'd' ], symmetry_group=c4v ) c c.unique_configurations( {1:2, 0:2} ) [ uc.count for uc in c.unique_configurations( {1:2, 0:2 } ) ] ``` Taking symmetry in to account, we now only have two unique configurations: either two adjacent site are occupied (four possible ways), or two diagonal sites are occupied (two possible ways): <img src="figures/square_unique_configurations.pdf" > The `unique_configurations()` method can also handle non-binary site occupations: ``` c.unique_configurations( {2:1, 1:1, 0:2} ) [ uc.count for uc in c.unique_configurations( {2:1, 1:1, 0:2 } ) ] ``` <img src="figures/square_unique_configurations_2.pdf"> ## Working with crystal structures using `pymatgen` One example where the it can be useful to identify symmetry-inequivalent arrangements of objects in a vector space, is when considering the possible arrangements of disordered atoms on a crystal lattice. To solve this problem for an arbitrary crystal structure, `bsym` contains an interface to [`pymatgen`](http://pymatgen.org) that will identify symmetry-inequivalent atom substitutions in a given `pymatgen` `Structure`. As an example, consider a $4\times4$ square-lattice supercell populated by lithium atoms. ``` from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure import numpy as np # construct a pymatgen Structure instance using the site fractional coordinates coords = np.array( [ [ 0.0, 0.0, 0.0 ] ] ) atom_list = [ 'Li' ] lattice = Lattice.from_parameters( a=1.0, b=1.0, c=1.0, alpha=90, beta=90, gamma=90 ) parent_structure = Structure( lattice, atom_list, coords ) * [ 4, 4, 1 ] parent_structure.cart_coords.round(2) ``` We can use the `bsym.interface.pymatgen.unique_structure_substitutions()` function to identify symmetry-inequivalent structures generated by substituting at different sites. ``` from bsym.interface.pymatgen import unique_structure_substitutions print( unique_structure_substitutions.__doc__ ) ``` As a trivial example, when substituting one Li atom for Na, we get a single unique structure ``` unique_structures = unique_structure_substitutions( parent_structure, 'Li', { 'Na':1, 'Li':15 } ) len( unique_structures ) ``` <img src="figures/pymatgen_example_one_site.pdf"> ``` na_substituted = unique_structures[0] ``` This Li$\to$Na substitution breaks the symmetry of the $4\times4$ supercell. If we now replace a second lithium with a magnesium atom, we generate five symmetry inequivalent structures: ``` unique_structures_with_Mg = unique_structure_substitutions( na_substituted, 'Li', { 'Mg':1, 'Li':14 } ) len( unique_structures_with_Mg ) [ s.number_of_equivalent_configurations for s in unique_structures_with_Mg ] ``` `number_of_equivalent_configurations` only lists the number of equivalent configurations found when performing the second substitution, when the list of structures `unique_structures_with_Mg` was created. The full configuration degeneracy relative to the initial empty 4×4 lattice can be queried using `full_configuration_degeneracy`. ``` [ s.full_configuration_degeneracy for s in unique_structures_with_Mg ] ``` <img src="figures/pymatgen_example_two_sites.pdf"> ``` # Check the squared distances between the Na and Mg sites in these unique structures are [1, 2, 4, 5, 8] np.array( sorted( [ s.get_distance( s.indices_from_symbol('Na')[0], s.indices_from_symbol('Mg')[0] )**2 for s in unique_structures_with_Mg ] ) ) ``` This double substitution can also be done in a single step: ``` unique_structures = unique_structure_substitutions( parent_structure, 'Li', { 'Mg':1, 'Na':1, 'Li':14 } ) len(unique_structures) np.array( sorted( [ s.get_distance( s.indices_from_symbol('Na')[0], s.indices_from_symbol('Mg')[0] ) for s in unique_structures ] ) )**2 [ s.number_of_equivalent_configurations for s in unique_structures ] ``` Because both substitutions were performed in a single step, `number_of_equivalent_configurations` and `full_configuration_degeneracy` now contain the same data: ``` [ s.full_configuration_degeneracy for s in unique_structures ] ``` ## Constructing `SpaceGroup` and `ConfigurationSpace` objects using `pymatgen` The `bsym.interface.pymatgen` module contains functions for generating `SpaceGroup` and `ConfigurationSpace` objects directly from `pymatgen` `Structure` objects. ``` from bsym.interface.pymatgen import ( space_group_symbol_from_structure, space_group_from_structure, configuration_space_from_structure ) ``` Documentation: - [`space_group_symbol_from_structure`](http://bsym.readthedocs.io/en/latest/api/interface/pymatgen.html#bsym.interface.pymatgen.space_group_symbol_from_structure) - [`space_group_from_structure`](http://bsym.readthedocs.io/en/latest/api/interface/pymatgen.html#bsym.interface.pymatgen.space_group_from_structure) - [`configuration_space_from_structure`](http://bsym.readthedocs.io/en/latest/api/interface/pymatgen.html#bsym.interface.pymatgen.configuration_space_from_structure) ``` coords = np.array( [ [ 0.0, 0.0, 0.0 ], [ 0.5, 0.5, 0.0 ], [ 0.0, 0.5, 0.5 ], [ 0.5, 0.0, 0.5 ] ] ) atom_list = [ 'Li' ] * len( coords ) lattice = Lattice.from_parameters( a=3.0, b=3.0, c=3.0, alpha=90, beta=90, gamma=90 ) structure = Structure( lattice, atom_list, coords ) space_group_symbol_from_structure( structure ) space_group_from_structure( structure ) configuration_space_from_structure( structure ) ``` ## Progress bars `bsym.ConfigurationSpace.unique_configurations()` and `bsym.interface.pymatgen.unique_structure_substitutions()` both accept optional `show_progress` arguments, which can be used to display progress bars (using `tqdm`(https://tqdm.github.io). Setting `show_progress=True` will give a simple progress bar. If you are running `bsym` in a Jupyter notebook, setting `show_progress="notebook"` will give you a progress bar as a notebook widget. (note, the widget status is not saved with this notebook, and may not display correctly on GitHub or using nbviewer) In the example below, we find all unique configurations for the pseudo-ReO<sub>3</sub> structured TiOF<sub>2</sub> in a 2&times;2&times;2 supercell. ``` a = 3.798 # lattice parameter coords = np.array( [ [ 0.0, 0.0, 0.0 ], [ 0.5, 0.0, 0.0 ], [ 0.0, 0.5, 0.0 ], [ 0.0, 0.0, 0.5 ] ] ) atom_list = [ 'Ti', 'X', 'X', 'X' ] lattice = Lattice.from_parameters( a=a, b=a, c=a, alpha=90, beta=90, gamma=90 ) unit_cell = Structure( lattice, atom_list, coords ) parent_structure = unit_cell * [ 2, 2, 2 ] unique_structures = unique_structure_substitutions( parent_structure, 'X', { 'O':8, 'F':16 }, show_progress='notebook' ) %load_ext version_information %version_information bsym, numpy, jupyter, pymatgen, tqdm ```
github_jupyter
Visualisation des différentes statistiques de Dbnary ============= ``` import datetime # PLotting import bqplot as bq # Data analys import numpy as np from IPython.display import clear_output from ipywidgets import widgets from pandasdatacube import * ENDPOINT: str = "http://kaiko.getalp.org/sparql" PREFIXES: dict[str] = {'dbnary': 'http://kaiko.getalp.org/dbnary#', 'dbnstats': 'http://kaiko.getalp.org/dbnary/statistics/', 'lime': 'http://www.w3.org/ns/lemon/lime#'} HTML_COLORS = ["red", "blue", "cyan", "pink", "lime", "purple", "orange", "fuchsia", 'Teal', 'Navy', 'Maroon', 'Olive', 'Gray', 'Lime', 'Silver', 'Green', 'Black'] ``` ### Classe qui retourne un DataFrame des résultats d'une requête SPARQL et autes fonctions utilitaires ``` def transformation_date(date: int) -> datetime.datetime: """ Function that transform a date of typr str (YYYYMMDD) to a datetime object """ if int(date[6:]) == 0: # if the date do'nt existv return datetime.datetime(year=int(date[:4]), month=int(date[4:6]), day=int(date[6:]) + 1) return datetime.datetime(year=int(date[:4]), month=int(date[4:6]), day=int(date[6:])) ``` ### On commence par chercher tout les différents types de datasets et on va proposer à l'utilisateur de choisir quel dataset télécharger ### Traitement des certains Datasets particulier, le code ci-dessous n'est pas généralisable #### 1. dbnaryNymRelationsCube ``` dataset: str = "dbnstats:dbnaryNymRelationsCube" dimensions: list[str] = ['dbnary:wiktionaryDumpVersion', 'dbnary:nymRelation', 'dbnary:observationLanguage'] mesures: list[str] = ['dbnary:count'] dtypes: dict[str] = {'count': int} data1: pd.DataFrame = get_datacube(ENDPOINT, dataset, dimensions, mesures, dtypes, PREFIXES).reset_index() relations1: np.ndarray = data1['nymRelation'].unique() # All type of relation in this cube labels1: list[str] = [item.split('#')[-1] for item in relations1] data1 = data1.pivot_table(columns='nymRelation', index=['wiktionaryDumpVersion', 'observationLanguage'], aggfunc=max).reset_index().sort_values(by=['wiktionaryDumpVersion', 'observationLanguage']) data1["wiktionaryDumpVersion"] = data1["wiktionaryDumpVersion"].map(transformation_date) out1 = widgets.Output() choice1 = widgets.ToggleButtons(options=[('Statistiques globales', 'glob'), ('Par pays', 'pays')], description='Choix:', disabled=False, tooltips=['Statistiques de tout les pays par années', 'Statistiques d\' pays au cours du temps']) def event1(obj): with out1: clear_output() if choice1.value == "pays": user_choice = widgets.Dropdown(options=list(data1["observationLanguage"].unique()), description="Choix:") choosed_data = data1[data1["observationLanguage"] == user_choice.value] y_sc = bq.LinearScale() x_ord = bq.scales.DateScale() line = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data["count"][relations1].T, stroke_width=1, display_legend=True, labels=labels1, scales={'x': x_ord, 'y': y_sc}) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Date', tick_format='%m %Y') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], animation_duration=1000, title=f"Différentes relations lexicales dans l'extraction {user_choice.value}") def edit_graph(obj): choosed_data = data1[data1["observationLanguage"] == user_choice.value] line.y = choosed_data["count"][relations1].T line.x = choosed_data["wiktionaryDumpVersion"] fig.title = f"Différentes relations lexicales dans l'extraction {user_choice.value}" if choice1.value == "glob": user_choice = widgets.Dropdown(options=[(np.datetime_as_string(item, unit='D'), item) for item in data1["wiktionaryDumpVersion"].unique()], description="Choix:", value=max(data1["wiktionaryDumpVersion"].unique())) x_ord = bq.OrdinalScale() y_sc = bq.LinearScale() choosed_data = data1[data1["wiktionaryDumpVersion"] == user_choice.value] x = choosed_data["observationLanguage"].values y = choosed_data["count"][relations1].T bar = bq.Bars(x=x, y=y, scales={'x': x_ord, 'y': y_sc}, type='stacked', labels=labels1, color_mode='element', display_legend=True, colors=HTML_COLORS) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Pays') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[bar], axes=[ax_x, ax_y], animation_duration=1000, title=f"Nombre de relations lexicales dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}") def edit_graph(obj): choosed_data = data1[data1["wiktionaryDumpVersion"] == user_choice.value] bar.x = choosed_data["observationLanguage"].values bar.y = choosed_data["count"][relations1].T fig.title = f"Nombre de relations lexicales dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}" def add_pie_chart_in_tooltip(chart, d): idx = d["data"]["index"] bar.tooltip = widgets.HTML(pd.DataFrame( data1[data1["wiktionaryDumpVersion"] == user_choice.value].iloc[idx]["count"]).to_html()) bar.on_hover(add_pie_chart_in_tooltip) display(user_choice, fig) user_choice.observe(edit_graph, 'value') choice1.observe(event1, 'value') display(choice1, out1) event1(None) ``` #### 2. dbnaryStatisticsCube ``` dataset: str = "dbnstats:dbnaryStatisticsCube" dimensions: list[str] = ['dbnary:observationLanguage', 'dbnary:wiktionaryDumpVersion'] mesures: list[str] = ['dbnary:lexicalEntryCount', 'dbnary:lexicalSenseCount', 'dbnary:pageCount', 'dbnary:translationsCount'] dtypes: dict[str] = {"lexicalEntryCount": int, "translationsCount": int, "lexicalSenseCount": int, "pageCount": int} data2: pd.DataFrame = get_datacube(ENDPOINT, dataset, dimensions, mesures, dtypes, PREFIXES).reset_index().sort_values(by=['wiktionaryDumpVersion', 'observationLanguage']) categories2: list[str] = ["lexicalEntryCount", "translationsCount", "lexicalSenseCount", "pageCount"] data2["wiktionaryDumpVersion"] = data2["wiktionaryDumpVersion"].map(transformation_date) out2 = widgets.Output() choice2 = widgets.ToggleButtons(options=[('Statistiques globales', 'glob'), ('Par pays', 'pays')], description='Choix:', disabled=False, tooltips=['Statistiques de tout les pays par années', 'Statistiques d\' pays au cours du temps']) def event2(obj): with out2: clear_output() if choice2.value == "pays": user_choice = widgets.Dropdown(options=list(data2["observationLanguage"].unique()), description="Choix:") choosed_data = data2[data2["observationLanguage"] == user_choice.value] y_sc = bq.LinearScale() x_ord = bq.scales.DateScale() line = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data[categories2].T, stroke_width=1, display_legend=True, labels=categories2, scales={'x': x_ord, 'y': y_sc}) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Date', tick_format='%m %Y') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], title=f"Nombre d'éléments dans l'extraction {user_choice.value}", animation_duration=1000) def edit_graph(obj): choosed_data = data2[data2["observationLanguage"] == user_choice.value] line.y = choosed_data[categories2].T line.x = choosed_data["wiktionaryDumpVersion"] fig.title = f"Nombre d'éléments dans l'extraction {user_choice.value}" if choice2.value == "glob": user_choice = widgets.Dropdown(options=[(np.datetime_as_string(item, unit='D'), item) for item in data2["wiktionaryDumpVersion"].unique()], description="Choix:", value=max(data2["wiktionaryDumpVersion"].unique())) x_ord = bq.OrdinalScale() y_sc = bq.LinearScale() choosed_data = data2[data2["wiktionaryDumpVersion"] == user_choice.value] x = choosed_data["observationLanguage"].values y = choosed_data[categories2].T bar = bq.Bars(x=x, y=y, scales={'x': x_ord, 'y': y_sc}, type='stacked', labels=categories2, color_mode='element', display_legend=True, colors=HTML_COLORS) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Pays') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[bar], axes=[ax_x, ax_y], animation_duration=1000, title=f"Nombre de relations lexicales dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}") def edit_graph(obj): choosed_data = data2[data2["wiktionaryDumpVersion"] == user_choice.value] bar.x = choosed_data["observationLanguage"].values bar.y = choosed_data[categories2].T fig.title = f"Nombre de relations lexicales dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}" def add_pie_chart_in_tooltip(chart, d): idx = d["data"]["index"] bar.tooltip = widgets.HTML( pd.DataFrame(data2[data2["wiktionaryDumpVersion"] == user_choice.value].iloc[idx]).to_html()) bar.on_hover(add_pie_chart_in_tooltip) display(user_choice, fig) user_choice.observe(edit_graph, 'value') choice2.observe(event2, 'value') display(choice2, out2) event2(None) ``` #### 3. dbnaryTranslationsCube ``` dataset: str = "dbnstats:dbnaryTranslationsCube" dimensions: list[str] = ['lime:language', 'dbnary:wiktionaryDumpVersion', 'dbnary:observationLanguage'] mesures: list[str] = ['dbnary:count'] dtypes: dict[str] = {'count': int} data3: pd.DataFrame = get_datacube(ENDPOINT, dataset, dimensions, mesures, dtypes, PREFIXES).reset_index().sort_values(by=['wiktionaryDumpVersion', 'observationLanguage']) relations3: np.ndarray = data3['language'].unique() relations3 = relations3[relations3 != "number_of_languages"] labels3: list[str] = [item.split('#')[-1] for item in relations3] data3["wiktionaryDumpVersion"] = data3["wiktionaryDumpVersion"].map(transformation_date) data3 = data3.pivot_table(columns='language', index=['wiktionaryDumpVersion', 'observationLanguage'], aggfunc=max).reset_index().sort_values(by=['wiktionaryDumpVersion', 'observationLanguage']) out3 = widgets.Output() choice3 = widgets.ToggleButtons(options=[('Statistiques globales', 'glob'), ('Par pays', 'pays')], description='Choix:', disabled=False, tooltips=['Statistiques de tout les pays par années', 'Statistiques d\' pays au cours du temps']) def event3(obj): with out3: clear_output() if choice3.value == "pays": user_choice = widgets.Dropdown(options=list(data3["observationLanguage"].unique()), description="Choix:") choosed_data = data3[data3["observationLanguage"] == user_choice.value] y_sc = bq.LinearScale() y_sc2 = bq.LinearScale() x_ord = bq.scales.DateScale() line = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data["count"][relations3].T, stroke_width=1, display_legend=True, labels=labels3, scales={'x': x_ord, 'y': y_sc}) line1 = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data["count"]["number_of_languages"].values, scales={'x': x_ord, 'y': y_sc2}, stroke_width=1, display_legend=True, labels=["Number of languages"], colors=['green'], line_style="dashed") ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Date', tick_format='%m %Y') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') ax_y2 = bq.Axis(scale=y_sc2, orientation='vertical', grid_lines='solid', label='Nombre de langues', label_offset='+50', side="right", label_color="green") fig = bq.Figure(marks=[line, line1], axes=[ax_x, ax_y, ax_y2], animation_duration=1000, title=f"Nombre de traductions dans l'extraction {user_choice.value}") def edit_graph(obj): choosed_data = data3[data3["observationLanguage"] == user_choice.value] line.y = choosed_data["count"][relations3].T line.x = choosed_data["wiktionaryDumpVersion"] line1.x = choosed_data["wiktionaryDumpVersion"] line1.y = choosed_data["count"]["number_of_languages"].values fig.title = f"Nombre de traductions dans l'extraction {user_choice.value}" if choice3.value == "glob": user_choice = widgets.Dropdown(options=[(np.datetime_as_string(item, unit='D'), item) for item in data3["wiktionaryDumpVersion"].unique()], description="Choix:", value=max(data3["wiktionaryDumpVersion"].unique())) x_ord = bq.OrdinalScale() y_sc = bq.LinearScale() y_sc2 = bq.LinearScale() choosed_data = data3[data3["wiktionaryDumpVersion"] == user_choice.value] x = choosed_data["observationLanguage"].values y = choosed_data["count"][relations3].T bar = bq.Bars(x=x, y=y, scales={'x': x_ord, 'y': y_sc}, type='stacked', labels=labels3, color_mode='element', display_legend=True, colors=HTML_COLORS) line = bq.Lines(x=x, y=choosed_data["count"]["number_of_languages"].values, scales={'x': x_ord, 'y': y_sc2}, stroke_width=1, display_legend=True, labels=["Number of languages"], colors=["green"]) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Pays') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') ax_y2 = bq.Axis(scale=y_sc2, orientation='vertical', grid_lines='solid', label='Nombre de langues', label_offset='+50', side="right", label_color="green") fig = bq.Figure(marks=[bar, line], axes=[ax_x, ax_y, ax_y2], animation_duration=1000, legend_location="top-left", title=f"Nombre de traductions dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}") def edit_graph(obj): choosed_data = data3[data3["wiktionaryDumpVersion"] == user_choice.value].sort_values( by="observationLanguage") bar.x = choosed_data["observationLanguage"].values bar.y = choosed_data["count"][relations3].T line.x = bar.x line.y = choosed_data["count"]["number_of_languages"].values fig.title = f"Nombre de traductions lexicales dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}" def add_pie_chart_in_tooltip(chart, d): idx = d["data"]["index"] bar.tooltip = widgets.HTML(pd.DataFrame( data3[data3["wiktionaryDumpVersion"] == user_choice.value].iloc[idx]["count"]).to_html()) bar.on_hover(add_pie_chart_in_tooltip) display(user_choice, fig) user_choice.observe(edit_graph, 'value') choice3.observe(event3, 'value') display(choice3, out3) event3(None) ``` #### 4. enhancementConfidenceDataCube ``` dataset: str = "dbnstats:enhancementConfidenceDataCube" dimensions: list[str] = ['dbnary:wiktionaryDumpVersion', 'dbnary:enhancementMethod', 'dbnary:observationLanguage'] mesures: list[str] = ['dbnary:precisionMeasure', 'dbnary:recallMeasure', 'dbnary:f1Measure'] dtypes: dict[str] = {"precisionMeasure": float, "recallMeasure": float, "f1Measure": float} data4t: pd.DataFrame = get_datacube(ENDPOINT, dataset, dimensions, mesures, dtypes, PREFIXES).reset_index().sort_values( by=['wiktionaryDumpVersion', 'observationLanguage']) categories4: list[str] = ["precisionMeasure", "recallMeasure", "f1Measure"] data4t["wiktionaryDumpVersion"] = data4t["wiktionaryDumpVersion"].map(transformation_date) out4 = widgets.Output() choice4 = widgets.ToggleButtons(options=[('Statistiques globales', 'glob'), ('Par pays', 'pays')], description='Choix:', disabled=False, tooltips=['Statistiques de tout les pays par années', 'Statistiques d\' pays au cours du temps']) choice4bis = widgets.ToggleButtons(options=[('Aléatoire', 'random'), ('Dbnary tversky', 'dbnary_tversky')], description='Méthode d\'amélioration:', disabled=False) def event4(obj): with out4: clear_output() data4 = data4t[data4t["enhancementMethod"] == choice4bis.value] if choice4.value == "pays": user_choice = widgets.Dropdown(options=list(data4["observationLanguage"].unique()), description="Choix:") choosed_data = data4[data4["observationLanguage"] == user_choice.value] y_sc = bq.LinearScale() x_ord = bq.scales.DateScale() line = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data[categories4].T, stroke_width=1, display_legend=True, labels=categories4, scales={'x': x_ord, 'y': y_sc}) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Date', tick_format='%m %Y') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], animation_duration=1000, title=f"Précision de la prédiction du contexte de traduction dans l'extraction du {user_choice.value}") def edit_graph(obj): choosed_data = data4[data4["observationLanguage"] == user_choice.value] line.y = choosed_data[categories4].T line.x = choosed_data["wiktionaryDumpVersion"] fig.title = f"Précision de la prédiction du contexte de traduction dans l'extraction du {user_choice.value}" if choice4.value == "glob": user_choice = widgets.Dropdown(options=[(np.datetime_as_string(item, unit='D'), item) for item in data4["wiktionaryDumpVersion"].unique()], description="Choix:", value=max(data4["wiktionaryDumpVersion"].unique())) x_ord = bq.OrdinalScale() y_sc = bq.LinearScale() choosed_data = data4[data4["wiktionaryDumpVersion"] == user_choice.value] x = choosed_data["observationLanguage"].values y = choosed_data[categories4].T bar = bq.Bars(x=x, y=y, scales={'x': x_ord, 'y': y_sc}, type='stacked', labels=categories4, color_mode='element', display_legend=True, colors=HTML_COLORS) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Pays') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[bar], axes=[ax_x, ax_y], animation_duration=1000, title=f"Précision de la prédiction du contexte de traduction dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}") def edit_graph(obj): choosed_data = data4[data4["wiktionaryDumpVersion"] == user_choice.value] bar.x = choosed_data["observationLanguage"].values bar.y = choosed_data[categories4].T fig.title = f"Précision de la prédiction du contexte de traduction dans l'extraction du {np.datetime_as_string(user_choice.value, unit='D')}" def add_pie_chart_in_tooltip(chart, d): idx = d["data"]["index"] bar.tooltip = widgets.HTML( pd.DataFrame(data4[data4["wiktionaryDumpVersion"] == user_choice.value].iloc[idx]).to_html()) bar.on_hover(add_pie_chart_in_tooltip) display(user_choice, fig) user_choice.observe(edit_graph, 'value') choice4.observe(event4, 'value') choice4bis.observe(event4, 'value') display(choice4, choice4bis, out4) event4(None) ``` #### 5. translationGlossesCube ``` dataset: str = "dbnstats:translationGlossesCube" dimensions: list[str] = ['dbnary:wiktionaryDumpVersion', 'dbnary:observationLanguage'] mesures: list[str] = ['dbnary:translationsWithNoGloss', 'dbnary:translationsWithSenseNumber', 'dbnary:translationsWithSenseNumberAndTextualGloss', 'dbnary:translationsWithTextualGloss'] dtypes: dict[str] = {"translationsWithSenseNumber": float, "translationsWithSenseNumberAndTextualGloss": float, "translationsWithTextualGloss": float, "translationsWithNoGloss": float} data5: pd.DataFrame = get_datacube(ENDPOINT, dataset, dimensions, mesures, dtypes, PREFIXES).reset_index().sort_values( by=['wiktionaryDumpVersion', 'observationLanguage']) categories5: list[str] = ["translationsWithSenseNumber", "translationsWithSenseNumberAndTextualGloss", "translationsWithTextualGloss", "translationsWithNoGloss"] data5["wiktionaryDumpVersion"] = data5["wiktionaryDumpVersion"].map(transformation_date) out5 = widgets.Output() choice5 = widgets.ToggleButtons(options=[('Statistiques globales', 'glob'), ('Par pays', 'pays')], description='Choix:', disabled=False, tooltips=['Statistiques de tout les pays par années', 'Statistiques d\' pays au cours du temps']) def event5(obj): with out5: clear_output() if choice5.value == "pays": user_choice = widgets.Dropdown(options=list(data5["observationLanguage"].unique()), description="Choix:") choosed_data = data5[data5["observationLanguage"] == user_choice.value] y_sc = bq.LinearScale() x_ord = bq.scales.DateScale() line = bq.Lines(x=choosed_data["wiktionaryDumpVersion"], y=choosed_data[categories5].T, stroke_width=1, display_legend=True, labels=categories5, scales={'x': x_ord, 'y': y_sc}) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Date', tick_format='%m %Y') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[line], axes=[ax_x, ax_y], title=f"{user_choice.value}", animation_duration=1000) def edit_graph(obj): choosed_data = data5[data5["observationLanguage"] == user_choice.value] line.y = choosed_data[categories5].T line.x = choosed_data["wiktionaryDumpVersion"] fig.title = f"{user_choice.value}" if choice5.value == "glob": user_choice = widgets.Dropdown(options=[(np.datetime_as_string(item, unit='D'), item) for item in data5["wiktionaryDumpVersion"].unique()], description="Choix:", value=max(data5["wiktionaryDumpVersion"].unique())) x_ord = bq.OrdinalScale() y_sc = bq.LinearScale() choosed_data = data5[data5["wiktionaryDumpVersion"] == user_choice.value] x = choosed_data["observationLanguage"].values y = choosed_data[categories5].T bar = bq.Bars(x=x, y=y, scales={'x': x_ord, 'y': y_sc}, type='stacked', labels=categories5, color_mode='element', display_legend=True, colors=HTML_COLORS) ax_x = bq.Axis(scale=x_ord, grid_lines='solid', label='Pays') ax_y = bq.Axis(scale=y_sc, orientation='vertical', grid_lines='solid', label='Valeur', label_offset='-50') fig = bq.Figure(marks=[bar], axes=[ax_x, ax_y], title=f"{np.datetime_as_string(user_choice.value, unit='D')}", animation_duration=1000) def edit_graph(obj): choosed_data = data5[data5["wiktionaryDumpVersion"] == user_choice.value] bar.x = choosed_data["observationLanguage"].values bar.y = choosed_data[categories5].T fig.title = f"{np.datetime_as_string(user_choice.value, unit='D')}" def add_pie_chart_in_tooltip(chart, d): idx = d["data"]["index"] bar.tooltip = widgets.HTML( pd.DataFrame(data5[data5["wiktionaryDumpVersion"] == user_choice.value].iloc[idx]).to_html()) bar.on_hover(add_pie_chart_in_tooltip) display(user_choice, fig) user_choice.observe(edit_graph, 'value') choice5.observe(event5, 'value') display(choice5, out5) event5(None) ```
github_jupyter
<CENTER> <img src="img/PyDataLogoBig-Paris2015.png" width="50%"> <header> <h1>Introduction to Pandas</h1> <h3>April 3rd, 2015</h3> <h2>Joris Van den Bossche</h2> <p></p> Source: <a href="https://github.com/jorisvandenbossche/2015-PyDataParis">https://github.com/jorisvandenbossche/2015-PyDataParis</a> </header> </CENTER> # About me: Joris Van den Bossche - PhD student at Ghent University and VITO, Belgium - bio-science engineer, air quality research - pandas core dev -> - https://github.com/jorisvandenbossche - [@jorisvdbossche](https://twitter.com/jorisvdbossche) Licensed under [CC BY 4.0 Creative Commons](http://creativecommons.org/licenses/by/4.0/) # Content of this talk - Why do you need pandas? - Basic introduction to the data structures - Guided tour through some of the pandas features with a **case study about air quality** If you want to follow along, this is a notebook that you can view or run yourself: - All materials (notebook, data, link to nbviewer): https://github.com/jorisvandenbossche/2015-PyDataParis - You need `pandas` > 0.15 (easy solution is using Anaconda) Some imports: ``` %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn pd.options.display.max_rows = 8 ``` # Let's start with a showcase ## Case study: air quality in Europe AirBase (The European Air quality dataBase): hourly measurements of all air quality monitoring stations from Europe Starting from these hourly data for different stations: ``` import airbase data = airbase.load_data() data ``` to answering questions about this data in a few lines of code: **Does the air pollution show a decreasing trend over the years?** ``` data['1999':].resample('A').plot(ylim=[0,100]) ``` **How many exceedances of the limit values?** ``` exceedances = data > 200 exceedances = exceedances.groupby(exceedances.index.year).sum() ax = exceedances.loc[2005:].plot(kind='bar') ax.axhline(18, color='k', linestyle='--') ``` **What is the difference in diurnal profile between weekdays and weekend?** ``` data['weekday'] = data.index.weekday data['weekend'] = data['weekday'].isin([5, 6]) data_weekend = data.groupby(['weekend', data.index.hour])['FR04012'].mean().unstack(level=0) data_weekend.plot() ``` We will come back to these example, and build them up step by step. # Why do you need pandas? ## Why do you need pandas? When working with *tabular or structured data* (like R dataframe, SQL table, Excel spreadsheet, ...): - Import data - Clean up messy data - Explore data, gain insight into data - Process and prepare your data for analysis - Analyse your data (together with scikit-learn, statsmodels, ...) # Pandas: data analysis in python For data-intensive work in Python the [Pandas](http://pandas.pydata.org) library has become essential. What is ``pandas``? * Pandas can be thought of as NumPy arrays with labels for rows and columns, and better support for heterogeneous data types, but it's also much, much more than that. * Pandas can also be thought of as `R`'s `data.frame` in Python. * Powerful for working with missing data, working with time series data, for reading and writing your data, for reshaping, grouping, merging your data, ... It's documentation: http://pandas.pydata.org/pandas-docs/stable/ ## Key features * Fast, easy and flexible input/output for a lot of different data formats * Working with missing data (`.dropna()`, `pd.isnull()`) * Merging and joining (`concat`, `join`) * Grouping: `groupby` functionality * Reshaping (`stack`, `pivot`) * Powerful time series manipulation (resampling, timezones, ..) * Easy plotting # Basic data structures Pandas does this through two fundamental object types, both built upon NumPy arrays: the ``Series`` object, and the ``DataFrame`` object. ## Series A Series is a basic holder for **one-dimensional labeled data**. It can be created much as a NumPy array is created: ``` s = pd.Series([0.1, 0.2, 0.3, 0.4]) s ``` ### Attributes of a Series: `index` and `values` The series has a built-in concept of an **index**, which by default is the numbers *0* through *N - 1* ``` s.index ``` You can access the underlying numpy array representation with the `.values` attribute: ``` s.values ``` We can access series values via the index, just like for NumPy arrays: ``` s[0] ``` Unlike the NumPy array, though, this index can be something other than integers: ``` s2 = pd.Series(np.arange(4), index=['a', 'b', 'c', 'd']) s2 s2['c'] ``` In this way, a ``Series`` object can be thought of as similar to an ordered dictionary mapping one typed value to another typed value: ``` population = pd.Series({'Germany': 81.3, 'Belgium': 11.3, 'France': 64.3, 'United Kingdom': 64.9, 'Netherlands': 16.9}) population population['France'] ``` but with the power of numpy arrays: ``` population * 1000 ``` We can index or slice the populations as expected: ``` population['Belgium'] population['Belgium':'Germany'] ``` Many things you can do with numpy arrays, can also be applied on objects. Fancy indexing, like indexing with a list or boolean indexing: ``` population[['France', 'Netherlands']] population[population > 20] ``` Element-wise operations: ``` population / 100 ``` A range of methods: ``` population.mean() ``` ### Alignment! Only, pay attention to **alignment**: operations between series will align on the index: ``` s1 = population[['Belgium', 'France']] s2 = population[['France', 'Germany']] s1 s2 s1 + s2 ``` ## DataFrames: Multi-dimensional Data A DataFrame is a **tablular data structure** (multi-dimensional object to hold labeled data) comprised of rows and columns, akin to a spreadsheet, database table, or R's data.frame object. You can think of it as multiple Series object which share the same index. <img src="img/dataframe.png" width=110%> One of the most common ways of creating a dataframe is from a dictionary of arrays or lists. Note that in the IPython notebook, the dataframe will display in a rich HTML view: ``` data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'], 'population': [11.3, 64.3, 81.3, 16.9, 64.9], 'area': [30510, 671308, 357050, 41526, 244820], 'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'London']} countries = pd.DataFrame(data) countries ``` ### Attributes of the DataFrame A DataFrame has besides a `index` attribute, also a `columns` attribute: ``` countries.index countries.columns ``` To check the data types of the different columns: ``` countries.dtypes ``` An overview of that information can be given with the `info()` method: ``` countries.info() ``` Also a DataFrame has a `values` attribute, but attention: when you have heterogeneous data, all values will be upcasted: ``` countries.values ``` If we don't like what the index looks like, we can reset it and set one of our columns: ``` countries = countries.set_index('country') countries ``` To access a Series representing a column in the data, use typical indexing syntax: ``` countries['area'] ``` As you play around with DataFrames, you'll notice that many operations which work on NumPy arrays will also work on dataframes. Let's compute density of each country: ``` countries['population']*1000000 / countries['area'] ``` Adding a new column to the dataframe is very simple: ``` countries['density'] = countries['population']*1000000 / countries['area'] countries ``` We can use masking to select certain data: ``` countries[countries['density'] > 300] ``` And we can do things like sorting the items in the array, and indexing to take the first two rows: ``` countries.sort_index(by='density', ascending=False) ``` One useful method to use is the ``describe`` method, which computes summary statistics for each column: ``` countries.describe() ``` The `plot` method can be used to quickly visualize the data in different ways: ``` countries.plot() ``` However, for this dataset, it does not say that much. ``` countries['population'].plot(kind='bar') countries.plot(kind='scatter', x='population', y='area') ``` The available plotting types: ‘line’ (default), ‘bar’, ‘barh’, ‘hist’, ‘box’ , ‘kde’, ‘area’, ‘pie’, ‘scatter’, ‘hexbin’. ``` countries = countries.drop(['density'], axis=1) ``` ## Some notes on selecting data One of pandas' basic features is the labeling of rows and columns, but this makes indexing also a bit more complex compared to numpy. We now have to distuinguish between: - selection by label - selection by position. For a DataFrame, basic indexing selects the columns. Selecting a single column: ``` countries['area'] ``` or multiple columns: ``` countries[['area', 'density']] ``` But, slicing accesses the rows: ``` countries['France':'Netherlands'] ``` For more advanced indexing, you have some extra attributes: * `loc`: selection by label * `iloc`: selection by position ``` countries.loc['Germany', 'area'] countries.loc['France':'Germany', :] countries.loc[countries['density']>300, ['capital', 'population']] ``` Selecting by position with `iloc` works similar as indexing numpy arrays: ``` countries.iloc[0:2,1:3] ``` The different indexing methods can also be used to assign data: ``` countries.loc['Belgium':'Germany', 'population'] = 10 countries ``` There are many, many more interesting operations that can be done on Series and DataFrame objects, but rather than continue using this toy data, we'll instead move to a real-world example, and illustrate some of the advanced concepts along the way. # Case study: air quality data of European monitoring stations (AirBase) ## AirBase (The European Air quality dataBase) AirBase: hourly measurements of all air quality monitoring stations from Europe. ``` from IPython.display import HTML HTML('<iframe src=http://www.eea.europa.eu/data-and-maps/data/airbase-the-european-air-quality-database-8#tab-data-by-country width=700 height=350></iframe>') ``` # Importing and cleaning the data ## Importing and exporting data with pandas A wide range of input/output formats are natively supported by pandas: * CSV, text * SQL database * Excel * HDF5 * json * html * pickle * ... ``` pd.read countries.to ``` ## Now for our case study I downloaded some of the raw data files of AirBase and included it in the repo: > station code: BETR801, pollutant code: 8 (nitrogen dioxide) ``` !head -1 ./data/BETR8010000800100hour.1-1-1990.31-12-2012 ``` Just reading the tab-delimited data: ``` data = pd.read_csv("data/BETR8010000800100hour.1-1-1990.31-12-2012", sep='\t') data.head() ``` Not really what we want. With using some more options of `read_csv`: ``` colnames = ['date'] + [item for pair in zip(["{:02d}".format(i) for i in range(24)], ['flag']*24) for item in pair] data = pd.read_csv("data/BETR8010000800100hour.1-1-1990.31-12-2012", sep='\t', header=None, na_values=[-999, -9999], names=colnames) data.head() ``` So what did we do: - specify that the values of -999 and -9999 should be regarded as NaN - specified are own column names For now, we disregard the 'flag' columns ``` data = data.drop('flag', axis=1) data ``` Now, we want to reshape it: our goal is to have the different hours as row indices, merged with the date into a datetime-index. ## Intermezzo: reshaping your data with `stack`, `unstack` and `pivot` The docs say: > Pivot a level of the (possibly hierarchical) column labels, returning a DataFrame (or Series in the case of an object with a single level of column labels) having a hierarchical index with a new inner-most level of row labels. <img src="img/stack.png" width=70%> ``` df = pd.DataFrame({'A':['one', 'one', 'two', 'two'], 'B':['a', 'b', 'a', 'b'], 'C':range(4)}) df ``` To use `stack`/`unstack`, we need the values we want to shift from rows to columns or the other way around as the index: ``` df = df.set_index(['A', 'B']) df result = df['C'].unstack() result df = result.stack().reset_index(name='C') df ``` `pivot` is similar to `unstack`, but let you specify column names: ``` df.pivot(index='A', columns='B', values='C') ``` `pivot_table` is similar as `pivot`, but can work with duplicate indices and let you specify an aggregation function: ``` df = pd.DataFrame({'A':['one', 'one', 'two', 'two', 'one', 'two'], 'B':['a', 'b', 'a', 'b', 'a', 'b'], 'C':range(6)}) df df.pivot_table(index='A', columns='B', values='C', aggfunc='count') #'mean' ``` ## Back to our case study We can now use `stack` to create a timeseries: ``` data = data.set_index('date') data_stacked = data.stack() data_stacked ``` Now, lets combine the two levels of the index: ``` data_stacked = data_stacked.reset_index(name='BETR801') data_stacked.index = pd.to_datetime(data_stacked['date'] + data_stacked['level_1'], format="%Y-%m-%d%H") data_stacked = data_stacked.drop(['date', 'level_1'], axis=1) data_stacked ``` For this talk, I put the above code in a separate function, and repeated this for some different monitoring stations: ``` import airbase no2 = airbase.load_data() ``` - FR04037 (PARIS 13eme): urban background site at Square de Choisy - FR04012 (Paris, Place Victor Basch): urban traffic site at Rue d'Alesia - BETR802: urban traffic site in Antwerp, Belgium - BETN029: rural background site in Houtem, Belgium See http://www.eea.europa.eu/themes/air/interactive/no2 # Exploring the data Some useful methods: `head` and `tail` ``` no2.head(3) no2.tail() ``` `info()` ``` no2.info() ``` Getting some basic summary statistics about the data with `describe`: ``` no2.describe() ``` Quickly visualizing the data ``` no2.plot(kind='box', ylim=[0,250]) no2['BETR801'].plot(kind='hist', bins=50) no2.plot(figsize=(12,6)) ``` This does not say too much .. We can select part of the data (eg the latest 500 data points): ``` no2[-500:].plot(figsize=(12,6)) ``` Or we can use some more advanced time series features -> next section! ## Working with time series data When we ensure the DataFrame has a `DatetimeIndex`, time-series related functionality becomes available: ``` no2.index ``` Indexing a time series works with strings: ``` no2["2010-01-01 09:00": "2010-01-01 12:00"] ``` A nice feature is "partial string" indexing, where we can do implicit slicing by providing a partial datetime string. E.g. all data of 2012: ``` no2['2012'] ``` Or all data of January up to March 2012: ``` data['2012-01':'2012-03'] ``` Time and date components can be accessed from the index: ``` no2.index.hour no2.index.year ``` ## The power of pandas: `resample` A very powerfull method is **`resample`: converting the frequency of the time series** (e.g. from hourly to daily data). The time series has a frequency of 1 hour. I want to change this to daily: ``` no2.resample('D').head() ``` By default, `resample` takes the mean as aggregation function, but other methods can also be specified: ``` no2.resample('D', how='max').head() ``` The string to specify the new time frequency: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#offset-aliases These strings can also be combined with numbers, eg `'10D'`. Further exploring the data: ``` no2.resample('M').plot() # 'A' # no2['2012'].resample('D').plot() no2.loc['2009':, 'FR04037'].resample('M', how=['mean', 'median']).plot() ``` #### Question: The evolution of the yearly averages with, and the overall mean of all stations ``` no2_1999 = no2['1999':] no2_1999.resample('A').plot() no2_1999.mean(axis=1).resample('A').plot(color='k', linestyle='--', linewidth=4) ``` # Analysing the data ## Intermezzo - the groupby operation (split-apply-combine) By "group by" we are referring to a process involving one or more of the following steps * **Splitting** the data into groups based on some criteria * **Applying** a function to each group independently * **Combining** the results into a data structure <img src="img/splitApplyCombine.png"> Similar to SQL `GROUP BY` The example of the image in pandas syntax: ``` df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'], 'data': [0, 5, 10, 5, 10, 15, 10, 15, 20]}) df df.groupby('key').aggregate('sum') # np.sum df.groupby('key').sum() ``` ## Back to the air quality data **Question: how does the *typical monthly profile* look like for the different stations?** First, we add a column to the dataframe that indicates the month (integer value of 1 to 12): ``` no2['month'] = no2.index.month ``` Now, we can calculate the mean of each month over the different years: ``` no2.groupby('month').mean() no2.groupby('month').mean().plot() ``` #### Question: The typical diurnal profile for the different stations ``` no2.groupby(no2.index.hour).mean().plot() ``` #### Question: What is the difference in the typical diurnal profile between week and weekend days. ``` no2.index.weekday? no2['weekday'] = no2.index.weekday ``` Add a column indicating week/weekend ``` no2['weekend'] = no2['weekday'].isin([5, 6]) data_weekend = no2.groupby(['weekend', no2.index.hour]).mean() data_weekend.head() data_weekend_FR04012 = data_weekend['FR04012'].unstack(level=0) data_weekend_FR04012.head() data_weekend_FR04012.plot() ``` #### Question: What are the number of exceedances of hourly values above the European limit 200 µg/m3 ? ``` exceedances = no2 > 200 # group by year and count exceedances (sum of boolean) exceedances = exceedances.groupby(exceedances.index.year).sum() ax = exceedances.loc[2005:].plot(kind='bar') ax.axhline(18, color='k', linestyle='--') ``` #### Question: Visualize the typical week profile for the different stations as boxplots. Tip: the boxplot method of a DataFrame expects the data for the different boxes in different columns) ``` # add a weekday and week column no2['weekday'] = no2.index.weekday no2['week'] = no2.index.week no2.head() # pivot table so that the weekdays are the different columns data_pivoted = no2['2012'].pivot_table(columns='weekday', index='week', values='FR04037') data_pivoted.head() box = data_pivoted.boxplot() ``` **Exercise**: Calculate the correlation between the different stations ``` no2[['BETR801', 'BETN029', 'FR04037', 'FR04012']].corr() no2[['BETR801', 'BETN029', 'FR04037', 'FR04012']].resample('D').corr() no2 = no2[['BETR801', 'BETN029', 'FR04037', 'FR04012']] ``` # Further reading - the documentation: http://pandas.pydata.org/pandas-docs/stable/ - Wes McKinney's book "Python for Data Analysis" - lots of tutorials on the internet, eg http://github.com/jvns/pandas-cookbook # What's new in pandas Some recent enhancements of the last year (versions 0.14 to 0.16): - Better integration for categorical data (`Categorical` and `CategoricalIndex`) - The same for `Timedelta` and `TimedeltaIndex` - More flexible SQL interface based on `sqlalchemy` - MultiIndexing using slicers - `.dt` accessor for accesing datetime-properties from columns - Groupby enhancements - And a lot of enhancements and bug fixes # How can you help? **We need you!** Contributions are very welcome and can be in different domains: - reporting issues - improving the documentation - testing release candidates and provide feedback - triaging and fixing bugs - implementing new features - spreading the word -> https://github.com/pydata/pandas ## Thanks for listening! Questions? - https://github.com/jorisvandenbossche - <mailto:jorisvandenbossche@gmail.com> - [@jorisvdbossche](https://twitter.com/jorisvdbossche) Slides and data: Source: https://github.com/jorisvandenbossche/2015-PyDataParis Slides presented with 'live reveal' https://github.com/damianavila/RISE
github_jupyter
<a href="https://colab.research.google.com/github/daanishrasheed/DS-Unit-2-Applied-Modeling/blob/master/DS_Sprint_Challenge_7.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> _Lambda School Data Science, Unit 2_ # Applied Modeling Sprint Challenge: Predict Chicago food inspections 🍔 For this Sprint Challenge, you'll use a dataset with information from inspections of restaurants and other food establishments in Chicago from January 2010 to March 2019. [See this PDF](https://data.cityofchicago.org/api/assets/BAD5301B-681A-4202-9D25-51B2CAE672FF) for descriptions of the data elements included in this dataset. According to [Chicago Department of Public Health — Food Protection Services](https://www.chicago.gov/city/en/depts/cdph/provdrs/healthy_restaurants/svcs/food-protection-services.html), "Chicago is home to 16,000 food establishments like restaurants, grocery stores, bakeries, wholesalers, lunchrooms, mobile food vendors and more. Our business is food safety and sanitation with one goal, to prevent the spread of food-borne disease. We do this by inspecting food businesses, responding to complaints and food recalls." #### Your challenge: Predict whether inspections failed The target is the `Fail` column. - When the food establishment failed the inspection, the target is `1`. - When the establishment passed, the target is `0`. #### Run this cell to install packages in Colab: ``` %%capture import sys if 'google.colab' in sys.modules: # Install packages in Colab !pip install category_encoders==2.* !pip install eli5 !pip install pandas-profiling==2.* !pip install pdpbox !pip install shap ``` #### Run this cell to load the data: ``` import pandas as pd train_url = 'https://drive.google.com/uc?export=download&id=13_tP9JpLcZHSPVpWcua4t2rY44K_s4H5' test_url = 'https://drive.google.com/uc?export=download&id=1GkDHjsiGrzOXoF_xcYjdzBTSjOIi3g5a' train = pd.read_csv(train_url) test = pd.read_csv(test_url) assert train.shape == (51916, 17) assert test.shape == (17306, 17) ``` ### Part 1: Preprocessing You may choose which features you want to use, and whether/how you will preprocess them. If you use categorical features, you may use any tools and techniques for encoding. _To earn a score of 3 for this part, find and explain leakage. The dataset has a feature that will give you an ROC AUC score > 0.90 if you process and use the feature. Find the leakage and explain why the feature shouldn't be used in a real-world model to predict the results of future inspections._ ### Part 2: Modeling **Fit a model** with the train set. (You may use scikit-learn, xgboost, or any other library.) Use cross-validation or do a three-way split (train/validate/test) and **estimate your ROC AUC** validation score. Use your model to **predict probabilities** for the test set. **Get an ROC AUC test score >= 0.60.** _To earn a score of 3 for this part, get an ROC AUC test score >= 0.70 (without using the feature with leakage)._ ### Part 3: Visualization Make visualizations for model interpretation. (You may use any libraries.) Choose two of these types: - Confusion Matrix - Permutation Importances - Partial Dependence Plot, 1 feature isolation - Partial Dependence Plot, 2 features interaction - Shapley Values _To earn a score of 3 for this part, make four of these visualization types._ ## Part 1: Preprocessing > You may choose which features you want to use, and whether/how you will preprocess them. If you use categorical features, you may use any tools and techniques for encoding. ``` train.head(35) n = train["Violations"].str.split(" - ", n = 1, expand = True) train.drop(columns =["Violations"], inplace = True) train['Violations'] = n[0] train['Violations'].value_counts() s = train['Violations'].str.split("|", n = 1, expand = True) train['Violations'] = s[0] train.head(1) n = test["Violations"].str.split(" - ", n = 1, expand = True) test.drop(columns =["Violations"], inplace = True) test['Violations'] = n[0] test['Facility Type'].value_counts() s = test['Violations'].str.split("|", n = 1, expand = True) test['Violations'] = s[0] train.head(1) target = 'Fail' features = ['Facility Type', 'Risk', 'Inspection Type', 'Violations'] ``` ## Part 2: Modeling > **Fit a model** with the train set. (You may use scikit-learn, xgboost, or any other library.) Use cross-validation or do a three-way split (train/validate/test) and **estimate your ROC AUC** validation score. > > Use your model to **predict probabilities** for the test set. **Get an ROC AUC test score >= 0.60.** ``` from sklearn.model_selection import train_test_split train, val = train_test_split(train, train_size=0.80, test_size=0.20, stratify=train['Fail'], random_state=42) X_train = train[features] y_train = train[target] X_val = val[features] y_val = val[target] X_test = test[features] y_test = test[target] import category_encoders as ce from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline transformers = make_pipeline( ce.OrdinalEncoder(), SimpleImputer() ) X_train_transformed = transformers.fit_transform(X_train) X_val_transformed = transformers.transform(X_val) X_val_transformed = pd.DataFrame(X_val_transformed, columns=X_val.columns) rf = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) rf.fit(X_train_transformed, y_train) print('Validation Accuracy', rf.score(X_val_transformed, y_val)) import category_encoders as ce from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline from xgboost import XGBClassifier processor = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='median') ) X_train_processed = processor.fit_transform(X_train) X_val_processed = processor.transform(X_val) eval_set = [(X_train_processed, y_train), (X_val_processed, y_val)] model = XGBClassifier(n_estimators=1000, n_jobs=-1) model.fit(X_train_processed, y_train, eval_set=eval_set, eval_metric='auc', early_stopping_rounds=10) from sklearn.metrics import roc_auc_score X_test_processed = processor.transform(X_test) class_index = 1 y_pred_proba = model.predict_proba(X_test_processed)[:, class_index] print(f'Test ROC AUC') print(roc_auc_score(y_test, y_pred_proba)) # Ranges from 0-1, higher is better ``` ## Part 3: Visualization > Make visualizations for model interpretation. (You may use any libraries.) Choose two of these types: > > - Permutation Importances > - Partial Dependence Plot, 1 feature isolation > - Partial Dependence Plot, 2 features interaction > - Shapley Values ``` %matplotlib inline from pdpbox.pdp import pdp_isolate, pdp_plot feature='Risk' encoder = transformers.named_steps['ordinalencoder'] for item in encoder.mapping: if item['col'] == feature: feature_mapping = item['mapping'] feature_mapping = feature_mapping[feature_mapping.index.dropna()] category_names = feature_mapping.index.tolist() category_codes = feature_mapping.values.tolist() isolated = pdp_isolate( model=rf, dataset=X_val_transformed, model_features=X_val.columns, feature=feature, cust_grid_points=category_codes ) fig, axes = pdp_plot(isolated, feature_name=feature, plot_lines=True, frac_to_plot=0.01) from pdpbox.pdp import pdp_interact, pdp_interact_plot features = ['Risk', 'Inspection Type'] years_grid = [0, 5, 10, 15, 20, 25, 30] interaction = pdp_interact( model=rf, dataset=X_val_transformed, model_features=X_val.columns, features=features, cust_grid_points=[category_codes, years_grid] ) pdp_interact_plot(interaction, plot_type='grid', feature_names=features); from sklearn.metrics import accuracy_score pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='mean'), RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) ) # Fit on train, score on val pipeline.fit(X_train, y_train) y_pred = pipeline.predict(X_val) print('Validation Accuracy', accuracy_score(y_val, y_pred)) from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels import seaborn as sns def plot_confusion_matrix(y_true, y_pred): labels = unique_labels(y_true) columns = [f'Predicted {label}' for label in labels] index = [f'Actual {label}' for label in labels] table = pd.DataFrame(confusion_matrix(y_true, y_pred), columns=columns, index=index) return sns.heatmap(table, annot=True, fmt='d', cmap='viridis') plot_confusion_matrix(y_val, y_pred); ```
github_jupyter
# How to Win in the Data Science Field ## A. Business Understanding This project aims to answer the question: "How does one win in the Data Science field?" To gain insight on this main inquiry, I focused on addressing the following: - Are there major differences in salary among the different data science roles? - What are the essential technical skills to do well in data science? - Does educational background play a huge part? - How much does continuous learning on online platforms help? ## B. Data Understanding For this project I have chosen to use the 2019 Kaggle ML & DS Survey raw data. I think this is a good dataset choice for the following reasons: - The Kaggle Community is the biggest data science and machine learning community, therefore would have a good representation of data scientist professionals. - It features a lot of relevant variables, from salary, demographics, to characteristics and habits of data science professionals in the community. ### Data Access and Exploration The first step is to import all the needed libraries. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import textwrap %matplotlib inline ``` We then import the dataset to be used for the analysis. ``` # Import data df = pd.read_csv('./multiple_choice_responses.csv') df.head() df.shape ``` There was a total of 19.7K data science professionals in the survey, and 246 fields corresponding to their responses to the survey. There are missing values, but we'll deal with them later depending on the analysis that will be implemented. ## C. Preparing the Data ### Cleaning the data We do some necessary filtering to the data with the following rationale: - Filtering among professionals / employed only because we are concerned about salary outcomes - Focusing among US residents only to lessen the variation in pay due to region - Focusing among professionals with salary >=30K USD only to most likely capture full-time employees ``` # Filter data among professionals only df = df[~df.Q5.isin(['Student', 'Not employed']) & df.Q5.notnull()] # Filter data among residents of the US only df = df[df.Q3.isin(['United States of America'])] # Filter data among annual salary of >=30K df = df[~df.Q10.isin(['$0-999','1,000-1,999','2,000-2,999','3,000-3,999','4,000-4,999','5,000-7,499','7,500-9,999','10,000-19,999','20,000-29,999']) & df.Q10.notnull()] # Recode some of the salary bins df.loc[df['Q10'].isin(['300,000-500,000','> $500,000']), 'Q10'] = '>= $300,000' # Shape of the dataframe df.shape ``` From these filtering, we get the final sample size of 2,013 US Data Science Professionals, earning an annual wage of >=30K USD. ### Missing Values As this analysis is highly descriptive and I will not employ any statistical modelling, I will address the missing values by simply dropping them from the computed percentages. ### Function Creation I created a few helper functions for charts to be used all throughout the analysis. Most of my charts are going to be bar plots and heatmaps. I created the functions depending on the data type (single respons and multiple response variables. ``` def barplots_single_answer(q_number, x_title, y_title, chart_title, order=None): ''' INPUT: q_number - question number for the variable of interest. It should be a single-answer question. x_title - desired title of the x-axis y_title - desired title of the y-axis chart_title - desired main title order_rows - desired sorting of the rows (will default to descending according to frequency of answers) OUTPUT: A barplot that shows the frequency in % for the variable of interest This function prepares the data for the visualization and draws the bar plot. ''' cat_values = round((df[pd.notnull(df[q_number])][q_number].value_counts()/len(df[pd.notnull(df[q_number])][q_number])) * 100,1) cat_values = cat_values.reset_index().rename(columns = {'index':q_number, q_number:'pct'}) f, ax = plt.subplots(figsize=(8,8)) sns.barplot(x = 'pct', y = q_number, data=cat_values, color='dodgerblue', order=order) ax.set_xlabel(x_title) ax.set_ylabel(y_title) plt.title(chart_title, fontsize = 14, fontweight ='bold') print(cat_values) def barplots_heatmap_single_answer(q_number, bar_chart_title, heatmap_title, order_rows = False): ''' INPUT: q_number - question number for the variable of interest. It should be a single-answer question. bar_chart_title - desired title of the frequency bar chart heatmap_title - desired title of the heatmap chart order_rows - desired sorting of the rows (will default to descending according to frequency of answers) OUTPUT: Two charts: A barplot that shows the frequency in % for the variable of interest, and a heatmap that visually correlates the variable of interest with salary range. Table reference for the percentages This function prepares the data for the visualization and provides the two visualizations specified. ''' # Value count for the variable of interest cat_values = df[pd.notnull(df[q_number])][q_number].value_counts() # Set a threshold of 20 records for category to be included in plotting, otherwise it will distort the normalized heatmap cat_values = cat_values[cat_values>=20] cat_values = round((cat_values/len(df[pd.notnull(df[q_number])][q_number])) * 100,1) if(order_rows == False): cat_values = cat_values else: cat_values = cat_values.reindex(index = order_rows) cat_values = cat_values.reset_index().rename(columns = {'index':q_number, q_number:'pct'}) # Sort order for the salary bins order_col = ['30,000-39,999','40,000-49,999','50,000-59,999','60,000-69,999','70,000-79,999', '80,000-89,999','90,000-99,999','100,000-124,999','125,000-149,999', '150,000-199,999','200,000-249,999', '250,000-299,999','>= $300,000'] y_labels = cat_values[q_number] # Crosstabs for the salary and variable of interest crosstab = pd.crosstab(df[q_number],df['Q10'], normalize='index') crosstab = crosstab.reindex(order_col, axis="columns") if(order_rows == False): crosstab = crosstab.reindex(y_labels, axis="rows") else: crosstab = crosstab.reindex(order_rows, axis="rows") # Set-up subplots fig = plt.figure(figsize=(14,6)) grid = plt.GridSpec(1, 10, wspace=10, hspace=1) plt.subplot(grid[0, :3]) # Left plot (barplot) ax1 = sns.barplot(x = 'pct', y = q_number, data=cat_values, color='dodgerblue', order=None) plt.title(bar_chart_title, fontsize = 14, fontweight ='bold') ax1.set_xlabel('Percentage %') ax1.set_ylabel('') # Text-wrapping of y-labels f = lambda x: textwrap.fill(x.get_text(), 27) ax1.set_yticklabels(map(f, ax1.get_yticklabels())) # Right plot (heatmap) plt.subplot(grid[0, 4:]) ax2 = sns.heatmap(crosstab, cmap="Blues", cbar=False) plt.title(heatmap_title, fontsize = 14, fontweight ='bold') ax2.set_xlabel('Yearly Salary') ax2.set_ylabel('') ax2.set_yticklabels(map(f, ax2.get_yticklabels())) print(cat_values) def barplots_heatmap_multi_answer(multi_question_list, bar_chart_title, heatmap_title, order_rows = False): ''' INPUT: multi_question_list - a list of fields containing the response for a multiple answer-type question bar_chart_title - desired title of the frequency bar chart heatmap_title - desired title of the heatmap chart order_rows - desired sorting of the rows (will default to descending according to frequency of answers) OUTPUT: Two charts: A barplot that shows the frequency in % for the variable of interest, and a heatmap that visually correlates the variable of interest with salary range. Table reference for the percentages This function prepares the data for the visualization and provides the two visualizations specified. ''' multi_question = multi_question_list df_store = [] for question in (multi_question): df_temp = df[question].value_counts() df_store.append(df_temp) df_multi = pd.concat(df_store) df_multi = pd.DataFrame(df_multi).reset_index().rename(columns = {'index':multi_question[0], 0:'pct'}) df_multi = df_multi[df_multi['pct']>=20] df_multi['pct'] = round(df_multi['pct']/sum(df_multi['pct']) * 100,1) if(order_rows == False): df_multi = df_multi.sort_values('pct', ascending=False) else: df_multi = df_multi.reindex(index = order_rows) # Sort order for the salary bins order_col = ['30,000-39,999','40,000-49,999','50,000-59,999','60,000-69,999','70,000-79,999', '80,000-89,999','90,000-99,999','100,000-124,999','125,000-149,999', '150,000-199,999','200,000-249,999', '250,000-299,999','>= $300,000'] y_labels = df_multi[multi_question[0]] # Crosstabs for the salary and variable of interest df_store_xtab = [] for question in (multi_question): df_temp_xtab = pd.crosstab(df[question],df['Q10'], normalize='index') df_store_xtab.append(df_temp_xtab) df_multi_xtab = pd.concat(df_store_xtab) df_multi_xtab = df_multi_xtab.reindex(order_col, axis="columns") if(order_rows == False): df_multi_xtab = df_multi_xtab.reindex(y_labels, axis="rows") else: df_multi_xtab = df_multi_xtab.reindex(order_rows, axis="rows") # Set-up subplots #fig = plt.figure(figsize=(14,6)) fig = plt.figure(figsize=(14,8)) grid = plt.GridSpec(1, 10, wspace=10, hspace=1) plt.subplot(grid[0, :3]) # Left plot (barplot) ax1 = sns.barplot(x = 'pct', y = multi_question[0], data=df_multi, color='dodgerblue', order=None) plt.title(bar_chart_title, fontsize = 14, fontweight ='bold') ax1.set_xlabel('Percentage %') ax1.set_ylabel('') # Text-wrapping of y-labels f = lambda x: textwrap.fill(x.get_text(), 27) ax1.set_yticklabels(map(f, ax1.get_yticklabels())) # Right plot (heatmap) plt.subplot(grid[0, 4:]) ax2 = sns.heatmap(df_multi_xtab, cmap="Blues", cbar=False) plt.title(heatmap_title, fontsize = 14, fontweight ='bold') ax2.set_xlabel('Yearly Salary') ax2.set_ylabel('') ax2.set_yticklabels(map(f, ax2.get_yticklabels())) print(df_multi) ``` ## D. Analysis ### Question 1: Are there major differences in salary among the different data science roles? We first look at the salary distribution of the sample. Most of the data science professionals have salaries that fall within the $100K-200K range. #### Chart 1: Salary Distribution (Q10) - Bar Chart ``` barplots_single_answer('Q10', 'Percentage %', 'Salary Range', 'Annual Salary Distribution', ['30,000-39,999','40,000-49,999','50,000-59,999','60,000-69,999','70,000-79,999', '80,000-89,999','90,000-99,999','100,000-124,999','125,000-149,999', '150,000-199,999','200,000-249,999', '250,000-299,999','>= $300,000']) ``` #### Chart 2: Data Practitioners Distribution (Q5) - Bar Chart ``` barplots_heatmap_single_answer('Q5', 'Current Data Role (%)', 'Annual Salary by Current Data Role') ``` Interpretation: - Data Scientists are heavy on the 100K-200K USD range which reflects our entire Kaggler sample. This makes sense because Data Scientist is the top profession at 34%. - There is an obvious discrepancy between a data scientist and a data analyst salary, with the former showing a heavier concentration on the 100K-200K USD range, and the latter somewhere within 60K-125K. It seems that data scientists are paid much more than analysts. - Other professions such as Statisticians and Database Engineers tend to have more variation in pay, while Data Engineers are more concentrated in the 120K-125K range. ### Question 2: What are the essential technical skills to do well in data science? While the questionnaire is very detailed in terms of the technical skills asked among the Kagglers, I decided to focus on a few main items (so as not to bore the readers): - "What programming languages do you use on a regular basis?" - From the above question, I derive how many programming languages they regularly use - Primary data analysis tools used #### Chart 3: Programming Languages Used ``` barplots_heatmap_multi_answer(['Q18_Part_1', 'Q18_Part_2', 'Q18_Part_3', 'Q18_Part_4', 'Q18_Part_5', 'Q18_Part_6', 'Q18_Part_7', 'Q18_Part_8', 'Q18_Part_9', 'Q18_Part_10', 'Q18_Part_11', 'Q18_Part_12'], 'Programming Languages Used (%)', 'Annual Salary by Programming Languages Used', order_rows = False) ``` Interpretation: - Python is the most popular language; SQL and R are also popular - Software engineering-oriented languages such as Java, C++, and C have more dense representation in the 150K-200K range. - Other noteworthy languages that relate to higher pay are Matlab, Typescript, and Bash. I also looked at the percentage of the sample who do not code at all: ``` # How many do not code at all? df['Q18_Part_11'].value_counts()/len(df)*100 ``` Only a small subset of the population does not code, which is not surprising given that these are Kagglers. I also ran an analysis to check how many programming languages do these data science professionals use: ``` lang_list = ['Q18_Part_1', 'Q18_Part_2', 'Q18_Part_3', 'Q18_Part_4', 'Q18_Part_5', 'Q18_Part_6', 'Q18_Part_7', 'Q18_Part_8', 'Q18_Part_9', 'Q18_Part_10','Q18_Part_12'] order_col = ['30,000-39,999','40,000-49,999','50,000-59,999','60,000-69,999','70,000-79,999', '80,000-89,999','90,000-99,999','100,000-124,999','125,000-149,999', '150,000-199,999','200,000-249,999', '250,000-299,999','>= $300,000'] df['Count_Languages'] = df[lang_list].apply(lambda x: x.count(), axis=1) # Group by salary range, get the average count of programming language used table_lang_salary = df[['Count_Languages','Q10']].groupby(['Q10']).mean() table_lang_salary = table_lang_salary.reindex(order_col, axis="rows").reset_index() # Average number of programming languages used table_lang_salary['Count_Languages'].mean() ``` On the average, they use 2-3 languages. But how does this correlate with salary? To answer this question, I created this bar chart: #### Chart 4: Number of Programming Languages Used ``` f, ax = plt.subplots(figsize=(5,8)) ax = sns.barplot(x='Count_Languages', y="Q10", data=table_lang_salary, color='dodgerblue') plt.title('Salary Range vs. \n How Many Programming Languages Used', fontsize = 14, fontweight ='bold') ax.set_xlabel('Avg Languages Used') ax.set_ylabel('Annual Salary Range') ``` Interpretation: Plotting the number of languages used according to salary range, we see that the number of languages used tend to increase as pay increases — up to the 125K-150K point. So yes, it may be worth learning more than 1. Apart from coding, I also looked at other tools that data science professionals use based on this question: "What is the primary tool that you use at work or school to analyze data?" #### Chart 5: Primary Data Analysis Tools ``` barplots_heatmap_single_answer('Q14', 'Primary Data Analysis Tool (%)', 'Annual Salary by Data Analysis Tool') ``` Interpretation: - Local development environments are the most popular tools with half of the sample using it. - Cloud-based software users have a large salary leverage though - those who use it appear to have a higher earning potential, most likely at 150K-200K, and even a high concentration of professionals earning more than 300K USD. - There is a large variation in pay among basic and advanced statistical software users. ### Question 3: Does educational background play a huge part? #### Chart 6. Highest level of educational attainment (Q4) - Bar chart and salary heatmap side by side ``` barplots_heatmap_single_answer('Q4', 'Highest Educational Attainment (%)', 'Annual Salary by Educational Attainment', order_rows=['Doctoral degree', 'Master’s degree', 'Professional degree', 'Bachelor’s degree', 'Some college/university study without earning a bachelor’s degree']) ``` Interpretation: - Data science professionals tend to be a highly educated group, with 72% having either a Master’s Degree or a PhD. - The salary heatmaps do not really show anything remarkable, except that Professional Degrees have a high concentration in the 150K-250K USD bracket. This group only constitutes 1.3% of the sample, hence I would say this is inconclusive. ### Question 4: How much does continuous learning on online platforms help? To answer this question, I referred to these items in the survey: - "On which platforms have you begun or completed data science courses?" - "Who/what are your favorite media sources that report on data science topics?" First, I looked at the online platforms and computed for the percentage of those who learned through this medium (excluding formal university education): ``` # Compute for Percentage of Kagglers who learned through online platforms platform_list = ['Q13_Part_1', 'Q13_Part_2', 'Q13_Part_3', 'Q13_Part_4', 'Q13_Part_5', 'Q13_Part_6', 'Q13_Part_7', 'Q13_Part_8', 'Q13_Part_9', 'Q13_Part_12'] df['Count_Platform'] = df[platform_list].apply(lambda x: x.count(), axis=1) len(df[df['Count_Platform'] > 0]) / len(df['Count_Platform']) ``` Interpretation: A stunning majority or 82% learn data science from these platforms. On the specific online platforms: #### Chart 7. Platforms where learn data science (Q13) - Bar chart and salary heatmap side by side ``` barplots_heatmap_multi_answer(['Q13_Part_1', 'Q13_Part_2', 'Q13_Part_3', 'Q13_Part_4', 'Q13_Part_5', 'Q13_Part_6', 'Q13_Part_7', 'Q13_Part_8', 'Q13_Part_9', 'Q13_Part_11', 'Q13_Part_12'], 'Platforms Used to Learn Data Science(%)', 'Annual Salary by Platforms Used') ``` Interpretation: - Coursera is by far the most popular, followed by Datacamp, Udemy, and Kaggle Courses. - Interestingly, Fast.ai skewed heavily on the higher income levels 125K-150K. - DataQuest on the other hand are much more spread over the lower and middle income levels, which suggests that beginners tend to use this site more. Apart from online courses, I also looked at other online media sources based on this question: "Who/what are your favorite media sources that report on data science topics?" #### Chart 8. Favorite Media Sources (Q12) - Bar chart and salary heatmap side by side ``` barplots_heatmap_multi_answer(['Q12_Part_1', 'Q12_Part_2', 'Q12_Part_3', 'Q12_Part_4', 'Q12_Part_5', 'Q12_Part_6', 'Q12_Part_7', 'Q12_Part_8', 'Q12_Part_9', 'Q12_Part_10', 'Q12_Part_11', 'Q12_Part_12'], 'Favorite Data Science Media Sources (%)', 'Annual Salary by Media Sources', order_rows = False) ``` Interpretation: - Blogs are most popular with 21% choosing this as their favorite data science topic source. - I did not see much pattern from the salary heatmap — most are just bunched within the 100K-200K USD range. - Curiously, Hacker News appears to have more followers on the higher end with 150K-200K salaries. ## Conclusion ### To win in the data science field (AND if you define winning as having a high pay): - Code! Learning more languages will probably help. Apart from Python and R consider adding other non-data science languages such as C++, Java, and Typescript into your toolkit. - Cloud-based technologies are worth learning. Get ready to explore those AWS, GCP, and Azure platforms for big data. - Continuously upskill and update through MOOCs and online courses, and through media such as blogs and technology news.
github_jupyter
## Section 7.0: Introduction to Plotly's Streaming API Welcome to Plotly's Python API User Guide. > Links to the other sections can be found on the User Guide's [homepage](https://plotly.com/python/userguide) Section 7 is divided, into separate notebooks, as follows: * [7.0 Streaming API introduction](https://plotly.com/python/intro_streaming) * [7.1 A first Plotly streaming plot](https://plotly.com/python/streaming_part1) Quickstart (initialize Plotly figure object and send 1 data point through a stream): >>> import plotly.plotly as py >>> from plotly.graph_objs import * >>> # auto sign-in with credentials or use py.sign_in() >>> trace1 = Scatter( x=[], y=[], stream=dict(token='my_stream_id') ) >>> data = Data([trace1]) >>> py.plot(data) >>> s = py.Stream('my_stream_id') >>> s.open() >>> s.write(dict(x=1, y=2)) >>> s.close() <hr> Check which version is installed on your machine and please upgrade if needed. ``` # (*) Import plotly package import plotly # Check plolty version (if not latest, please upgrade) plotly.__version__ ``` <hr> Plotly's Streaming API enables your Plotly plots to update in real-time, without refreshing your browser. In other words, users can *continuously* send data to Plotly's servers and visualize this data in *real-time*. For example, imagine that you have a thermometer (hooked to an Arduino for example) in your attic and you would like to monitor the temperature readings from your laptop. Plotly together with its streaming API makes this project easy to achieve. With Ploly's Streaming API: > Everyone looking at a Plotly streaming plot sees the same data updating at the same time. Like all Plotly plots, Plotly streaming plots are immediately shareable by shortlink, embedded in website, or in an IPython notebook. Owners of the Plotly plot can edit the plot with the Plotly web GUI and all viewers will see these changes live. And for the skeptical among us, *it's fast*: plots update up to 20 times per second. In this section, we present examples of how to make Plotly streaming plots. Readers looking for info about the nuts and bolts of Plotly's streaming API should refer to <a href="https://plotly.com/streaming/" target="_blank">this link</a>. So, we first import a few modules and sign in to Plotly using our credentials file: ``` # (*) To communicate with Plotly's server, sign in with credentials file import plotly.plotly as py # (*) Useful Python/Plotly tools import plotly.tools as tls # (*) Graph objects from plotly.graph_objs import * import numpy as np # (*) numpy for math functions and arrays ``` ##### What do Plotly streaming plots look like? ``` # Embed an existing Plotly streaming plot tls.embed('streaming-demos','6') # Note that the time point correspond to internal clock of the servers, # that is UTC time. ``` Data is sent in real-time. <br> Plotly draws the data in real-time. <br> Plotly's interactibility happens in real-time. ##### Get your stream tokens Making Plotly streaming plots requires no modifications to the sign in process; however, users must generate stream *tokens* or *ids*. To do so, first sign-in to <a href="https://plotly.com" target="_blank">plot.ly</a>. Once that is done, click on the *Settings* button in the upper-right corner of the page: <img src="http://i.imgur.com/RNExysW.png" style="margin-top:1em; margin-bottom:1em" /> <p style="margin-top:1.5em;,margin-bottom:1.5em">Under the <b>Stream Tokens</b> tab, click on the <b>Generate Token</b> button:</p> <img src="http://i.imgur.com/o5Uguye.png" /> And there you go, you have generated a stream token. Please note that: > You must generate one stream token per **trace** in your Plotly streaming plot. If you are looking to run this notebook with you own account, please generate 4 unique stream tokens and add them to your credentials file by entering: >>> tls.set_credentials_file(stream_ids=[ "ab4kf5nfdn", "kdf5bn4dbn", "o72o2p08y5", "81dygs4lcy" ]) where the `stream_ids` keyword argument is filled in with your own stream ids. Note that, in the above, `tls.set_credentials()` overwrites the existing stream tokens (if any) but does not clear the other keys in your credentials file such as `username` and `api_key`. Once your credentials file is updated with your stream tokens (or stream ids, a synonym), retrieve them as a list: ``` stream_ids = tls.get_credentials_file()['stream_ids'] ``` We are now ready to start making Plotly streaming plots! The content of this section has been divided into separate IPython notebooks as loading multiple streaming plots at once can cause performance slow downs on some internet connections. Here are the links to the subsections' notebooks: * [7.0 Streaming API introduction](https://plotly.com/python/intro_streaming) * [7.1 A first Plotly streaming plot](https://plotly.com/python/streaming_part1) In addition, here is a notebook of another Plotly streaming plot: * <a href="http://nbviewer.ipython.org/gist/empet/a03885a54c256a21c514" target="_blank">Streaming the Poisson Pareto Burst Process</a> by <a href="https://github.com/empet" target="_blank">Emilia Petrisor</a> <div style="float:right; \"> <img src="http://i.imgur.com/4vwuxdJ.png" align=right style="float:right; margin-left: 5px; margin-top: -10px" /> </div> <h4>Got Questions or Feedback? </h4> Reach us here at: <a href="https://community.plot.ly" target="_blank">Plotly Community</a> <h4> What's going on at Plotly? </h4> Check out our twitter: <a href="https://twitter.com/plotlygraphs" target="_blank">@plotlygraphs</a> ``` from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">')) ! pip install publisher --upgrade import publisher publisher.publish( 's7_streaming.ipynb', 'python/intro_streaming//', 'Getting Started with Plotly Streaming', 'Getting Started with Plotly Streaming', title = 'Getting Started with Plotly Streaming', thumbnail='', language='python', layout='user-guide', has_thumbnail='false') ```
github_jupyter
# Data Visualization: Rules and Guidelines > **Co-author** - [Paul Schrimpf *UBC*](https://economics.ubc.ca/faculty-and-staff/paul-schrimpf/) **Prerequisites** - [Introduction to Plotting](../scientific/plotting.ipynb) **Outcomes** - Understand steps of creating a visualization - Know when to use each of the core plots - Introductory ability to make effective visualizations ## Outline - [Data Visualization: Rules and Guidelines](#Data-Visualization:-Rules-and-Guidelines) - [Introduction](#Introduction) - [Steps to Creating Effective Charts](#Steps-to-Creating-Effective-Charts) - [Visualization Types](#Visualization-Types) - [Color in Plots](#Color-in-Plots) - [Visualization Rules](#Visualization-Rules) - [References](#References) - [Exercises](#Exercises) ``` # Uncomment following line to install on colab #! pip install qeds fiona geopandas xgboost gensim folium pyLDAvis descartes import matplotlib.colors as mplc import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import pandas as pd import statsmodels.formula.api as sm from pandas_datareader import DataReader %matplotlib inline # activate plot theme import qeds qeds.themes.mpl_style(); ``` ## Introduction An economist’s (or data scientist’s) job goes beyond simply learning new things using data and theory. Learning these new things is meant to help economists or data scientists communicate these ideas to others, whether the medium is an academic paper or a business meeting. One of the most effective mediums of communication is visualization. Well-done visualizations can help your audience remember your message. They accomplish this through at least two main channels: 1. Psychology researchers have observed [*picture superiority*](https://en.wikipedia.org/wiki/Picture_superiority_effect): the fact that images are more likely to be remembered than words. While the reasons and extent of the effect are debated, the consensus view is that the effect exists. How large might this effect be? In a paper by Defeyter, Russo, and McPartlin (2009), the authors found that participants were able to identify pictures they had previously studied for approximately 500 ms each with 75-85% accuracy but words with only a 55-65% accuracy. 1. Data visualizations help people walk through the logic you used to build the chart, allowing them to reason through the argument and thus makes your claim more convincing. In this lecture, we will discuss the process of creating a data visualization, ways to best ensure successfully communication, and some general design guidelines. Along the way, you will be introduced to many features of `matplotlib` that were not discussed in the introductory lecture. We won’t discuss most of these features, but we encourage you to read more in the [online documentation](https://matplotlib.org/contents.html) if you have questions. ## Steps to Creating Effective Charts Before we begin discussions of specific recommendations, it is helpful to agree on the goal of a data visualization and a process that can be used to accomplish the goal. As mentioned in the introduction, the purpose of a visualization is to facilitate the communication of a message or idea. We have found the following steps to be useful for achieving this goal: 1. Identify the message. 1. Describe your visualization. 1. Create a draft of the visualization (and verify your data!). 1. Fine tune the visualization details. After discussing the role research plays in data visualization, we will use an example to provide deeper context for the remaining steps. **Step 0: Research** Before we proceed, note that prior to reaching this process, you will have spent a significant amount of time exploring the data and thinking about your overall message. In fact, during the research step, you will almost certainly produce visualizations to help yourself understand the data. These visualizations can highlight outliers or unlikely combinations of variables. For example, NYC publishes data on taxi pickups and dropoffs. One might expect tips to be somewhat independent of whether someone pays cash or credit, but the 75th percentile tip for cash payers is 0! Because it’s unlikely that cash payers choose not to tip, one likely explanation is a reporting issue in the data collection. The steps and guidelines that follow may be helpful in the research process, but refining each of your exploratory visualizations to a publishable version is not practical. Some of these recommendations will be specific to creating a visualization after you understand the story you’re telling. ### Example The output of this example will be a reproduction of a visualization from [this NYT article](https://www.nytimes.com/2019/01/11/upshot/big-cities-low-skilled-workers-wages.html). This NYT article is based on research done by David Autor <sup>[1](#ely)</sup> , an economist at MIT, and his co-authors. Autor’s research investigates the observable changes over time between work opportunities in rural and urban locations in the United States. This particular graph explores how both college-educated workers and non-college-educated workers were able to find higher-paying jobs by working in urban areas in the 20th century. More recently, this *city wage premium* is still apparent for those with college educations. However, for those without a college education, it has disappeared. #### Identify the Message The first step to creating a visualization might feel a little obvious, but is the most important step. If you fail to choose a concise message, then you won’t be able to clearly communicate the idea. In this example, we want people to be able to answer the question, “What happened to the rural/urban wage gap for non-college-educated workers since the 1950s?”. Part of what makes the answer interesting is that the wage gap changes are unique to non-college-educated workers; we will want to display changes in the wage gap for college-educated workers as well. #### Visualize Choosing the type of visualization that best illustrates your point is an important skill to develop. Using the wrong type of visualization can inhibit the flow of information from the graph to your audience’s brain. In our case, we need to display the relationship between population density (our measure of rural/urban) and wages for different years and education levels. Since the wage gap will be the main focus, we want to choose a visualization that highlights this aspect of the data. Scatter plots are one of the most effective ways to demonstrate the relationship of two variables. We will place the log of population density on the x-axis and the log of wages on the y-axis. We will then need to find a way to demonstrate this for different years and education levels. One natural solution is to demonstrate one of these variables using color and the other using different subplots. In the original article, they chose to highlight differences in college education using color and time using subplots. #### Visualization Draft Drafting an early version of your visualization without concerning yourself about its aesthetics allows you to think about whether it is able to answer the proposed question. Sometimes you’ll get to this step and realize that you need to go back to one of the previous steps… It’s ok to scrap what you have and restart at square one. In fact, you will frequently do this, no matter how much experience you’ve developed. In our own work, we’ve found that it’s not uncommon to discard ten or more versions of a graph before settling on a draft we are happy with. Below, we create a draft of our plot. ``` # Read in data df = pd.read_csv("https://datascience.quantecon.org/assets/data/density_wage_data.csv") df["year"] = df.year.astype(int) # Convert year to int def single_scatter_plot(df, year, educ, ax, color): """ This function creates a single year's and education level's log density to log wage plot """ # Filter data to keep only the data of interest _df = df.query("(year == @year) & (group == @educ)") _df.plot( kind="scatter", x="density_log", y="wages_logs", ax=ax, color=color ) return ax # Create initial plot fig, ax = plt.subplots(1, 4, figsize=(16, 6), sharey=True) for (i, year) in enumerate(df.year.unique()): single_scatter_plot(df, year, "college", ax[i], "b") single_scatter_plot(df, year, "noncollege", ax[i], "r") ax[i].set_title(str(year)) ``` <a id='exercise-0'></a> > See exercise 1 in the [*exercise list*](#exerciselist-0) ``` # Your code here ``` #### Fine-tune Great! We have now confirmed that our decisions up until this point have made sense and that a version of this graphic can successfully convey our message. The last step is to clean the graph. We want to ensure that no features detract or distract from our message. Much of the remaining lecture will be dedicated to this fine-tuning, so we will post-pone presenting the details. However, the code we use to create the best version of this graphic is included below. ``` # Read in data df = pd.read_csv("https://datascience.quantecon.org/assets/data/density_wage_data.csv") df["year"] = df.year.astype(int) # Convert year to int def single_scatter_plot(df, year, educ, ax, color): """ This function creates a single year's and education level's log density to log wage plot """ # Filter data to keep only the data of interest _df = df.query("(year == @year) & (group == @educ)") _df.plot( kind="scatter", x="density_log", y="wages_logs", ax=ax, color=color ) return ax # Create initial plot fig, ax = plt.subplots(1, 4, figsize=(16, 6)) colors = {"college": "#1385ff", "noncollege": "#ff6d13"} for (i, year) in enumerate(df.year.unique()): single_scatter_plot(df, year, "college", ax[i], colors["college"]) single_scatter_plot(df, year, "noncollege", ax[i], colors["noncollege"]) ax[i].set_title(str(year)) bgcolor = (250/255, 250/255, 250/255) fig.set_facecolor(bgcolor) for (i, _ax) in enumerate(ax): # Label with words if i == 0: _ax.set_xlabel("Population Density") else: _ax.set_xlabel("") # Turn off right and top axis lines _ax.spines['right'].set_visible(False) _ax.spines['top'].set_visible(False) # Don't use such a white background color _ax.set_facecolor(bgcolor) # Change bounds _ax.set_ylim((np.log(4), np.log(30))) _ax.set_xlim((0, 10)) # Change ticks xticks = [10, 100, 1000, 10000] _ax.set_xticks([np.log(xi) for xi in xticks]) _ax.set_xticklabels([str(xi) for xi in xticks]) yticks = list(range(5, 32, 5)) _ax.set_yticks([np.log(yi) for yi in yticks]) if i == 0: _ax.set_yticklabels([str(yi) for yi in yticks]) _ax.set_ylabel("Average Wage") else: _ax.set_yticklabels([]) _ax.set_ylabel("") ax[0].annotate("College Educated Workers", (np.log(75), np.log(14.0)), color=colors["college"]) ax[0].annotate("Non-College Educated Workers", (np.log(10), np.log(5.25)), color=colors["noncollege"]); ``` ## Visualization Types You have seen many kinds of visualizations throughout your life. We discuss a few of the most frequently used visualization types and how they describe data below. For a more complete list of visualization types, see the Duke library’s [data visualization guide](https://guides.library.duke.edu/datavis/vis_types). ### Scatter Plots Scatter plots can be used in various ways. They are frequently used to show how two variables are related to one another or compare various observations based on two variables. [This article](https://qz.com/1235712/the-origins-of-the-scatter-plot-data-visualizations-greatest-invention/) about the scatter plot is a good read. One strength of a scatter plot is that its simplicity allows the data to speak for itself. A plot of two variables allows viewers to immediately see whether the variables are linearly related, quadratically related, or maybe not related at all. We have already seen an example of a scatter plot which shows the relationship between two variables. Below, we demonstrate how it can be used to compare. ``` cities = [ "San Francisco", "Austin", "Las Vegas", "New York", "Seattle", "Pittsburgh", "Detroit", "Fresno", "Phoenix", "Orlando", "Atlanta", "Madison" ] unemp_wage = np.array([ [2.6, 39.89], [2.9, 29.97], [4.6, 24.38], [3.9, 33.09], [3.9, 40.11], [4.2, 27.98], [4.1, 28.41], [7.1, 22.96], [4.5, 27.42], [3.0, 21.47], [3.6, 25.19], [2.2, 29.48] ]) df = pd.DataFrame(unemp_wage, index=cities, columns=["Unemployment", "Wage"]) fig, ax = plt.subplots() df.plot(kind="scatter", x="Unemployment", y="Wage", ax=ax, s=25, color="#c90000") # Add annotations for (i, row) in df.iterrows(): city = row.name if city in ["San Francisco", "Madison"]: offset = (-35, -10.5) elif city in ["Atlanta", "Phoenix", "Madison"]: offset = (-25, -12.5) elif city in ["Detroit"]: offset = (-38, 0) elif city in ["Pittsburgh"]: offset = (5, 0) else: offset = (5, 2.5) ax.annotate( city, xy=(row["Unemployment"], row["Wage"]), xytext=offset, textcoords="offset points" ) bgcolor = (250/255, 250/255, 250/255) fig.set_facecolor(bgcolor) ax.set_facecolor(bgcolor) ax.set_xlim(0, 10) ax.set_ylim(20, 45) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ``` ### Line Plots Line plots are best used to either show how a variable evolves over time or to demonstrate the relationship between variables. Note: it differs from scatter plots in the way it displays relationships between variables. A line plot is restricted to displaying a line, so you cannot just draw a line between all of your datapoints. Instead, before drawing the line, you must fit some kind of statistical model that can show how one variable changes as the other changes. Below, we add regression lines which estimate the relationship between population density and wages to our college/non-college urban wage premium plot. In fact, Dr. Autor’s original slides contain regression lines, but the New York Times chose to remove them. ``` from sklearn.linear_model import LinearRegression # Read in data df = pd.read_csv("https://datascience.quantecon.org/assets/data/density_wage_data.csv") df["year"] = df.year.astype(int) # Convert year to int def single_scatter_plot(df, year, educ, ax, color): """ This function creates a single year's and education level's log density to log wage plot """ # Filter data to keep only the data of interest _df = df.query("(year == @year) & (group == @educ)") _df.plot( kind="scatter", x="density_log", y="wages_logs", ax=ax, color=color ) lr = LinearRegression() X = _df["density_log"].values.reshape(-1, 1) y = _df["wages_logs"].values.reshape(-1, 1) lr.fit(X, y) x = np.linspace(2.0, 9.0).reshape(-1, 1) y_pred = lr.predict(x) ax.plot(x, y_pred, color=color) return ax # Create initial plot fig, ax = plt.subplots(1, 4, figsize=(16, 6)) colors = {"college": "#1385ff", "noncollege": "#ff6d13"} for (i, year) in enumerate(df.year.unique()): single_scatter_plot(df, year, "college", ax[i], colors["college"]) single_scatter_plot(df, year, "noncollege", ax[i], colors["noncollege"]) ax[i].set_title(str(year)) bgcolor = (250/255, 250/255, 250/255) fig.set_facecolor(bgcolor) for (i, _ax) in enumerate(ax): # Label with words if i == 0: _ax.set_xlabel("Population Density") else: _ax.set_xlabel("") # Turn off right and top axis lines _ax.spines['right'].set_visible(False) _ax.spines['top'].set_visible(False) # Don't use such a white background color _ax.set_facecolor(bgcolor) # Change bounds _ax.set_ylim((np.log(4), np.log(30))) _ax.set_xlim((0, 10)) # Change ticks xticks = [10, 100, 1000, 10000] _ax.set_xticks([np.log(xi) for xi in xticks]) _ax.set_xticklabels([str(xi) for xi in xticks]) yticks = list(range(5, 32, 5)) _ax.set_yticks([np.log(yi) for yi in yticks]) if i == 0: _ax.set_yticklabels([str(yi) for yi in yticks]) _ax.set_ylabel("Average Wage") else: _ax.set_yticklabels([]) _ax.set_ylabel("") ax[0].annotate("College Educated Workers", (np.log(75), np.log(14.0)), color=colors["college"]) ax[0].annotate("Non-College Educated Workers", (np.log(10), np.log(5.25)), color=colors["noncollege"]) ``` ### Bar Charts Bar charts are mostly used to display differences for a variable between groups though they can also be used to show how a variable changes over time (which in some ways, is just showing a difference as grouped by time…). Bar charts show the differences between these groups using the length of each bar, so that comparing the different groups is straightforward. In the example below, we show a bar chart of how the unemployment rate differs across several cities in the United States. ``` cities = [ "San Francisco", "Austin", "Las Vegas", "New York", "Seattle", "Pittsburgh", "Detroit", "Fresno", "Phoenix", "Orlando", "Atlanta", "Madison" ] unemp_wage = np.array([ [2.6, 39.89], [2.9, 29.97], [4.6, 24.38], [3.9, 33.09], [3.9, 40.11], [4.2, 27.98], [4.1, 28.41], [7.1, 22.96], [4.5, 27.42], [3.0, 21.47], [3.6, 25.19], [2.2, 29.48] ]) df = pd.DataFrame(unemp_wage, index=cities, columns=["Unemployment", "Wage"]) df = df.sort_values(["Unemployment"], ascending=False) fig, ax = plt.subplots() df["Unemployment"].plot(kind="barh", ax=ax, color="#1b48fc") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_title("Unemployment Rate in US Cities") ``` ### Histograms Histograms display the approximate distribution of a single variable. They can be particularly important when your variables are not distributed normally since we typically think of means and variances in terms of the normal distribution. In the example below, we show a histogram of GDP growth rates over the period 1948 - 2019. Our histogram indicates this variable is approximately normally distributed. ``` # GDP quarterly growth gdp = DataReader("GDP", "fred", 1948, 2019).pct_change().dropna() gdp = gdp * 100 fig, ax = plt.subplots() gdp.plot( kind="hist", y="GDP", color=(244/255, 77/255, 24/255), bins=23, legend=False, density=True, ax=ax ) ax.set_facecolor((0.96, 0.96, 0.96)) fig.set_facecolor((0.96, 0.96, 0.96)) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_title("US GDP Growth from 1948-2019") ``` ## Color in Plots Choosing colors for your plots is not always a straightforward task. Visualization expert Edward Tufte <https://www.edwardtufte.com/tufte/> wrote, > … Avoiding catastrophe becomes the first principle in bringing color to information: Above all, do no harm ([*Envisioning Information*](https://www.edwardtufte.com/tufte/books_ei) by Edward Tufte) So how do we “do no harm”? ### Hue Saturation Lightness We will use the [Hue Saturation Value](https://en.wikipedia.org/wiki/HSL_and_HSV) (HSV) paradigm as a way to formalize our discussion of colors. - **Hue**: This represents the share of each of the primary colors (red, green, blue) as angles around a circle. The hue begins with red at 0 degrees, green at 120 degrees, and blue at 240 degrees (Note: matplotlib converts these back into numbers between 0 and 1 by dividing by 360). Angles between these colors are mixes of the primary colors. - **Saturation**: Denotes how rich the color is using numbers between 0 and 1. At full saturation (saturation is 1), the color is as rich as possible. At saturation 0, the color has no color and is approximately a projection of the color into grayscale (Note that this is not exactly true). - **Value**: Denotes how dark the color is using numbers between 0 and 1. We view this as how much black has been added to a color. If a color has value 0, then it is as dark as possible (the color black). If the color has value 1 then it has no black and is just the original color. The way in which HSV covers the color space is demonstrated in the following figure. <img src="https://datascience.quantecon.org/assets/_static/visualization_files/HSV_color_solid_cylinder_saturation_gray.png" alt="HSL_cylinder.png" style=""> Image attribution: By [SharkD](https://commons.wikimedia.org/w/index.php?curid=9801673). Below, we demonstrate how colors change as we move hue/saturation/value one at a time. ``` def color_swatches(colors): ncolors = len(colors) fig, ax = plt.subplots(figsize=(ncolors*2, 2)) for (start_x, color) in enumerate(colors): color_rect = patches.Rectangle((start_x, 0), 1, 1, color=color) ax.add_patch(color_rect) ax.set_xlim(0, len(colors)) ax.set_ylim(0, 1) ax.set_yticks([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_xticklabels([]) return fig # Vary hue colors = [mplc.hsv_to_rgb((i/360, 1, 1)) for i in np.linspace(0, 360, 6)] fig = color_swatches(colors) fig.suptitle("Varying Hue") # Vary saturation colors = [mplc.hsv_to_rgb((0, i, 1)) for i in np.linspace(0, 1, 5)] fig = color_swatches(colors) fig.suptitle("Varying Saturation") # Vary value colors = [mplc.hsv_to_rgb((0, 1, i)) for i in np.linspace(0, 1, 5)] fig = color_swatches(colors) fig.suptitle("Varying Value") ``` ### Color Palettes A good color palette will exploit aspects of hue, saturation, and value to emphasize the information in the data visualization. For example, for qualitatively different groups (where we just want to identify separate groups which have no quantitative relationships between them), one could fix the saturation and value then draw $ N $ evenly spaced values from hue space. However, creating a good color palette sometimes requires more nuance than can be attributed to rules of thumb. Luckily, matplotlib and other Python packages can help us choose good color palettes. Often, relying on these pre-built color palettes and themes is better than than creating your own. We can get a list of all of the color palettes (referred to as colormaps by matplotlib) included with matplotlib by doing: ``` print(plt.colormaps()) ``` The [matplotlib documentation](https://matplotlib.org/tutorials/colors/colormaps.html) differentiates between colormaps used for varying purposes. Colormaps are often split into several categories based on their function (see, e.g., [Moreland]): - Sequential: incrementally change lightness and often saturation of color, generally using a single hue; should be used for representing information that has ordering. - Diverging: change lightness and possibly saturation of two different colors that meet in the middle at an unsaturated color; should be used when the information being plotted has a critical middle value, such as topography or when the data deviates around zero. - Cyclic: change lightness of two different colors that meet in the middle and beginning/end at an unsaturated color; should be used for values that wrap around at the endpoints, such as phase angle, wind direction, or time of day. - Qualitative: often are miscellaneous colors; should be used to represent information which does not have ordering or relationships. Most of the examples we have used so far can use qualitative colormaps because they are simply meant to distinguish between different variables/observations and not say something about how they differ. Additionally, three other sources of information on colors and color palettes are: - The [seaborn documentation](https://seaborn.pydata.org/tutorial/color_palettes.html). - A [talk](https://www.youtube.com/watch?v=xAoljeRJ3lU) given at the Scipy conference in 2015 by Nathaniel Smith. - A [website](https://colorusage.arc.nasa.gov/graphics_page_design.php) literally put together by “rocket scientists” at NASA. ### Do No Harm Now that we have a little background that we can use as a common language, we can proceed with discussing how we can use color effectively. #### Sometimes Value is More Effective than Hue Sometimes, in a graph with many lines, using the same color with different values is a more effective way to highlight differences than using different colors. Compare the following example, which is a modification of an example by Larry Arend, Alex Logan, and Galina Havin’s [graphics website](https://colorusage.arc.nasa.gov/graphics_page_design.php) (the NASA one we linked above). ``` def confusing_plot(colors): c1, c2, c3 = colors fig, ax = plt.subplots() x1 = np.linspace(0.2, 0.9, 5) x2 = np.linspace(0.3, 0.8, 5) ax.text(0.4, 0.10, "Not Important", color=c3, fontsize=15) ax.text(0.25, 0.25, "Not Important", color=c3, fontsize=15) ax.text(0.5, 0.70, "Not Important", color=c3, fontsize=15) ax.plot(x1, 1.25*x1 - 0.2, color=c3, linewidth=2) ax.plot(x1, 1.25*x1 + 0.1, color=c3, linewidth=2) ax.plot(x1, 0*x1 + 0.3, color=c3, linewidth=2) ax.plot(x2, 0.15*x1 + 0.4, color=c2, linewidth=3) ax.plot(x1, -x1 + 1.2, color=c2, linewidth=3) ax.plot(x1, -x1 + 1.25, color=c2, linewidth=3) ax.text(0.10, 0.5, "Second order", color=c2, fontsize=22) ax.text(0.5, 0.35, "Second order", color=c2, fontsize=22) ax.text(0.40, 0.65, "Second order", color=c2, fontsize=22) ax.plot(x2, 0.25*x1 + 0.1, color=c1, linewidth=5) ax.text(0.05, 0.4, "Important", color=c1, fontsize=34) ax.set_xlim(0, 1) ax.set_ylim(0, 1) return fig # All black colors = [mplc.hsv_to_rgb((0, 1, x)) for x in [0.0, 0.0, 0.0]] fig = confusing_plot(colors) # Vary the hues colors = [mplc.hsv_to_rgb((x, 1, 1)) for x in [0.0, 0.33, 0.66]] fig = confusing_plot(colors) # Vary the values colors = [mplc.hsv_to_rgb((0, 0, x)) for x in [0.00, 0.35, 0.7]] fig = confusing_plot(colors) ``` In our opinion, the last one with no color is actually the most readable. The point of this exercise is **not** to not use color in your plots, but rather to encourage you to think about whether hue or value will be more effective in communicating your message. #### Carelessness with Value Can Make Grayscale Impossible to Read Recall that driving the saturation to 0 is approximately equivalent to projecting the colors onto grayscale. Well, if you aren’t careful in choosing your colors, then they may have the same projected values and become unidentifiable once converted to grayscale. This code is based on an [example](https://matplotlib.org/gallery/statistics/barchart_demo.html#barchart-demo) from the matplotlib documentation. ``` n_groups = 5 means_men = (20, 35, 30, 35, 27) means_women = (25, 32, 34, 20, 25) fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.35 color_men = mplc.hsv_to_rgb((0.66, 0.35, 0.9)) rects1 = ax.bar( index, means_men, bar_width, color=color_men, label='men' ) color_women = mplc.hsv_to_rgb((0.10, 0.65, 0.85)) rects2 = ax.bar( index + bar_width, means_women, bar_width, color=color_women, label='women' ) ax.set_xlabel('group') ax.set_ylabel('scores') ax.set_title('scores by group and gender') ax.set_xticks(index + bar_width / 2) ax.set_xticklabels(('a', 'b', 'c', 'd', 'e')) ax.legend() fig.tight_layout() ``` And here is the same image converted to grayscale. <img src="https://datascience.quantecon.org/assets/_static/visualization_files/bar_grayscale.png" alt="bar_grayscale.png" style=""> The image below, from [this flowingdata blog entry](https://flowingdata.com/2012/11/09/incredibly-divided-nation-in-a-map), shows what happens when you don’t check your colors… Don’t do this. <img src="https://datascience.quantecon.org/assets/_static/visualization_files/Divided-nation.jpg" alt="Divided-nation.jpg" style=""> Warm colors (colors like red, yellow, and orange) often appear lighter than cool colors (colors like blue, green and purple) when converted to grayscale even when they have similar values. Sometimes to know whether colors are different enough, you just have to test it out. #### Use Color to Draw Attention If you are displaying information about various groups but are really only interested in how one group differs from the others, then you should choose several close-together hues to represent the less important groups and a distinct color to display the group of interest. ``` fig, ax = plt.subplots() npts = 50 x = np.linspace(0, 1, npts) np.random.seed(42) # Set seed for reproducibility y1 = 1.20 + 0.75*x + 0.25*np.random.randn(npts) y2 = 1.35 + 0.50*x + 0.25*np.random.randn(npts) y3 = 1.40 + 0.65*x + 0.25*np.random.randn(npts) y4 = 0.15 + 3.0*x + 0.15*np.random.randn(npts) # Group of interest colors = [mplc.hsv_to_rgb((x, 0.4, 0.85)) for x in [0.40, 0.50, 0.60]] colors.append(mplc.hsv_to_rgb((0.0, 0.85, 1.0))) for (y, c) in zip([y1, y2, y3, y4], colors): ax.scatter(x=x, y=y, color=c, s=36) ax.text(0.25, 0.5, "Group of Interest", color=colors[-1]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ``` <a id='exercise-1'></a> > See exercise 2 in the [*exercise list*](#exerciselist-0) #### Don’t Use Color to Differentiate Small Objects Color is a great differentiator when there is enough of the colored object to see… However, when the objects become too small, differentiating between colors, no matter how distinct, becomes quite difficult. Below is the same plot as we had above, but we have made the scatter plot’s points smaller. ``` fig, ax = plt.subplots() npts = 50 x = np.linspace(0, 1, npts) np.random.seed(42) # Set seed for reproducibility y1 = 1.20 + 0.75*x + 0.25*np.random.randn(npts) y2 = 1.35 + 0.50*x + 0.25*np.random.randn(npts) y3 = 1.40 + 0.65*x + 0.25*np.random.randn(npts) y4 = 0.15 + 3.0*x + 0.15*np.random.randn(npts) # Group of interest colors = [mplc.hsv_to_rgb((x, 0.4, 0.85)) for x in [0.40, 0.50, 0.60]] colors.append(mplc.hsv_to_rgb((0.0, 0.85, 1.0))) for (y, c) in zip([y1, y2, y3, y4], colors): ax.scatter(x=x, y=y, color=c, s=1) ax.text(0.25, 0.5, "Group of Interest", color=colors[-1]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ``` It becomes harder to read, but because the red is so much darker than some of the other colors, finding the group of interest is still possible (a lesson to be learned here!). #### Colors’ Connotations Some colors have connotations. Using colors to mean the opposite of what they’re usually used for can be confusing. For example, using red to denote positive profits and black to denote negative profits would be a poor color choice because red is often associated with losses and black is associated with profits. ``` df = pd.DataFrame( {"profits": [1.5, 2.5, 3.5, -6.7, -2.0, 1.0]}, index=[2005, 2006, 2007, 2008, 2009, 2010] ) fig, ax = plt.subplots() colors = ["k" if x < 0 else "r" for x in df["profits"].values] bars = ax.bar(np.arange(len(colors)), df["profits"].values, color=colors, alpha=0.8) ax.hlines(0, -1.0, 6.0) ax.set_xticklabels(df.index) ax.set_xlim(-0.5, 5.5) ax.set_title("Profits for Company X") ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ``` This plot becomes much more intuitive by using red for negative values. ``` fig, ax = plt.subplots() colors = ["r" if x < 0 else "k" for x in df["profits"].values] bars = ax.bar(np.arange(len(colors)), df["profits"].values, color=colors, alpha=0.8) ax.hlines(0, -1.0, 6.0) ax.set_xticklabels(df.index) ax.set_xlim(-0.5, 5.5) ax.set_title("Profits for Company X") ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ``` #### Accounting for Color Blindness Nearly 1 in 10 men have some form of color blindness. The most prevalent form makes differentiating between red and green difficult. So, besides making your plots feel “Christmas-themed”, using both red and green to illustrate differences in a plot can often make your visualization difficult for some to follow. Some Python libraries allow you to simulate different forms of color blindness or choose sensible defaults for colors. We recommend viewing the documentation for [colorspacious](https://colorspacious.readthedocs.io/en/latest/tutorial.html#simulating-colorblindness) and [viscm](https://github.com/matplotlib/viscm). ## Visualization Rules We have already discussed some guidelines for color. We will now discuss some guidelines for which elements to include and how to structure your graphs. Violating each of these may make sense in particular situations, but please have a good reason (and one you can explain when someone points out what you’ve done). The main theme for these guidelines will be to keep the plot as simple as possible so that your readers can get the clearest understanding of your story. Many people try too hard to make their plot eye-catching, and in the process, they destroy the message in the graph. Graphs should be a simple as possible, but not simpler. We will discuss some guidelines that we feel are most abused, but many very good books have been written on this subject. Some books that we have found extremely instructive are: 1. *Visual Display of Quantitative Information* by Edward Tufte. 1. *The Wall Street Journal Guide to Information Graphics: The Dos and Don’ts of Presenting Data, Facts, and Figures* by Dona M Wong. 1. *The Functional Art: An introduction to information graphics and visualization* by Alberto Cairo. Some blogs that we think are useful for seeing well-done visualizations are: 1. Flowing Data: [https://flowingdata.com/](https://flowingdata.com/) 1. Story Telling with Data: [http://www.storytellingwithdata.com/](http://www.storytellingwithdata.com/) 1. Visualizing Data: [http://www.visualisingdata.com/](http://www.visualisingdata.com/) 1. Junk Charts: [https://junkcharts.typepad.com/](https://junkcharts.typepad.com/) As you begin to create more visualizations in your work, we recommend reading these books and blogs. Seeing how others display their information will ensure that when you run into interesting problems in the future, you’ll have a well of knowledge that you can call upon. In fact, one friend of ours takes this very seriously. He keeps an organized binder of graphics that he has seen and likes. He reads this binder, sometimes for hours, when he is thinking about how to communicate messages for his presentations. A couple last links to specific articles we enjoyed: - [This Financial Times article](https://ig.ft.com/science-of-charts) is a great exercise to demonstrate how choice of graph type can affect a visualizations interpretability. - [This article](https://towardsdatascience.com/data-visualization-best-practices-less-is-more-and-people-dont-read-ba41b8f29e7b) does an exceptional job at redesigning graphics that were originally poorly done. - [Duke library data visualization guide](https://guides.library.duke.edu/datavis/topten) has a few concise rules worth reviewing. ### Bar Plot Recommendations In Dona Wong’s book, she advises against using *zebra patterns*. ``` df = pd.DataFrame( { "Unemployment Rate": [5.20, 5.67, 9.20, 4.03, 3.80], "Pension Expenditure (% of GDP)": [4.18, 4.70, 13.90, 6.24, 7.06], "Social Welfare Expenditure (% of GDP)": [7.42, 9.84, 19.72, 12.98, 14.50], "Highest Tax Rate": [47, 33, 59.6, 50, 39.6] }, index = ["Australia", "Canada", "France", "UK", "USA"] ) def create_barplot(df, colors): fig, ax = plt.subplots(figsize=(14, 6)) df.T.plot(kind="bar", color=colors, ax=ax, edgecolor="k", rot=0) ax.legend(bbox_to_anchor=(0, 1.02, 1.0, 1.02), loc=3, mode="expand", ncol=5) ax.set_xticklabels(df.columns, fontsize=6) return fig ``` Instead, she proposes using different shades of the same color (ordered from lightest to darkest!). ``` colors = [ (0.902, 0.902, 0.997), (0.695, 0.695, 0.993), (0.488, 0.488, 0.989), (0.282, 0.282, 0.985), (0.078, 0.078, 0.980) ] create_barplot(df, colors); ``` Notice that we put a legend at the top and maintain the same order as kept in the bars. Additionally, the general consensus is that starting bar plots at any number besides 0 is a misrepresentation of the data. Always start your bar plots at 0! An example of how starting at a non-zero number is misleading can be seen below and was originally from the [flowingdata blog](https://flowingdata.com/2012/08/06/fox-news-continues-charting-excellence). First, we look at a reproduction of the originally displayed image. ``` fig, ax = plt.subplots() ax.bar([0, 1], [35, 39.6], color="orange") ax.set_xticks([0, 1]) ax.set_xticklabels(["Now", "Jan 1, 2013"]) ax.set_ylim(34, 42) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ax.set_title("IF BUSH TAX CUTS EXPIRE\nTop Tax Rate") ``` This looks like a big difference! In fact, your eyes are telling you that taxes will increase by a factor of 5 if the tax cuts expire. If we start this same bar plot at 0, the chart becomes much less striking and tells you that the percentage increase in the top tax rate is only 5-10 percent. ``` fig, ax = plt.subplots() ax.bar([0, 1], [35, 39.6], color="orange") ax.set_xticks([0, 1]) ax.set_xticklabels(["Now", "Jan 1, 2013"]) ax.set_ylim(0, 42) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ax.set_title("IF BUSH TAX CUTS EXPIRE\nTop Tax Rate") ``` We also have opinions about what type of person uses all caps, but we’ll keep that to ourselves for now. ### Pie Plots As a general rule, you should avoid pie plots. When comparing groups, your reader can more easily measure the heights on a bar graph than determine the size of the angles in a pie chart. Let’s look at an example of this below. ``` df = pd.DataFrame( {"values": [5.5, 4.5, 8.4, 4.75, 2.5]}, index=["Bob", "Alice", "Charlie", "Susan", "Jessie"] ) colors = [mplc.hsv_to_rgb((0.66, 0.8, 0.9))]*2 colors += [mplc.hsv_to_rgb((0.05, 0.6, 0.9))] colors += [mplc.hsv_to_rgb((0.66, 0.8, 0.9))]*2 fig, ax = plt.subplots(1, 2) df.plot(kind="barh", y="values", ax=ax[0], legend=False, color=colors) df.plot(kind="pie", y="values", ax=ax[1], legend=False, colors=colors, startangle=0) ax[0].spines['right'].set_visible(False) ax[0].spines['top'].set_visible(False) ax[1].set_ylabel("") fig.suptitle("How many pieces of pie eaten") ``` Using the pie chart, can you tell who ate more pie Alice or Susan? How about with the bar chart? The pie chart can sometimes be used to illustrate whether one or two groups is much larger than the others. If you were making a case that Charlie ate too much of the pie and should pay more than an equal split, then a pie chart works (though a bar plot also works…). If you wanted to make a more precise point, then you might consider going with a bar plot instead. ### Simplify Line Plots We’ve tried to emphasize repeatedly that simplifying your visualizations is essential to being able to communicate your message. We do it again here and will do it a few more times after this… Don’t try and fit too much information into a single line plot. We see people do this very frequently – remember that a visualization should have ONE main message. Do not pollute your message with extra information. In our example using World Bank data below, we will show that Japan’s population is aging faster than that of many other economically successful countries. We show this using the age dependency ratio, which is the number of individuals aged 65+ divided by the number of individuals who are 15-64, for each country over time. A high age dependency ratio means that the government will have a smaller tax base to collect from but have relatively higher health and pension expenditures to pay to the old. ``` download_url = "https://datascience.quantecon.org/assets/data/WorldBank_AgeDependencyRatio.csv" df = pd.read_csv(download_url, na_values="..") df = df[["Country Name", "1960", "1970", "1980", "1990", "2000", "2010", "2017"]] df = df.set_index("Country Name").T df.index = df.index.values.astype(int) ``` Let’s visualize these variables for a collection of many developed countries. ``` fig, ax = plt.subplots() df.plot(ax=ax, legend=False) ax.text(2007, 38, "Japan") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` Notice that with so many lines, the message about Japan is hidden or polluted by noise. If we did want to demonstrate that Japan is significantly different than many other developed countries, we might try a plot like this: ``` fig, ax = plt.subplots() not_japan = list(df.columns) not_japan.remove("Japan") df[not_japan].plot(ax=ax, color=[(0.8, 0.8, 0.8)], lw=0.4, legend=False) ax.text(1970, 29, "Other Developed Countries") df["Japan"].plot(ax=ax, color=(0.95, 0.05, 0.05), lw=2.5, legend=False) ax.text(2006.5, 38, "Japan") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` However, placing this many lines on a single plot is definitely an exception, and we encourage you to do so sparingly. Generally, you should only have a few informative lines for each plot. We now will focus our graph on a few countries of interest. To do so, the plot below uses many different line styles. ``` fig, ax = plt.subplots() df["Japan"].plot(ax=ax, legend=False, linestyle="solid") ax.text(2002, 35, "Japan") df["United Kingdom"].plot(ax=ax, legend=False, linestyle="dashed") ax.text(1975, 24, "UK") df["United States"].plot(ax=ax, legend=False, linestyle="dashed") ax.text(1980, 19, "US") df["China"].plot(ax=ax, legend=False, linestyle="dotted") ax.text(1990, 10, "China") df["India"].plot(ax=ax, legend=False, linestyle="dotted") ax.text(2005, 5, "India") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` There are some good-use cases for using line styles to distinguish between different pieces of data, but not many. In particular, having this many different styles and colors makes it difficult to figure out what is going on. Instead, we recommend using color and line width instead of line styles to highlight certain pieces of information, as seen below. ``` fig, ax = plt.subplots() emph_color = (0.95, 0.05, 0.05) sec_color = [(0.05, 0.05+0.075*x, 0.95) for x in range(4)] df["Japan"].plot(ax=ax, legend=False, color=emph_color, linewidth=2.5) ax.text(2002, 35, "Japan") df["United Kingdom"].plot(ax=ax, legend=False, color=sec_color[0], alpha=0.4, linewidth=0.75) ax.text(1975, 24, "UK") df["United States"].plot(ax=ax, legend=False, color=sec_color[1], alpha=0.4, linewidth=0.75) ax.text(1980, 19, "US") df["China"].plot(ax=ax, legend=False, color=sec_color[2], alpha=0.4, linewidth=0.75) ax.text(1990, 10, "China") df["India"].plot(ax=ax, legend=False, color=sec_color[3], alpha=0.4, linewidth=0.75) ax.text(2005, 5, "India") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` ### Tick Steps Use easy to interpret increments such as multiples of 2, 5, 10, 25 etc… Using increments like `0, 3, 6, 9, 12, ...` make it more difficult for your reader to do mentally determine what the values between the lines are: ``` fig, ax = plt.subplots(1, 2, figsize=(14, 6)) x = np.linspace(0, 26, 50) ax[0].plot(x, np.sqrt(x)) ax[1].plot(x, np.sqrt(x)) ax[0].set_xticks(np.arange(0, 27, 3)) ax[0].set_xticklabels(np.arange(0, 27, 3)) ax[1].set_xticks(np.arange(0, 27, 5)) ax[1].set_xticklabels(np.arange(0, 27, 5)) ``` ### No Background Colors There are no reasons to use background colors in your visualizations. Research has shown that white or very light grays provide the best contrast as a background. Compare the following graphs and think about which feels better. ``` fig, ax = plt.subplots() ax.bar([0, 1], [35, 39.6], color="orange") ax.set_xticks([0, 1]) ax.set_xticklabels(["Now", "Jan 1, 2013"]) ax.set_ylim(0, 42) bgcolor = "blue" fig.set_facecolor(bgcolor) ax.set_facecolor(bgcolor) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ax.set_title("IF BUSH TAX CUTS EXPIRE\nTop Tax Rate") ``` versus ``` fig, ax = plt.subplots() ax.bar([0, 1], [35, 39.6], color="orange") ax.set_xticks([0, 1]) ax.set_xticklabels(["Now", "Jan 1, 2013"]) ax.set_ylim(0, 42) bgcolor = (0.99, 0.99, 0.99) fig.set_facecolor(bgcolor) ax.set_facecolor(bgcolor) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') for _spine in ["right", "top", "left", "bottom"]: ax.spines[_spine].set_visible(False) ax.set_title("IF BUSH TAX CUTS EXPIRE\nTop Tax Rate") ``` ### Legends Legends are quite common in charts, but many visualization experts advise against using them. Legends have several weaknesses: 1. Relying solely on line color often makes a black and white version of your plot effectively useless, since you don’t know whether the colors will be distinguishable in grayscale. 1. Legends require people to distinguish between small samples of colors. For someone with weak eyesight or color blindness, this can make interpreting graphs nearly impossible. 1. They add distance between the data and its description. This requires peoples’ eyes to go back and forth between the lines and the legend when trying to understand the story being told. This distracts from the ability to digest the story quickly and succinctly. To demonstrate this, we revisit our age dependency ratio example from earlier. ``` download_url = "https://datascience.quantecon.org/assets/data/WorldBank_AgeDependencyRatio.csv" df = pd.read_csv(download_url, na_values="..") df = df[["Country Name", "1960", "1970", "1980", "1990", "2000", "2010", "2017"]] df = df.set_index("Country Name").T df.index = df.index.values.astype(int) ``` With a legend: ``` fig, ax = plt.subplots() emph_color = (0.95, 0.05, 0.05) sec_color = [(0.05, 0.05+0.075*x, 0.95) for x in range(4)] df["Japan"].plot(ax=ax, legend=True, color=emph_color, linewidth=2.5) df["United Kingdom"].plot(ax=ax, legend=True, color=sec_color[0], alpha=0.4, linewidth=0.75) df["United States"].plot(ax=ax, legend=True, color=sec_color[1], alpha=0.4, linewidth=0.75) df["China"].plot(ax=ax, legend=True, color=sec_color[2], alpha=0.4, linewidth=0.75) df["India"].plot(ax=ax, legend=True, color=sec_color[3], alpha=0.4, linewidth=0.75) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` With labels: ``` fig, ax = plt.subplots() emph_color = (0.95, 0.05, 0.05) sec_color = [(0.05, 0.05+0.075*x, 0.95) for x in range(4)] df["Japan"].plot(ax=ax, legend=False, color=emph_color, linewidth=2.5) ax.text(2002, 35, "Japan") df["United Kingdom"].plot(ax=ax, legend=False, color=sec_color[0], alpha=0.4, linewidth=0.75) ax.text(1975, 24, "UK") df["United States"].plot(ax=ax, legend=False, color=sec_color[1], alpha=0.4, linewidth=0.75) ax.text(1980, 19, "US") df["China"].plot(ax=ax, legend=False, color=sec_color[2], alpha=0.4, linewidth=0.75) ax.text(1990, 10, "China") df["India"].plot(ax=ax, legend=False, color=sec_color[3], alpha=0.4, linewidth=0.75) ax.text(2005, 5, "India") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title("Japan's Aging Population") ax.set_ylabel("Age Dependency Ratio") ``` Most people find the example with labels to be a more readable graph. ### Limit the Information in a Single Plot Don’t try to put too much information in a single plot! We have tried to emphasize this point throughout this lecture, but it is so important that we are emphasizing it again! Don’t information overload your audience! ### Talk to Other People Our last guideline: talk with others about your visualization. The best way to determine whether other people understand your message is to show it to them. ## References <a id='ely'></a> **[1]** In particular, it is based on [this lecture](https://www.aeaweb.org/webcasts/2019/aea-ely-lecture-work-of-the-past-work-of-the-future) by Autor presented at the annual AEA meeting in January, 2019. This is a prestigious invited lecture with a large audience, so it is a more “polished” than the typical academic lecture. It is worth watching. Notice how almost every slide includes data visualizations, and very few consist solely of text. Also, notice the ways that the NYT modified Autor’s figures and think about whether these changes improved the figures. ## Exercises <a id='exerciselist-0'></a> **Exercise 1** Create a draft of the alternative way to organize time and education -- that is, have two subplots (one for each education level) and four groups of points (one for each year). Why do you think they chose to organize the information as they did rather than this way? ([*back to text*](#exercise-0)) **Exercise 2** Using the data on Canadian GDP growth below, create a bar chart which uses one color for the bars for the years 2000 to 2008, a red for 2009, and the same color as before for 2010 to 2018. ``` ca_gdp = pd.Series( [5.2, 1.8, 3.0, 1.9, 3.1, 3.2, 2.8, 2.2, 1.0, -2.8, 3.2, 3.1, 1.7, 2.5, 2.9, 1.0, 1.4, 3.0], index=list(range(2000, 2018)) ) fig, ax = plt.subplots() for side in ["right", "top", "left", "bottom"]: ax.spines[side].set_visible(False) ``` ([*back to text*](#exercise-1))
github_jupyter
#### New to Plotly? Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/). <br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/#start-plotting-online). <br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started! #### Version Check Note: `Facet Grids and Trellis Plots` are available in version <b>2.0.12+</b><br> Run `pip install plotly --upgrade` to update your Plotly version ``` import plotly plotly.__version__ ``` #### Facet by Column A `facet grid` is a generalization of a scatterplot matrix where we can "facet" a row and/or column by another variable. Given some tabular data, stored in a `pandas.DataFrame`, we can plot one variable against another to form a regular scatter plot, _and_ we can pick a third faceting variable to form panels along the rows and/or columns to segment the data even further, forming a bunch of panels. We can also assign a coloring rule or a heatmap based on a color variable to color the plot. ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') fig = ff.create_facet_grid( mpg, x='displ', y='cty', facet_col='cyl', ) py.iplot(fig, filename='facet by col') ``` #### Facet by Row ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') fig = ff.create_facet_grid( mpg, x='displ', y='cty', facet_row='cyl', marker={'color': 'rgb(86, 7, 100)'}, ) py.iplot(fig, filename='facet by row') ``` #### Facet by Row and Column ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') fig = ff.create_facet_grid( mpg, x='displ', y='cty', facet_row='cyl', facet_col='drv', marker={'color': 'rgb(234, 239, 155)'}, ) py.iplot(fig, filename='facet by row and col') ``` #### Color by Categorical Variable ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') fig = ff.create_facet_grid( mtcars, x='mpg', y='wt', facet_col='cyl', color_name='cyl', color_is_cat=True, ) py.iplot(fig, filename='facet - color by categorical variable') ``` #### Custom Colormap ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') fig = ff.create_facet_grid( tips, x='total_bill', y='tip', color_name='sex', show_boxes=False, marker={'size': 10, 'opacity': 1.0}, colormap={'Male': 'rgb(165, 242, 242)', 'Female': 'rgb(253, 174, 216)'} ) py.iplot(fig, filename='facet - custom colormap') ``` #### Label Variable Name:Value ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') fig = ff.create_facet_grid( mtcars, x='mpg', y='wt', facet_col='cyl', facet_col_labels='name', facet_row_labels='name', ) py.iplot(fig, filename='facet - label variable name') ``` #### Custom Labels ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') fig = ff.create_facet_grid( mtcars, x='wt', y='mpg', facet_col='cyl', facet_col_labels={4: '$2^2 = 4$', 6: '$\\frac{18}{3} = 6$', 8: '$2\cdot4 = 8$'}, marker={'color': 'rgb(240, 100, 2)'}, ) py.iplot(fig, filename='facet - custom labels') ``` #### Plot in 'ggplot2' style To learn more about ggplot2, check out http://ggplot2.tidyverse.org/reference/facet_grid.html ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') fig = ff.create_facet_grid( tips, x='total_bill', y='tip', facet_row='sex', facet_col='smoker', marker={'symbol': 'circle-open', 'size': 10}, ggplot2=True ) py.iplot(fig, filename='facet - ggplot2 style') ``` #### Plot with 'scattergl' traces ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') grid = ff.create_facet_grid( mpg, x='class', y='displ', trace_type='scattergl', ) py.iplot(grid, filename='facet - scattergl') ``` #### Plot with Histogram Traces ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') fig = ff.create_facet_grid( tips, x='total_bill', y='tip', facet_row='sex', facet_col='smoker', trace_type='histogram', ) py.iplot(fig, filename='facet - histogram traces') ``` #### Other Trace Types Facet Grids support `scatter`, `scattergl`, `histogram`, `bar` and `box` trace types. More trace types coming in the future. ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') fig = ff.create_facet_grid( tips, y='tip', facet_row='sex', facet_col='smoker', trace_type='box', ) py.iplot(fig, filename='facet - box traces') ``` #### Reference ``` help(ff.create_facet_grid) ! pip install git+https://github.com/plotly/publisher.git --upgrade import publisher publisher.publish( 'facet-and-trellis-plots.ipynb', 'python/facet-plots/', 'Facet and Trellis Plots', 'How to make Facet and Trellis Plots in Python with Plotly.', title = 'Python Facet and Trellis Plots | plotly', redirect_from ='python/trellis-plots/', has_thumbnail='true', thumbnail='thumbnail/facet-trellis-thumbnail.jpg', language='python', display_as='statistical', order=10.2) ```
github_jupyter
# Введение Данные интерактивные тетради основаны на языке Python. Для выполнения кода выберите ячейку с кодом и нажмите `Ctrl + Enter`. ``` from platform import python_version print("Используемая версия Python:", python_version()) ``` Ячейки подразумевают последовательное исполнение. ``` l = [1, 2, 3] l[0] type(l) help(l) ``` ## Математический аппарат В этих интерактивных тетрадях используется математический аппарат, основанный на парах вектор-кватернион. Вектор (`Vector`) представлен тремя чиселами, кватернион (`Quaternion`) - четыремя. Пара вектор-кватернион (`Transformation`) соостоит из вектора и кватерниона и описывает последовательные перемещение и поворот. $$ T = \begin{bmatrix} [v_x, v_y, v_z] \\ [q_w, q_x, q_y, q_z] \end{bmatrix} $$ Математический аппарат расположен в файле [kinematics.py](../edit/kinematics.py) ### Vector Вектор - тройка чисел, описывает перемещение: $$ v = [v_x, v_y, v_z] $$ ``` from kinematics import Vector ``` Создание вектора требует трех чисел: ``` v1 = Vector(1, 2, 3) v2 = Vector(-2, 4, -3) ``` Вектора можно складывать поэлементно: ``` v1 + v2 ``` А также умножать на скаляр: ``` 2.5 * v1 ``` Нулевой вектор создается через `Vector.zero()`: ``` Vector.zero() ``` ### Quaternion Кватернион - четверка чисел, описывает поворот: $$ q = [q_w, q_x, q_y, q_z] $$ ``` from kinematics import Quaternion from numpy import pi ``` Кватернион создается из угла и оси поворота: ``` q1 = Quaternion.from_angle_axis(0.5 * pi, Vector(0, 0, 1)) q2 = Quaternion.from_angle_axis(0.5 * pi, Vector(1, 0, 0)) print(q1) print(q2) ``` Перемножение кватернионов соответствует последовательному приложению поворотов, в данном случае - повороту вокруг оси, проходящей через точку `(1, 1, 1)` на угол 120 градусов: ``` q1 * q2 Quaternion.from_angle_axis(2 / 3 * pi, Vector(1, 1, 1).normalized()) ``` Поворот вектора сокращен до оператора `*`: ``` q = Quaternion.from_angle_axis(pi / 2, Vector(0, 0, 1)) q * Vector(1, 2, 3) ``` Кватернион нулевого поворота создается `Quaternion.identity()`: ``` Quaternion.identity() * Vector(1, 2, 3) ``` ### Transform ``` from kinematics import Transform ``` Пара вектор-кватернион собирается из вектора и кватерниона: ``` t1 = Transform(v1, q1) t2 = Transform(v2, q2) ``` Пара состоит из смещения и поворота: ``` t1.translation t1.rotation ``` Пара с нулевыми смещением и поворотом создается через `Transform.identity()`: ``` Transform.identity() ``` Суммирование двух пар описывет последовательное применение смещения - поворота - смещения - поворота: ``` t1 + t2 ``` Суммирование пары и ветора описывает применение преобразования, записанного в паре к вектору: ``` t1 + Vector(1, 0, 0) ``` ## Графика Подключим магию для работы с графикой: ``` from matplotlib import pyplot as plt from matplotlib import animation import numpy as np from IPython.display import HTML import graphics %matplotlib notebook ``` Отрисовка систем координат производится через `graphics.axis`. Преобразование цепочки в отдельные массивы точек `X, Y, Z` производится через `graphics.chain_to_points`. ``` fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.set_xlim([-3, 3]); ax.set_ylim([-3, 3]); ax.set_zlim([-3, 3]); graphics.axis(ax, Transform.identity(), 3) graphics.axis(ax, t1) graphics.axis(ax, t1 + t2) x, y, z = graphics.chain_to_points([Transform.identity(), t1, t1 + t2]) ax.plot(x, y, z) fig.show() ``` ## Анимация Анимация будет сохраняться в переменную, например в `ani`, которую потом можно будет отобразить в виде видеоролика через `HTML(ani.to_jshtml())`. Перед сохранением в виде ролика можно заранее повернуть сцену мышкой. Обратите внимание что перерисовка каждого кадра требует работы ядра. Для остановки нажмите кнопку выключения в правом верхнем углу трехмерной сцены. ``` fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.set_xlim([-1, 1]); ax.set_ylim([-1, 1]); ax.set_zlim([0, 2 * pi]) l, = ax.plot([], [], []) t = np.arange(1, 2 * pi, 0.1) frames = 100 def animate(i): offs = i / frames * 2 * pi z = t q = Quaternion.from_angle_axis(t + offs, Vector(0, 0, 1)) v = q * Vector(1, 0, 0) x = v.x y = v.y l.set_data_3d(x, y, z) ani = animation.FuncAnimation( fig, animate, frames=frames, interval=100 ) ``` Не забудьте выключить пересчет модели кнопкой в правом верхнем углу трехмерной сцены. ``` HTML(ani.to_jshtml()) ``` Полученый таким образом ролик можно сохранить в составе всей тетради и выкачать локальную копию через `File -> Download as -> Notebook (.ipynb)`. ## Символьные вычисления Для работы с символьными вычислениями используется пакет `sympy`. ``` import sympy as sp x = sp.symbols("x") x ``` `sympy` позволяет описывать деревья вычислений: ``` v = sp.sin(x) ** 2 + sp.cos(x) ** 2 v ``` И упрощать их: ``` sp.simplify(v) u = sp.cos(x) ** 2 - sp.sin(x) ** 2 u sp.simplify(u) ``` Можно легко дифференцировать выражения: ``` t = sp.symbols("t") f = sp.sin(t + 2 * x ** 2) f ``` Производная по $t$: ``` sp.diff(f, t) ``` Производная по $x$: ``` sp.diff(f, x) ``` Для того, чтобы описать кватернион в системе `sympy`, нужно передать `sympy`(`sp`) как последний агрумент в `Quaternion.from_angle_axis`: ``` a, b, c = sp.symbols("a, b, c") angle = sp.symbols("alpha") q = Quaternion.from_angle_axis(angle, Vector(0, 0, 1), sp) v = Vector(a, b, c) rotated = q * v sp.simplify(rotated.x) sp.simplify(rotated.y) sp.simplify(rotated.z) ``` А еще можно решать уравнения: ``` alpha, beta = sp.symbols("alpha, beta") t0 = Transform( Vector.zero(), Quaternion.from_angle_axis(alpha, Vector(0, 0, 1), sp) ) t1 = t0 + Transform( Vector(beta, 0, 0), Quaternion.identity() ) target_x = t1.translation.x target_x target_y = t1.translation.y target_y x, y = sp.symbols("x, y") solution = sp.solve( [ sp.simplify(target_x) - x, sp.simplify(target_y) - y ], [ alpha, beta ] ) ``` Первое решение для $\alpha$: ``` solution[0][0] ``` Первое решение для $\beta$: ``` solution[0][1] ``` Действительно, если подставить решение, в, например, $y$, получим следущее: ``` sp.simplify( t1.translation.y.replace(alpha, solution[0][0]).replace(beta, solution[0][1]) ) ``` Для $x$ такой красоты (пока) не произойдет, придется упрощать вручную: ``` sp.simplify( t1.translation.x.replace(alpha, solution[0][0]).replace(beta, solution[0][1]) ) ``` Возможно стоит использовать свое собственное решение, например: $$ \alpha = \tan^{-1}(y, x) $$ $$ \beta = \sqrt{x^2 + y^2} $$ ``` own_alpha = sp.atan2(y, x) own_beta = sp.sqrt(x ** 2 + y ** 2) sp.simplify(t1.translation.x.replace(alpha, own_alpha).replace(beta, own_beta)) sp.simplify(t1.translation.y.replace(alpha, own_alpha).replace(beta, own_beta)) ```
github_jupyter
<a href="https://colab.research.google.com/github/SahityaRoy/AKpythoncodes/blob/main/Copy_of_Untitled22.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline mpl.style.use('ggplot') car=pd.read_csv('/content/quikr_car.csv') car.head() car.shape car.info() backup=car.copy() car.year.unique() car.kms_driven.unique() car.Price.unique() car.fuel_type.unique() car.company.unique() # names are pretty inconsistent # names have company names attached to it # some names are spam like 'Maruti Ertiga showroom condition with' and 'Well mentained Tata Sumo' # company: many of the names are not of any company like 'Used', 'URJENT', and so on. # year has many non-year values # year is in object. Change to integer # Price has Ask for Price # Price has commas in its prices and is in object # kms_driven has object values with kms at last. # It has nan values and two rows have 'Petrol' in them # fuel_type has nan values # Cleaning Data car=car[car['year'].str.isnumeric()] car['year']=car['year'].astype('int') car.info() #price has ask for car=car[car['Price']!='Ask For Price'] #price has commas in its price and is in object car['Price']=car['Price'].str.replace(',','').astype('int') #kms_driven has object value with kms at last car['kms_driven']=car['kms_driven'].str.split().str.get(0).str.replace(',','') #it has nan values and two rows have 'Petrol' in them car=car[car['kms_driven'].str.isnumeric()] car['kms_driven']=car['kms_driven'].astype(int) #fuel_type has nan values car=car[~car['fuel_type'].isna()] car.shape #name and company had spammed data...but with the previous cleaning, those rows got removed. #Company does not need any cleaning now. Changing car names. Keeping only the first three words car['name']=car['name'].str.split().str.slice(start=0,stop=3).str.join(' ') #Resetting the index of the final cleaned data car=car.reset_index(drop=True) #cleaned data car.head() car.to_csv('/content/Cleaned_Car_data.csv') car.info() car.describe(include='all') car=car[car['Price']<6000000] car.company.unique() import seaborn as sns #relationship B/W company and Price plt.subplots(figsize=(15,7)) ax=sns.boxplot(x='company',y='Price',data=car) ax.set_xticklabels(ax.get_xticklabels(),rotation=40,ha='right') plt.show() #Checking relationship of Year with Price plt.subplots(figsize=(20,10)) ax=sns.swarmplot(x='year',y='Price',data=car) ax.set_xticklabels(ax.get_xticklabels(),rotation=40,ha='right') plt.show() #Checking relationship of kms_driven with Price sns.relplot(x='kms_driven',y='Price',data=car,height=7,aspect=1.5) #Checking relationship of Fuel Type with Price plt.subplots(figsize=(14,7)) sns.boxplot(x='fuel_type',y='Price',data=car) #Relationship of Price with FuelType, Year and Company mixed ax=sns.relplot(x='company',y='Price',data=car,hue='fuel_type',size='year',height=7,aspect=2) ax.set_xticklabels(rotation=40,ha='right') #Extracting Training Data X=car[['name','company','year','kms_driven','fuel_type']] y=car['Price'] X.shape y.shape #Appliying train test split from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2) from sklearn.linear_model import LinearRegression from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.metrics import r2_score #Creating an OneHotEncoder object to contain all the possible categories ohe=OneHotEncoder() ohe.fit(X[['name','company','fuel_type']]) #Creating a column transformer to transform categorical columns column_trans=make_column_transformer((OneHotEncoder(categories=ohe.categories_),['name','company','fuel_type']), remainder='passthrough') lr=LinearRegression() pipe=make_pipeline(column_trans,lr) pipe.fit(X_train,y_train) y_pred=pipe.predict(X_test) y_pred #cheking r2_score r2_score(y_test,y_pred) #Finding the model with a random state of TrainTestSplit where the model was found to give almost 0.92 as r2_score scores=[] for i in range(1000): X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.1,random_state=i) lr=LinearRegression() pipe=make_pipeline(column_trans,lr) pipe.fit(X_train,y_train) y_pred=pipe.predict(X_test) scores.append(r2_score(y_test,y_pred)) np.argmax(scores) scores[np.argmax(scores)] pipe.predict(pd.DataFrame(columns=X_test.columns,data=np.array(['Maruti Suzuki Swift','Maruti',2019,100,'Petrol']).reshape(1,5))) #The best model is found at a certain random state X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.1,random_state=np.argmax(scores)) lr=LinearRegression() pipe=make_pipeline(column_trans,lr) pipe.fit(X_train,y_train) y_pred=pipe.predict(X_test) r2_score(y_test,y_pred) import pickle pickle.dump(pipe,open('LinearRegressionModel.pkl','wb')) pipe.predict(pd.DataFrame(columns=['name','company','year','kms_driven','fuel_type'],data=np.array(['Maruti Suzuki Swift','Maruti',2019,100,'Petrol']).reshape(1,5))) pipe.steps[0][1].transformers[0][1].categories[0] ```
github_jupyter
``` import tensorflow as tf import pandas as pd import numpy as np import pickle from time import time from utils.df_loader import load_compas_df from utils.preprocessing import min_max_scale_numerical, remove_missing_values, inverse_dummy from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from alibi.explainers import CounterFactualProto, CounterFactual from alibi_cf.utils import get_cat_vars_dict tf.get_logger().setLevel(40) # suppress deprecation messages tf.compat.v1.disable_v2_behavior() # disable TF2 behaviour as alibi code still relies on TF1 constructs tf.keras.backend.clear_session() pd.options.mode.chained_assignment = None print('TF version: ', tf.__version__) print('Eager execution enabled: ', tf.executing_eagerly()) # False seed = 123 tf.random.set_seed(seed) np.random.seed(seed) df, feature_names, numerical_cols, categorical_cols, columns_type, target_name, possible_outcomes = load_compas_df() scaled_df, scaler = min_max_scale_numerical(df, numerical_cols) scaled_df.head(5) dummy_df = pd.get_dummies(scaled_df, columns= [ col for col in categorical_cols if col != target_name]) ### We should have this amount of input features. sum([len(scaled_df[col].unique()) for col in categorical_cols if col != target_name]) + len(numerical_cols) # enconded_df, encoder_dict = label_encode(scaled_df, categorical_cols) cat_to_ohe_cat = {} for c_col in categorical_cols: if c_col != target_name: cat_to_ohe_cat[c_col] = [ ohe_col for ohe_col in dummy_df.columns if ohe_col.startswith(c_col) and ohe_col != target_name] ohe_feature_names = [ col for col in dummy_df.columns if col != target_name] dummy_df.head(5) inverse_dummy(dummy_df, cat_to_ohe_cat).head(5) from sklearn.preprocessing import LabelEncoder target_label_encoder = LabelEncoder() dummy_df[target_name] = target_label_encoder.fit_transform(dummy_df[target_name]) dummy_df= dummy_df[ohe_feature_names + [target_name]] train_df, test_df = train_test_split(dummy_df, train_size=.8, random_state=seed, shuffle=True) X_train = np.array(train_df[ohe_feature_names]) y_train = np.array(train_df[target_name]) X_test = np.array(test_df[ohe_feature_names]) y_test = np.array(test_df[target_name]) ### Train nn = model= tf.keras.models.Sequential( [ tf.keras.layers.Dense(24,activation='relu'), tf.keras.layers.Dense(12,activation='relu'), tf.keras.layers.Dense(12,activation='relu'), tf.keras.layers.Dense(12,activation='relu'), tf.keras.layers.Dense(12,activation='relu'), tf.keras.layers.Dense(1), tf.keras.layers.Activation(tf.nn.sigmoid), ] ) nn.compile(optimizer="Adam", loss='binary_crossentropy', metrics=['accuracy']) nn.fit(X_train, y_train, batch_size=64, epochs=20, shuffle=True) models = { "dt": DecisionTreeClassifier().fit(X_train,y_train), "rfc": RandomForestClassifier().fit(X_train,y_train), "nn": nn, } pickle.dump(models['dt'], open('./saved_models/dt.p', 'wb')) pickle.dump(models['rfc'], open('./saved_models/rfc.p', 'wb')) models['nn'].save('./saved_models/nn.h5',overwrite=True) ### Load models = {} models['dt'] = pickle.load(open('./saved_models/dt.p', 'rb')) models['rfc'] = pickle.load(open('./saved_models/rfc.p', 'rb')) models['nn'] = tf.keras.models.load_model('./saved_models/nn.h5') ## Initialise NN output shape as (None, 1) for tensorflow.v1 models['nn'].predict(np.zeros((2, X_train.shape[-1]))) example_data = X_test[0, :].reshape(1,-1) dt_pred = models['dt'].predict(example_data)[0] rfc_pred = models['rfc'].predict(example_data)[0] nn_pred = models['nn'].predict(example_data)[0][0] print(f"DT [{dt_pred}], RFC [{rfc_pred}], NN [{nn_pred}]") ``` # Alibi ## 1. Counterfactual Prototype ``` cat_vars_dict = get_cat_vars_dict(scaled_df, categorical_cols, feature_names, target_name) cat_vars_dict cat_feature_names = [ col for col in categorical_cols if col != target_name ] cat_vars_idx_info = [] for cat_col in cat_feature_names: num_unique_v = len([ col for col in train_df.columns if col.startswith(f"{cat_col}_")]) first_index = min([ list(train_df.columns).index(col) for col in train_df.columns if col.startswith(f"{cat_col}_")]) cat_vars_idx_info.append({ "col": cat_col, "num_unique_v": num_unique_v, "first_index": first_index }) cat_vars_idx_info cat_vars_ohe = {} for idx_info in cat_vars_idx_info: cat_vars_ohe[idx_info['first_index']] = idx_info['num_unique_v'] from alibi_cf import AlibiBinaryPredictWrapper alibi_wrapped = { 'dt': AlibiBinaryPredictWrapper(models['dt']), 'rfc': AlibiBinaryPredictWrapper(models['rfc']), 'nn': AlibiBinaryPredictWrapper(models['nn']), } feature_range = (np.ones((1, len(feature_names))), np.zeros((1, len(feature_names)))) cf_p_dict = {} for k in alibi_wrapped.keys(): cf_p_dict[k] = CounterFactualProto( alibi_wrapped[k].predict, example_data.shape, cat_vars=cat_vars_ohe, feature_range=feature_range, max_iterations=500, ohe=True, ) cf_p_dict[k].fit(X_train) "" num_instances = 5 num_cf_per_instance = 1 results = {} for k in cf_p_dict.keys(): results[k] = [] print(f"Finding counterfactual for {k}") for idx, instance in enumerate(X_test[0:num_instances]): print(f"instance {idx}") example = instance.reshape(1, -1) for num_cf in range(num_cf_per_instance): print(f"CF {num_cf}") start_t = time() exp = cf_p_dict[k].explain(example) end_t = time () running_time = end_t - start_t if k=='nn': prediction = target_label_encoder.inverse_transform((models[k].predict(example)[0]> 0.5).astype(int))[0] else: prediction = target_label_encoder.inverse_transform(models[k].predict(example))[0] if (not exp.cf is None) and (len(exp.cf) > 0): print("Found CF") if k == 'nn': cf = inverse_dummy(pd.DataFrame(exp.cf['X'], columns=ohe_feature_names), cat_to_ohe_cat) cf.loc[0, target_name] = target_label_encoder.inverse_transform([exp.cf['class']])[0] else: cf = inverse_dummy(pd.DataFrame(exp.cf['X'], columns=ohe_feature_names), cat_to_ohe_cat) cf.loc[0, target_name] = target_label_encoder.inverse_transform([exp.cf['class']])[0] # print(exp.cf) # print(cf) else: print("CF not found") cf = None input_df = inverse_dummy(pd.DataFrame(example, columns=ohe_feature_names), cat_to_ohe_cat) input_df.loc[0, target_name] = prediction results[k].append({ "input": input_df, "cf": cf, 'exp': exp, "running_time": running_time, "ground_truth": target_label_encoder.inverse_transform([y_test[idx]])[0], "prediction": prediction, }) all_df = {} for k in results.keys(): all_data = [] for i in range(len(results[k])): final_df = pd.DataFrame([{}]) scaled_input_df = results[k][i]['input'].copy(deep=True) origin_columns = [f"origin_input_{col}" for col in scaled_input_df.columns] origin_input_df = scaled_input_df.copy(deep=True) scaled_input_df.columns = [f"scaled_input_{col}" for col in scaled_input_df.columns] origin_input_df[numerical_cols] = scaler.inverse_transform(origin_input_df[numerical_cols]) origin_input_df.columns = origin_columns final_df = final_df.join([scaled_input_df, origin_input_df]) if not results[k][i]['cf'] is None: scaled_cf_df = results[k][i]['cf'].copy(deep=True) # scaled_cf_df.loc[0, target_name] = target_label_encoder.inverse_transform([scaled_cf_df.loc[0, target_name]])[0] origin_cf_columns = [f"origin_cf_{col}" for col in scaled_cf_df.columns] origin_cf_df = scaled_cf_df.copy(deep=True) scaled_cf_df.columns = [f"scaled_cf_{col}" for col in scaled_cf_df.columns] origin_cf_df[numerical_cols] = scaler.inverse_transform(origin_cf_df[numerical_cols]) origin_cf_df.columns = origin_cf_columns final_df = final_df.join([scaled_cf_df, origin_cf_df]) # final_df = final_df.join([scaled_input_df, origin_input_df, scaled_cf_df, origin_cf_df]) final_df['running_time'] = results[k][i]['running_time'] final_df['Found'] = "Y" if not results[k][i]['cf'] is None else "N" final_df['ground_truth'] = results[k][i]['ground_truth'] final_df['prediction'] = results[k][i]['prediction'] all_data.append(final_df) all_df[k] = pd.concat(all_data) for df_k in all_df.keys(): all_df[df_k].to_csv(f"./results/proto_compas_{df_k}_result.csv") ```
github_jupyter
# Lesson 2: `if / else` and Functions --- Sarah Middleton (http://sarahmid.github.io/) This tutorial series is intended as a basic introduction to Python for complete beginners, with a special focus on genomics applications. The series was originally designed for use in GCB535 at Penn, and thus the material has been highly condensed to fit into just four class periods. The full set of notebooks and exercises can be found at http://github.com/sarahmid/python-tutorials For a slightly more in-depth (but non-interactive) introduction to Python, see my Programming Bootcamp materials here: http://github.com/sarahmid/programming-bootcamp Note that if you are viewing this notebook online from the github/nbviewer links, you will not be able to use the interactive features of the notebook. You must download the notebook files and run them locally with Jupyter/IPython (http://jupyter.org/). --- ## Table of Contents 1. Conditionals I: The "`if / else`" statement 2. Built-in functions 3. Modules 4. Test your understanding: practice set 2 # 1. Conditionals I: The "`if / else`" statement --- Programming is a lot like giving someone instructions or directions. For example, if I wanted to give you directions to my house, I might say... > Turn right onto Main Street > Turn left onto Maple Ave > **If** there is construction, continue straight on Maple Ave, turn right on Cat Lane, and left on Fake Street; **else**, cut through the empty lot to Fake Street > Go straight on Fake Street until house 123 The same directions, but in code: ``` construction = False print "Turn right onto Main Street" print "Turn left onto Maple Ave" if construction: print "Continue straight on Maple Ave" print "Turn right onto Cat Lane" print "Turn left onto Fake Street" else: print "Cut through the empty lot to Fake Street" print "Go straight on Fake Street until house 123" ``` This is called an "`if / else`" statement. It basically allows you to create a "fork" in the flow of your program based on a condition that you define. If the condition is `True`, the "`if`"-block of code is executed. If the condition is `False`, the `else`-block is executed. Here, our condition is simply the value of the variable `construction`. Since we defined this variable to quite literally hold the value `False` (this is a special data type called a Boolean, more on that in a minute), this means that we skip over the `if`-block and only execute the `else`-block. If instead we had set `construction` to `True`, we would have executed only the `if`-block. Let's define Booleans and `if / else` statements more formally now. --- ### [ Definition ] Booleans - A Boolean ("bool") is a type of variable, like a string, int, or float. - However, a Boolean is much more restricted than these other data types because it is only allowed to take two values: `True` or `False`. - In Python, `True` and `False` are always capitalized and never in quotes. - Don't think of `True` and `False` as words! You can't treat them like you would strings. To Python, they're actually interpreted as the numbers 1 and 0, respectively. - Booleans are most often used to create the "conditional statements" used in if / else statements and loops. --- ### [ Definition ] The `if / else` statement **Purpose:** creates a fork in the flow of the program based on whether a conditional statement is `True` or `False`. **Syntax:** if (conditional statement): this code is executed else: this code is executed **Notes:** - Based on the Boolean (`True` / `False`) value of a conditional statement, either executes the `if`-block or the `else`-block - The "blocks" are indicated by indentation. - The `else`-block is optional. - Colons are required after the `if` condition and after the `else`. - All code that is part of the `if` or `else` blocks must be indented. **Example:** ``` x = 5 if (x > 0): print "x is positive" else: print "x is negative" ``` --- So what types of conditionals are we allowed to use in an `if / else` statement? Anything that can be evaluated as `True` or `False`! For example, in natural language we might ask the following true/false questions: > is `a` True? > is `a` less than `b`? > is `a` equal to `b`? > is `a` equal to "ATGCTG"? > is (`a` greater than `b`) and (`b` greater than `c`)? To ask these questions in our code, we need to use a special set of symbols/words. These are called the **logical operators**, because they allow us to form logical (true/false) statements. Below is a chart that lists the most common logical operators: ![conditionals](images/conditionals_symbols.PNG) Most of these are pretty intuitive. The big one people tend to mess up on in the beginning is `==`. Just remember: a single equals sign means *assignment*, and a double equals means *is the same as/is equal to*. You will NEVER use a single equals sign in a conditional statement because assignment is not allowed in a conditional! Only `True` / `False` questions are allowed! ### `if / else` statements in action Below are several examples of code using `if / else` statements. For each code block, first try to guess what the output will be, and then run the block to see the answer. ``` a = True if a: print "Hooray, a was true!" a = True if a: print "Hooray, a was true!" print "Goodbye now!" a = False if a: print "Hooray, a was true!" print "Goodbye now!" ``` > Since the line `print "Goodbye now!"` is not indented, it is NOT considered part of the `if`-statement. Therefore, it is always printed regardless of whether the `if`-statement was `True` or `False`. ``` a = True b = False if a and b: print "Apple" else: print "Banana" ``` > Since `a` and `b` are not both `True`, the conditional statement "`a and b`" as a whole is `False`. Therefore, we execute the `else`-block. ``` a = True b = False if a and not b: print "Apple" else: print "Banana" ``` > By using "`not`" before `b`, we negate its current value (`False`), making `b` `True`. Thus the entire conditional as a whole becomes `True`, and we execute the `if`-block. ``` a = True b = False if not a and b: print "Apple" else: print "Banana" ``` >"`not`" only applies to the variable directly in front of it (in this case, `a`). So here, `a` becomes `False`, so the conditional as a whole becomes `False`. ``` a = True b = False if not (a and b): print "Apple" else: print "Banana" ``` > When we use parentheses in a conditional, whatever is within the parentheses is evaluated first. So here, the evaluation proceeds like this: > First Python decides how to evaluate `(a and b)`. As we saw above, this must be `False` because `a` and `b` are not both `True`. > Then Python applies the "`not`", which flips that `False` into a `True`. So then the final answer is `True`! ``` a = True b = False if a or b: print "Apple" else: print "Banana" ``` > As you would probably expect, when we use "`or`", we only need `a` *or* `b` to be `True` in order for the whole conditional to be `True`. ``` cat = "Mittens" if cat == "Mittens": print "Awwww" else: print "Get lost, cat" a = 5 b = 10 if (a == 5) and (b > 0): print "Apple" else: print "Banana" a = 5 b = 10 if ((a == 1) and (b > 0)) or (b == (2 * a)): print "Apple" else: print "Banana" ``` >Ok, this one is a little bit much! Try to avoid complex conditionals like this if possible, since it can be difficult to tell if they're actually testing what you think they're testing. If you do need to use a complex conditional, use parentheses to make it more obvious which terms will be evaluated first! ### Note on indentation - Indentation is very important in Python; it’s how Python tells what code belongs to which control statements - Consecutive lines of code with the same indenting are sometimes called "blocks" - Indenting should only be done in specific circumstances (if statements are one example, and we'll see a few more soon). Indent anywhere else and you'll get an error. - You can indent by however much you want, but you must be consistent. Pick one indentation scheme (e.g. 1 tab per indent level, or 4 spaces) and stick to it. ### [ Check yourself! ] `if/else` practice Think you got it? In the code block below, write an `if/else` statement to print a different message depending on whether `x` is positive or negative. ``` x = 6 * -5 - 4 * 2 + -7 * -8 + 3 # ******add your code here!********* ``` # 2. Built-in functions --- Python provides some useful built-in functions that perform specific tasks. What makes them "built-in"? Simply that you don’t have to "import" anything in order to use them -- they're always available. This is in contrast the the *non*-built-in functions, which are packaged into modules of similar functions (e.g. "math") that you must import before using. More on this in a minute! We've already seen some examples of built-in functions, such as `print`, `int()`, `float()`, and `str()`. Now we'll look at a few more that are particularly useful: `raw_input()`, `len()`, `abs()`, and `round()`. --- ### [ Definition ] `raw_input()` **Description:** A built-in function that allows user input to be read from the terminal. **Syntax:** raw_input("Optional prompt: ") **Notes**: - The execution of the code will pause when it reaches the `raw_input()` function and wait for the user to input something. - The input ends when the user hits "enter". - The user input that is read by `raw_input()` can then be stored in a variable and used in the code. - **Important: This function always returns a string, even if the user entered a number!** You must convert the input with int() or float() if you expect a number input. **Examples:** ``` name = raw_input("Your name: ") print "Hi there", name, "!" age = int(raw_input("Your age: ")) #convert input to an int print "Wow, I can't believe you're only", age ``` --- ### [ Definition ] `len()` **Description:** Returns the length of a string (also works on certain data structures). Doesn’t work on numerical types. **Syntax:** len(string) **Examples:** ``` print len("cat") print len("hi there") seqLength = len("ATGGTCGCAT") print seqLength ``` --- ### [ Definition ] `abs()` **Description:** Returns the absolute value of a numerical value. Doesn't accept strings. **Syntax:** abs(number) **Examples:** ``` print abs(-10) print abs(int("-10")) positiveNum = abs(-23423) print positiveNum ``` --- ### [ Definition ] `round()` **Description:** Rounds a float to the indicated number of decimal places. If no number of decimal places is indicated, rounds to zero decimal places. **Synatx:** round(someNumber, numDecimalPlaces) **Examples:** ``` print round(10.12345) print round(10.12345, 2) print round(10.9999, 2) ``` --- If you want to learn more built in functions, go here: https://docs.python.org/2/library/functions.html # 3. Modules --- Modules are groups of additional functions that come with Python, but unlike the built-in functions we just saw, these functions aren't accessible until you **import** them. Why aren’t all functions just built-in? Basically, it improves speed and memory usage to only import what is needed (there are some other considerations, too, but we won't get into it here). The functions in a module are usually all related to a certain kind of task or subject area. For example, there are modules for doing advanced math, generating random numbers, running code in parallel, accessing your computer's file system, and so on. We’ll go over just two modules today: `math` and `random`. See the full list here: https://docs.python.org/2.7/py-modindex.html ### How to use a module Using a module is very simple. First you import the module. Add this to the top of your script: import <moduleName> Then, to use a function of the module, you prefix the function name with the name of the module (using a period between them): <moduleName>.<functionName> (Replace `<moduleName>` with the name of the module you want, and `<functionName>` with the name of a function in the module.) The `<moduleName>.<functionName>` synatx is needed so that Python knows where the function comes from. Sometimes, especially when using user created modules, there can be a function with the same name as a function that's already part of Python. Using this syntax prevents functions from overwriting each other or causing ambiguity. --- ### [ Definition ] The `math` module **Description:** Contains many advanced math-related functions. See full list of functions here: https://docs.python.org/2/library/math.html **Examples:** ``` import math print math.sqrt(4) print math.log10(1000) print math.sin(1) print math.cos(0) ``` --- ### [ Definition ] The `random` module **Description:** contains functions for generating random numbers. See full list of functions here: https://docs.python.org/2/library/random.html **Examples:** ``` import random print random.random() # Return a random floating point number in the range [0.0, 1.0) print random.randint(0, 10) # Return a random integer between the specified range (inclusive) print random.gauss(5, 2) # Draw from the normal distribution given a mean and standard deviation # this code will output something different every time you run it! ``` # 4. Test your understanding: practice set 2 --- For the following blocks of code, **first try to guess what the output will be**, and then run the code yourself. These examples may introduce some ideas and common pitfalls that were not explicitly covered in the text above, ***so be sure to complete this section***. The first block below holds the variables that will be used in the problems. Since variables are shared across blocks in Jupyter notebooks, you just need to run this block once and then those variables can be used in any other code block. ``` # RUN THIS BLOCK FIRST TO SET UP VARIABLES! a = True b = False x = 2 y = -2 cat = "Mittens" print a print (not a) print (a == b) print (a != b) print (x == y) print (x > y) print (x = 2) print (a and b) print (a and not b) print (a or b) print (not b or a) print not (b or a) print (not b) or a print (not b and a) print not (b and a) print (not b) and a print (x == abs(y)) print len(cat) print cat + x print cat + str(x) print float(x) print ("i" in cat) print ("g" in cat) print ("Mit" in cat) if (x % 2) == 0: print "x is even" else: print "x is odd" if (x - 4*y) < 0: print "Invalid!" else: print "Banana" if "Mit" in cat: print "Hey Mits!" else: print "Where's Mits?" x = "C" if x == "A" or "B": print "yes" else: print "no" x = "C" if (x == "A") or (x == "B"): print "yes" else: print "no" ``` > Surprised by the last two? It's important to note that when you want compare a variable against multiple things, you only compare it to one thing at a time. Although it makes sense in English to say, is x equal to A or B?, in Python you must write: ((x == "A") or (x == "B")) to accomplish this. The same goes for e.g. ((x > 5) and (x < 10)) and anything along those lines. > So why does the first version give the answer "yes"? Basically, anything that isn't `False` or the literal number 0 is considered to be `True` in Python. So when you say '`x == "A" or "B"`', this evaluates to '`False or True`', which is `True`!
github_jupyter
``` given = """ E N T E R L A S E R L A S E R R E S A L L A S E R O B S I D I A N L A S E R G W E R E S A L L A S E R L M R R E S A L A L A S E R R E S A L A O E R L A S E R L L L E M I T T E R S O S E L R E S A L L A A M R E S A L E N A S L A L A S E R R S S R E S A L R S L A R A S R E S A L E E E L A S E R T R L L E S E L A S E R S R R W A L L O E R R A S E R R E S A L A L A S E R N S E L E S A R E B E R Y L L L R L M E A S L A S E L N L L A S E R J A E A O L A R A S A R O L R E S A L A E S S S O L L E S E L T A L A S E R D S M E A E N R A S E R S W R E S A L E L R I R L R S E S A R D R L A S E R O W A E T L R R T S E L O E T R E S A L N A S S T A E E O A R O S O N L A S E R Y L E A E S S S N L L A B A R R E S A L X L R L R E A A E B L R E S A L L A S E R E X I T R L L L A S E R E S L A S E R L A S E R """.strip().replace(' ', '\t') print(given) print(""" Artisan Bass speaker Count (on) Deprived (of) Enjoyed together False teeth French cap Gram or pound Inform (of) Like a birthday Moon feature More confident Not capable Place a value on Put in danger Race in stages Recycle alternative Regal Renders undrinkable Rip up Suitor Trash Undo a wedding Wave rider """.replace('\t', ' ')) import forge from puzzle.puzzlepedia import puzzlepedia puzzle = puzzlepedia.parse(""" @ 6 9 7 11 3 1 8 4 10 5 12 2 * APPRAISE * DENATURE * IMPERIAL * ? * RELAY * ? * BEREFT * CRAFTER * REFUSE * SURFER * UNFIT * WOOFER """.lower()) import Numberjack given = """ 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 0 1 0 1 0 1 0 1 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 0 1 1 0 0 1 """.strip() G = Numberjack.Matrix(5, 5, 'x') model = Numberjack.Model() options = G.row + G.col def constrain(bits): model.add(Numberjack.Disjunction([ Numberjack.Conjunction([bits_bit == option_bit for bits_bit, option_bit in zip(bits, option)]) for option in options ])) for soln in given.split('\n'): bits = [bit == '1' for bit in soln.split('\t')] constrain(bits) solver = model.load('Mistral') solver.solve() print(str(model)) print("is_sat", solver.is_sat()) print("is_unsat", solver.is_unsat()) for r in range(5): row = [] for c in range(5): row.append('%2d' % G[r][c].get_value()) print('\t'.join(row)) ''.join(""" QLSRUXWGGSFCSUSLFWLSDAFHWFIXTEYYCMVT OLTGUGHVHMVIXOUBWEZFTHYPTXCGPWGIKOLW BFIIRBYXTOGQYFPYOZZXGMQJNUUGHNWNWATH MYZFRGMSYUUFVYEDPTPHLJOOQLFTXARTWKOG YNJSTTHPXNCRHOSHLKJYWVBTDCYNRGLVKMWN HIURUSGNCIFNJWXWCPCTROYRQGELVRFWEAGT RHTFGEWNRJGYGYKFVYEYMSPQDWKFEXUDPJRZ EMDDUGUCGTGRGMFGRPVYIMVQUWVBGOAPKRGN GHJTUTNYGWYWWKVTKRTRUNULGYFUYEXQRUCF CNXJKUFKHYJVCITWIBGMGIIFRIARRIXAWJKI SUNERQRUTFGRGFDPMJUWNBWDJWKCZJJYFVKN WJSHPGNPLPLTULJHRSMKMAXNVZYRMYGHWNDU ENUIWQDDLSATXFJQSZSTNPZIVERLCTLXKGTD WZIQXWCYTGERRLFWMQMJSXILJAVGSTCRVQHW VFJPUQNUFHEYMHNYNNLRJGJRQKXGFPRENLWR GHDDFLLNUZHTXQRFTCXQMAJNYGILDPIZXUGK """.strip().split('\n')) example = {"ver":[[1,2,3],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]],"hor":[[12,3],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]]} ver_str = """ 5 1 1 5 4 3 3 1 3 4 3 4 4 4 1 1 1 1 1 1 4 3 3 4 3 1 1 1 1 2 4 3 2 4 1 1 1 1 1 1 1 5 2 1 2 2 3 4 3 4 2 2 1 1 2 2 2 2 1 2 2 2 2 2 2 4 4 4 4 4 1 1 2 2 2 2 1 1 1 1 1 1 1 1 2 2 2 2 2 2 3 4 4 1 1 1 1 1 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 2 2 2 4 4 4 1 2 4 4 1 1 2 2 2 4 2 2 2 6 2 2 2 6 1 1 4 4 4 2 4 2 7 1 1 1 1 1 1 1 2 4 2 4 2 4 1 1 1 1 4 2 5 2 8 1 1 1 1 1 1 4 5 2 5 3 1 4 4 4 5 5 2 6 3 6 6 2 5 3 6 5 2 6 4 4 8 6 2 6 24 3 3 2 9 23 3 2 2 2 1 5 4 3 3 2 2 1 3 5 4 4 4 2 2 1 1 3 4 15 4 2 2 1 2 3 4 9 5 2 2 2 3 3 5 5 2 2 3 3 3 6 7 2 2 3 4 3 18 4 4 5 4 14 4 5 6 4 8 4 6 8 4 5 8 10 5 6 9 12 19 11 14 14 13 """.strip() hor_str = """ 00 00 0 0 00 00 00 00 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 00 00 0 0 00 00 00 00 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 00 00 0 0 00 00 00 00 0 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 5 1 1 00 00 0 0 00 00 00 00 0 2 1 1 0 0 0 1 1 1 0 0 0 5 1 1 0 0 5 1 1 3 0 0 1 1 5 1 00 00 0 0 00 00 00 00 0 1 1 1 0 0 5 1 1 1 0 0 5 1 1 3 3 0 5 1 1 5 0 0 1 1 1 3 00 00 0 3 01 00 00 00 6 1 1 1 5 0 5 1 1 3 0 0 5 1 1 5 1 0 5 1 1 5 0 5 3 1 1 1 0 1 1 0 2 06 15 3 0 1 2 00 00 4 3 02 00 03 16 5 4 3 3 3 4 3 1 1 5 2 2 2 2 2 3 3 3 3 2 2 2 2 2 1 1 1 3 5 3 4 1 5 10 03 8 3 3 3 04 07 05 5 7 13 03 19 08 7 5 4 4 4 3 4 5 5 5 2 1 2 2 2 2 2 2 2 2 2 2 2 1 4 3 4 3 3 4 4 9 9 03 04 5 5 7 8 05 05 7 09 15 5 3 03 18 04 03 3 2 2 2 2 2 3 2 3 2 3 3 2 3 3 3 3 3 3 3 3 3 3 3 3 4 3 4 4 2 3 4 4 02 02 2 3 3 3 11 15 9 12 10 9 7 06 05 04 04 3 3 2 2 1 1 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 3 2 3 1 1 2 2 03 04 4 5 6 7 09 10 12 """.strip() ver = [[int(s) for s in line.split()] for line in ver_str.split('\n')] hor_rows = [[int(s) for s in line.split()] for line in hor_str.split('\n')] hor = [] for col_idx in range(max(map(len, hor_rows))): col = [] hor.append(col) for row in hor_rows: if col_idx < len(row) and row[col_idx]: col.append(row[col_idx]) print(ver) print(hor) import json json.dumps({'ver': ver, 'hor': hor}) import forge from puzzle.puzzlepedia import puzzlepedia puzzle = puzzlepedia.parse(""" @ 1 2 3 4 5 6 7 8 9 10 * BigOldBell * BootyJuker * CorkChoker * FacePinner * FakeTurtle * LemurPoker * PixieProng * SheepStick * SqueezeToy * TinyStools """.lower()) import Numberjack model = Numberjack.Model() x = {} for name in 'abcd': x[name] = Numberjack.Variable([4, 5, 6, 8], name) model.add(Numberjack.AllDiff(x.values())) model.add(Numberjack.Sum([x[n] for n in 'abcd']) == 23) base = 1 for n in 'efgh': base = x[n] * base model.add(base == 42) solver = model.load('Mistral') solver.solve() print("is_sat", solver.is_sat()) print("is_unsat", solver.is_unsat()) print(model) for name in 'abcdefgh': print(x[name], x[name].get_value()) ```
github_jupyter
``` ! pip install h2o import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn import tree import h2o from h2o.estimators.glm import H2OGeneralizedLinearEstimator from h2o.estimators.random_forest import H2ORandomForestEstimator from h2o.estimators.gbm import H2OGradientBoostingEstimator from h2o.grid.grid_search import H2OGridSearch from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from google.colab import drive drive.mount('/content/drive') #Initialize H2o h2o.init() # Reading dataset from Google drive df_creditcarddata = h2o.import_file("/content/drive/My Drive/Colab Notebooks/UCI_Credit_Card.csv") type(df_creditcarddata) df_creditcarddata.head() #check dimensions of the data df_creditcarddata.shape df_creditcarddata.columns df_creditcarddata.types #Count for the response var df_creditcarddata['default.payment.next.month'].table() df_creditcarddata = df_creditcarddata.drop(["ID"], axis = 1) df_creditcarddata.head() import pylab as pl df_creditcarddata[['AGE','BILL_AMT1','BILL_AMT2','BILL_AMT3','BILL_AMT4','BILL_AMT5','BILL_AMT6', 'LIMIT_BAL']].as_data_frame().hist(figsize=(20,20)) pl.show() # Defaulters by Gender columns = ["default.payment.next.month","SEX"] default_by_gender = df_creditcarddata.group_by(by=columns).count(na ="all") print(default_by_gender.get_frame()) # Defaulters by education columns = ["default.payment.next.month","EDUCATION"] default_by_education = df_creditcarddata.group_by(by=columns).count(na ="all") print(default_by_education.get_frame()) # Defaulters by MARRIAGE columns = ["default.payment.next.month","MARRIAGE"] default_by_marriage = df_creditcarddata.group_by(by=columns).count(na ="all") print(default_by_marriage.get_frame()) # Convert the categorical variables into factors df_creditcarddata['SEX'] = df_creditcarddata['SEX'].asfactor() df_creditcarddata['EDUCATION'] = df_creditcarddata['EDUCATION'].asfactor() df_creditcarddata['MARRIAGE'] = df_creditcarddata['MARRIAGE'].asfactor() df_creditcarddata['PAY_0'] = df_creditcarddata['PAY_0'].asfactor() df_creditcarddata['PAY_2'] = df_creditcarddata['PAY_2'].asfactor() df_creditcarddata['PAY_3'] = df_creditcarddata['PAY_3'].asfactor() df_creditcarddata['PAY_4'] = df_creditcarddata['PAY_4'].asfactor() df_creditcarddata['PAY_5'] = df_creditcarddata['PAY_5'].asfactor() df_creditcarddata['PAY_6'] = df_creditcarddata['PAY_6'].asfactor() df_creditcarddata.types # Also, encode the binary response variable as a factor df_creditcarddata['default.payment.next.month'] = df_creditcarddata['default.payment.next.month'].asfactor() df_creditcarddata['default.payment.next.month'].levels() # Define predictors manually predictors = ['LIMIT_BAL','SEX','EDUCATION','MARRIAGE','AGE','PAY_0','PAY_2','PAY_3',\ 'PAY_4','PAY_5','PAY_6','BILL_AMT1','BILL_AMT2','BILL_AMT3','BILL_AMT4',\ 'BILL_AMT5','BILL_AMT6','PAY_AMT1','PAY_AMT2','PAY_AMT3','PAY_AMT4','PAY_AMT5','PAY_AMT6'] target = 'default.payment.next.month' # Split the H2O data frame into training/test sets # using 70% for training # using the rest 30% for test evaluation splits = df_creditcarddata.split_frame(ratios=[0.7], seed=1) train = splits[0] test = splits[1] ``` **GENERALIZED LINEAR MODEL (Defaut Settings)** STANDARDIZATION is enabled by default GLM with default setting GLM using lmbda search GLM using Grid search GLM WITH DEFAULT SETTINGS Logistic Regression (Binomial Family) H2O's GLM has the "family" argument, where the family is 'binomial' if the data is categorical 2 levels/classes or binary (Enum or Int). ``` GLM_default_settings = H2OGeneralizedLinearEstimator(family='binomial', \ model_id='GLM_default',nfolds = 10, \ fold_assignment = "Modulo", \ keep_cross_validation_predictions = True) GLM_default_settings.train(x = predictors, y = target, training_frame = train) ``` ### **GLM WITH LAMBDA SEARCH** The model parameter, lambda, controls the amount of regularization in a GLM model Setting lambda_search = True gives us optimal lambda value for the regularization strength. ``` GLM_regularized = H2OGeneralizedLinearEstimator(family='binomial', model_id='GLM', \ lambda_search=True, nfolds = 10, \ fold_assignment = "Modulo", \ keep_cross_validation_predictions = True) GLM_regularized.train(x = predictors, y = target,training_frame = train) ``` ### **GLM WITH GRID SEARCH** GLM needs to find the optimal values of the regularization parameters α and λ lambda: controls the amount of regularization, when set to 0 it gets disabled alpha : controls the distribution between lasso & ridge regression penalties. random grid search: H2o supports 2 types of grid search, cartesian and random. We make use of the random as the search criteria for faster computation Stopping metric: we specify the metric used for early stopping. AUTO takes log loss as default source: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/algo-params/lambda.html ``` hyper_parameters = { 'alpha': [0.0001, 0.001, 0.01, 0.1], 'lambda': [0.001, 0.01, 0.1] } search_criteria = { 'strategy': "RandomDiscrete", 'stopping_metric': "AUTO", 'stopping_rounds': 5} GLM_grid_search = H2OGridSearch(H2OGeneralizedLinearEstimator(family='binomial', \ nfolds = 10, fold_assignment = "Modulo", \ keep_cross_validation_predictions = True),\ hyper_parameters, grid_id="GLM_grid", search_criteria=search_criteria) GLM_grid_search.train(x= predictors,y= target, training_frame=train) ``` ### Get the grid results, sorted by validation AUC ``` # Get the grid results, sorted by validation AUC GLM_grid_sorted = GLM_grid_search.get_grid(sort_by='auc', decreasing=True) GLM_grid_sorted # Extract the best model from random grid search Best_GLM_model_from_Grid = GLM_grid_sorted.model_ids[0] #model performance Best_GLM_model_from_Grid = h2o.get_model(Best_GLM_model_from_Grid) print(Best_GLM_model_from_Grid) ``` ### RF WITH DEFAULT SETTINGS ``` # Build a RF model with default settings RF_default_settings = H2ORandomForestEstimator(model_id = 'RF_D',\ nfolds = 10, fold_assignment = "Modulo", \ keep_cross_validation_predictions = True) # Use train() to build the model RF_default_settings.train(x = predictors, y = target, training_frame = train) #Let's see the default parameters that RF model utilizes: RF_default_settings.summary() ``` ### RF with GRID SEARCH to extract the best model ``` hyper_params = {'sample_rate':[0.7,0.9], 'col_sample_rate_per_tree': [0.8, 0.9], 'max_depth': [3, 5, 9], 'ntrees': [200, 300, 400] } RF_grid_search = H2OGridSearch(H2ORandomForestEstimator(nfolds = 10, \ fold_assignment = "Modulo", \ keep_cross_validation_predictions = True, \ stopping_metric = 'AUC',stopping_rounds = 5), \ hyper_params = hyper_params, \ grid_id= 'RF_gridsearch') # Use train() to start the grid search RF_grid_search.train(x = predictors, y = target, training_frame = train) # Sort the grid models RF_grid_sorted = RF_grid_search.get_grid(sort_by='auc', decreasing=True) print(RF_grid_sorted) # Extract the best model from random grid search Best_RF_model_from_Grid = RF_grid_sorted.model_ids[0] # Model performance Best_RF_model_from_Grid = h2o.get_model(Best_RF_model_from_Grid) print(Best_RF_model_from_Grid) GBM_default_settings = H2OGradientBoostingEstimator(model_id = 'GBM_default', \ nfolds = 10, \ fold_assignment = "Modulo", \ keep_cross_validation_predictions = True) # Use train() to build the model GBM_default_settings.train(x = predictors, y = target, training_frame = train) hyper_params = {'learn_rate': [0.001,0.01, 0.1], 'sample_rate': [0.8, 0.9], 'col_sample_rate': [0.2, 0.5, 1], 'max_depth': [3, 5, 9], 'ntrees' : [100, 200, 300] } GBM_grid_search = H2OGridSearch(H2OGradientBoostingEstimator(nfolds = 10, \ fold_assignment = "Modulo", \ keep_cross_validation_predictions = True,\ stopping_metric = 'AUC', stopping_rounds = 5), hyper_params = hyper_params, grid_id= 'GBM_Grid') # Use train() to start the grid search GBM_grid_search.train(x = predictors, y = target, training_frame = train) # Sort and show the grid search results GBM_grid_sorted = GBM_grid_search.get_grid(sort_by='auc', decreasing=True) print(GBM_grid_sorted) # Extract the best model from random grid search Best_GBM_model_from_Grid = GBM_grid_sorted.model_ids[0] Best_GBM_model_from_Grid = h2o.get_model(Best_GBM_model_from_Grid) print(Best_GBM_model_from_Grid) ``` ### STACKED ENSEMBLE ``` # list the best models from each grid all_models = [Best_GLM_model_from_Grid, Best_RF_model_from_Grid, Best_GBM_model_from_Grid] # Set up Stacked Ensemble ensemble = H2OStackedEnsembleEstimator(model_id = "ensemble", base_models = all_models, metalearner_algorithm = "deeplearning") # uses GLM as the default metalearner ensemble.train(y = target, training_frame = train) ``` ### Checking model performance of all base learners ``` # Checking the model performance for all GLM models built model_perf_GLM_default = GLM_default_settings.model_performance(test) model_perf_GLM_regularized = GLM_regularized.model_performance(test) model_perf_Best_GLM_model_from_Grid = Best_GLM_model_from_Grid.model_performance(test) # Checking the model performance for all RF models built model_perf_RF_default_settings = RF_default_settings.model_performance(test) model_perf_Best_RF_model_from_Grid = Best_RF_model_from_Grid.model_performance(test) # Checking the model performance for all GBM models built model_perf_GBM_default_settings = GBM_default_settings.model_performance(test) model_perf_Best_GBM_model_from_Grid = Best_GBM_model_from_Grid.model_performance(test) ``` ### Best AUC from the base learners ``` # Best AUC from the base learner models best_auc = max(model_perf_GLM_default.auc(), model_perf_GLM_regularized.auc(), \ model_perf_Best_GLM_model_from_Grid.auc(), \ model_perf_RF_default_settings.auc(), \ model_perf_Best_RF_model_from_Grid.auc(), \ model_perf_GBM_default_settings.auc(), \ model_perf_Best_GBM_model_from_Grid.auc()) print("Best AUC out of all the models performed: ", format(best_auc)) ``` ### AUC from the Ensemble Learner ``` # Eval ensemble performance on the test data Ensemble_model = ensemble.model_performance(test) Ensemble_model = Ensemble_model.auc() print(Ensemble_model) ```
github_jupyter
# Dragon Real Estate -Price Prediction ``` #load the house dataset import pandas as pd housing=pd.read_csv("data.csv") #sample of first 5 data housing.head() #housing information housing.info() #or find missing value housing.isnull().sum() print(housing["CHAS"].value_counts()) housing.describe() %matplotlib inline # data visualization import matplotlib.pyplot as plt housing.hist(bins=50,figsize=(20,15)) plt.show() ##train test spliting import numpy as np def split_train_test(data,test_ratio): np.random.seed(42) shuffled=np.random.permutation(len(data)) print(shuffled) test_set_size=int(len(data) * test_ratio) test_indices=shuffled[:test_set_size] train_indices=shuffled[test_set_size:] return data.iloc[train_indices], data.iloc[test_indices] train_set,test_set=split_train_test(housing,0.2) print(f"Rows in train set:{len(train_set)}\nRoows in test set:{len(test_set)}\n") #train the data from sklearn.model_selection import train_test_split train_set,test_set=train_test_split(housing,test_size=0.2,random_state=42) print(f"Rows in train set:{len(train_set)}\nRoows in test set:{len(test_set)}\n") from sklearn.model_selection import StratifiedShuffleSplit split=StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=42) for train_index,test_index in split.split(housing,housing["CHAS"]): strat_train_set=housing.loc[train_index] strat_test_set=housing.loc[test_index] strat_test_set strat_test_set.describe() strat_test_set.info() strat_test_set["CHAS"].value_counts() strat_train_set["CHAS"].value_counts() 95/7 376/28 housing=strat_train_set.copy() ``` # looking for corelation ``` corr_matrix=housing.corr() corr_matrix["MEDV"].sort_values(ascending=False) from pandas.plotting import scatter_matrix attributes=["MEDV","RM","ZN","LSTAT"] scatter_matrix(housing[attributes],figsize=(12,8)) housing.plot(kind="scatter",x="RM",y="MEDV",alpha=0.8) ``` # TRYING OUT ATTRIBUTE COMBINATIONS ``` housing["TAXRM"]=housing["TAX"]/housing["RM"] housing.head() corr_matrix=housing.corr() corr_matrix["MEDV"].sort_values(ascending=False) housing.plot(kind="scatter",x="TAXRM",y="MEDV",alpha=0.8) housing=strat_train_set.drop("MEDV",axis=1) housing_labels=strat_train_set["MEDV"].copy() #if some missing attributes is present so what we do??? #1.get rid of the missing data points #2.get rid of the whole attribute #3. set th evalue to some value(0,mean or median) #1.... #a=housing.dropna(subset=["RM"]) #2.... #housing.drop("RM",axis=1) #3..... #median=housing["RM"].median() #housing["RM"].fillna(median) from sklearn.impute import SimpleImputer imputer=SimpleImputer(strategy="median") imputer.fit(housing) imputer.statistics_ X=imputer.transform(housing) housing_tr=pd.DataFrame(X,columns=housing.columns) housing_tr.describe() ``` # feature scalling ``` #min max scalling #Standarzitaion ``` # creating pipeline ``` from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler my_pipeline=Pipeline([ ("imputer",SimpleImputer(strategy="median")), #.....add as many as you want in your pipeline ("std_scaler",StandardScaler()), ]) housing_num_tr=my_pipeline.fit_transform(housing_tr) housing_num_tr housing_num_tr.shape ``` # selecting a desired model for dragon real estate ``` from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor #model=LinearRegression() #model=DecissionTreeRegressor() model=RandomForestRegressor() model.fit(housing_num_tr,housing_labels) some_data=housing.iloc[:5] some_labels=housing_labels.iloc[:5] prepared_data=my_pipeline.transform(some_data) model.predict(prepared_data) list(some_labels) ``` # evaluating the model ``` from sklearn.metrics import mean_squared_error housing_predictions=model.predict(housing_num_tr) mse=mean_squared_error(housing_labels,housing_predictions) rmse=np.sqrt(mse) rmse ``` # using better evaluation technique- cross validation ``` from sklearn.model_selection import cross_val_score scores=cross_val_score(model,housing_num_tr,housing_labels,scoring="neg_mean_squared_error",cv=10) rmse_scores=np.sqrt(-scores) rmse_scores def print_scores(scores): print("Scores:",scores) print("Mean:",scores.mean()) print("Standard deviation:",scores.std()) print_scores(rmse_scores) ``` quiz:convert this notebook into a python file and run the pipeline using visual studio code # saving the model ``` from joblib import dump, load dump(model, 'Dragon.joblib') ``` ##testing the model on test data ``` X_test=strat_test_set.drop("MEDV",axis=1) Y_test=strat_test_set["MEDV"].copy() X_test_prepared=my_pipeline.transform(X_test) final_predictions=model.predict(X_test_prepared) final_mse=mean_squared_error(Y_test,final_predictions) final_rmse=np.sqrt(final_mse) print(final_predictions,list(Y_test)) final_rmse prepared_data[0] ``` ##using the model ``` from joblib import dump, load import numpy as np model=load('Dragon.joblib') features=np.array([[-0.43942006, 3.12628155, -1.12165014, -0.27288841, -1.42262747, -0.24141041, -1.31238772, 2.61111401, -1.0016859 , -0.5778192 , -0.97491834, 0.41164221, -0.86091034]]) model.predict(features) ```
github_jupyter
### This script relies on a active environment with Basemap If that is not possible, you properly have to outcomment a thing or two. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import time import geopandas as gpd from mpl_toolkits.basemap import Basemap import ezodf basePath = 'C:/Users/Krist/University College London/Digital Visualisation/Final Project/' ports_1 = gpd.read_file(basePath+'Data Sources/Global Ports Shapefile (1)/WPI.shp') countries = gpd.read_file(basePath+'Data Sources/countries (1)/ne_50m_admin_0_countries.shp').fillna(value='None') ``` # Let's see the ports. ``` # Let's visualise the ports # Plotting the civil airports plt.figure(figsize=(15,15)) map = Basemap() map.drawcoastlines() for port in ports_1.index: map.plot(list(ports_1.loc[port].geometry.coords)[0][0], list(ports_1.loc[port].geometry.coords)[0][1],color='darkblue',marker='o',markersize=3) plt.show() ``` ### Berief descriptive statistics ``` ports_1.columns ports_1.head() ports_1.shape ports_1.RAILWAY.unique() ports_1.HARBORSIZE.unique() print('Distribution of ports in each size category:\n\n', {size:sum([True if obs == size else False for obs in ports_1.HARBORSIZE]) for size in ports_1.HARBORSIZE.unique()}) print('Distribution of ports with Railway access:\n\n', {size:sum([True if obs == size else False for obs in ports_1.RAILWAY]) for size in ports_1.RAILWAY.unique()}) ``` ## Joining the countries shapefile with the ports But first ensuring country-classification attached on individual ports. #### We want the ports to have a country classification attach, i.e. a unique ISO_A3 code. This can be done via a spatial join of the ports and the geometries in the country shapefile. However, some of the countries (more like states) in the country-shapefile doesn't not have a ISO_A3 code, which is corrected below. Alternating the iso codes is needed, because some have a iso_code of -99 (Because it isn't a sovereign state) http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-0-details/ https://unstats.un.org/unsd/tradekb/Knowledgebase/Country-Code ``` # Ensuring correct ISO_A3 codes iso_codes = [] for iso,name,sov in zip(countries.ISO_A3,countries.NAME,countries.SOV_A3): if (iso == '-99') and (name != 'France'): print(name,sov) iso_codes.append(sov) elif (iso == '-99') and (name == 'France'): iso_codes.append('FRA') else: iso_codes.append(iso) countries['ISO3'] = np.array(iso_codes).astype('object') IsoCodes = countries[['ISO_A2','ISO3','SOV_A3','NAME']].sort_values(by=['ISO_A2']) IsoCodes = IsoCodes.reset_index(drop=True) # Manually based on their SOV_A3 code # Reference: https://www.iban.com/country-codes # Not bullet proof, but it works for the purpose for i in IsoCodes.index: if IsoCodes['ISO_A2'].loc[i]=='-99': #print(IsoCodes['ISO3'].loc[i][0:2]) IsoCodes['ISO_A2'].loc[i] = IsoCodes['ISO3'].loc[i][0:2] IsoCodes = IsoCodes.sort_values(by=['NAME']) #IsoCodes = IsoCodes.drop_duplicates(['ISO_A2']) IsoCodes = IsoCodes.set_index(['ISO_A2']) iso3CodePorts = [] nameCountryPorts = [] for country in ports_1.COUNTRY: if country in list(IsoCodes.index): if country == 'AU': iso3CodePorts.append('AUS') nameCountryPorts.append('Australia') elif country == 'SO': iso3CodePorts.append('SOM') nameCountryPorts.append('Somalia') elif country == 'CY': iso3CodePorts.append('CYP') nameCountryPorts.append('Cyprus') else: iso3CodePorts.append(IsoCodes['ISO3'].loc[country]) nameCountryPorts.append(IsoCodes['NAME'].loc[country]) else: iso3CodePorts.append('None') nameCountryPorts.append('None') ports_1['ISO3'] = np.array(iso3CodePorts) ports_1['CountryName'] = np.array(nameCountryPorts) ``` ### Performing the join ``` # Joining together the ports with the country file ports = gpd.sjoin(ports_1,countries,how='left') # Selecting the columns of interest ports = ports[['PORT_NAME','ISO3_left','CountryName','LATITUDE','LONGITUDE','HARBORSIZE','HARBORTYPE','RAILWAY','geometry']] # Renaming the chosen columns ports.columns=['port_name','iso3','country_name','latitude','longitude','harborsize','harbortype','railway','geometry'] ports.head() ``` ### Investigating the ports without any country-classification ``` # How many ports do not have a ISO3 code? sum([1 if iso == 'None' else 0 for iso in ports.iso3]) # Only continuing with the ports without country classification portsNoCountry = ports[[True if iso == 'None' else False for iso in ports.iso3]] print('The number of ports in each possible harbor size are:\n\n', {size:sum([True if harborsize == size else False for harborsize in ports.harborsize]) for\ size in ports.harborsize.unique()}) print('The number of ports without a country is:\n\n', {size:sum([1 if iso == 'None' else 0 for iso in portsNoCountry[[True if portsize == size else False for \ portsize in portsNoCountry.harborsize]].iso3])\ for size in portsNoCountry.harborsize.unique()}) ``` For now, nothing is done about the ports with missing country classification, as the amount is to small compared to total number of ports. ### Writing the files ``` gpdPorts = gpd.GeoDataFrame(ports,geometry=ports.geometry,crs = countries.crs) # Based on this answer: https://gis.stackexchange.com/questions/159681/geopandas-cant-save-geojson with open(basePath+'Final Data/ports.geojson', 'w') as f: f.write(gpdPorts.to_json()) portsToSave = ports.drop(['geometry'],axis=1) portsToSave.to_csv(basePath+'Final Data/ports.csv') ``` ### Potential Attributes ``` # The purpose below is to give an idea of the content of the potential attributes, which could be included for visualisation. print('The excluded columns are:\n\n', list(ports_1.columns)[0:16]+list(ports_1.columns)[-4:], '\n\nThey are excluded because the already are included or because there is too many unique values.', '\n\nThe potentially interesting attributes are:\n\n', np.array(ports_1.columns)[16:-4]) for potentialAtt in ports_1.columns: if potentialAtt in list(list(ports_1.columns)[16:-4]): print('\nThe name of the potential attribute is: %s\nThe unique values are:\n\n'%(potentialAtt), ports_1[potentialAtt].unique()) ``` ### The below is some exploratory stats on potentailly interesting categories. It is not at such important unless new attributes/dimensions is of interest We are interested in the largest ports around the world, namely 'M' and 'L'. ``` #sizeMLIndcies = [i for i,s in enumerate(ports_1.HARBORSIZE) if s in ('M','L')] sizeMLPorts = ports_1[(ports_1.HARBORSIZE == 'M') | (ports_1.HARBORSIZE == 'L')] sizeMLPorts = sizeMLPorts.reset_index(drop=True) # Plot the V sized ports # Plotting the civil airports plt.figure(figsize=(15,15)) map = Basemap() map.drawcoastlines() for port in sizeMLPorts.index: map.plot(list(sizeMLPorts.loc[port].geometry.coords)[0][0], list(sizeMLPorts.loc[port].geometry.coords)[0][1],color='darkblue',marker='o',markersize=3) plt.show() sizeMLPorts.head() ``` #### Let's take a look at some cargo-related variables. ``` cargoColumns = [column for column in ports_1.columns if 'cargo' in column.lower()] cargoColumns for column in cargoColumns: print('%s\n' % column) print({uniVal:sum([True if obs == uniVal else False for obs in ports_1[column]]) \ for uniVal in ports_1[column].unique()},'\n') ``` And cargo variables for our sized-subset ``` for column in cargoColumns: print('%s\n' % column) print({uniVal:sum([True if obs == uniVal else False for obs in sizeMLPorts[column]]) \ for uniVal in sizeMLPorts[column].unique()},'\n') ``` ### Country distribution ``` print({C:sum([True if obs == C else False for obs in sizeMLPorts.COUNTRY]) for C in sizeMLPorts.COUNTRY.unique()},'\n') print('\nThere are %i countries in the subset' % len(sizeMLPorts.COUNTRY.unique())) ``` ### End of exploratory stats ## Let's take a look at the UK Data ``` # Opening the Open Document Sheet doc = ezodf.opendoc(basePath+'Data Sources/UK Port Freight (2)/port-freight-statistics-2017/port0400.ods') # Data sheet sheet = doc.sheets[2] # A way to extract the data start = time.time() totalContent = [] for i,row in enumerate(sheet.rows()): if i == 0: columns = [cell.value for cell in row] columns = columns[:-1] # individualUKPortData = pd.DataFrame(columns = columns) if 0 < i: content = [cell.value for cell in row] totalContent.append(content[:-1]) #individualUKPortData.loc[i] = content individualUKPortData = pd.DataFrame(totalContent,columns = columns).fillna('None') end = time.time() print('The processing took %.3f seconds' % (end-start)) individualUKPortData.shape #individualUKPortData['Year'] = np.array(individualUKPortData['Year']).astype('datetime64') individualUKPortData.loc[0:10] ``` ### Let's see some unique values, to get an idea of the opportunities that the data presents. ``` for column in individualUKPortData.columns: print('This is "%s"'% column,'\n\n','The unique values are:\n\n',individualUKPortData[column].unique(),'\n\n') ``` From the above, it seems natural to consider the direction and the region for each port, as we already are restricted on the year. ``` individualUKPortData2017 = individualUKPortData[individualUKPortData.Year == 2017] print(individualUKPortData2017.shape) portsUK = pd.DataFrame(index=individualUKPortData2017['Reporting Port'].unique()) dataholder = [[] for i in np.arange(6)] # <- because there are 3 unique values in 'Regions' and 2 unique values in 'Directions' # plus a total column # Excluding the 'None' regions = [region for region in individualUKPortData2017.Region.unique() if region != 'None'] j = 0 for region in regions: temp = individualUKPortData2017[individualUKPortData2017.Region==region] for port in individualUKPortData2017['Reporting Port'].unique(): # Inwards dataholder[j].append(round(sum(temp[(temp['Reporting Port'] == port) & (temp.direction == 1)\ & (temp.Type == 'Tonnage')]['Value (thousands)'])/1000,3)) # Outwards dataholder[j+1].append(round(sum(temp[(temp['Reporting Port'] == port) & (temp.direction == 2)\ & (temp.Type == 'Tonnage')]['Value (thousands)'])/1000,3)) #dataholder[-1].append(dataholder[j][-1]+dataholder[j+1][-1]) j += 2 for column in np.arange(len(dataholder)): portsUK[str(column)] = dataholder[column] # print the regions, to set correct columns print(regions) portsUK.columns = ['domestic_traffic_inwards','domestic_traffic_outwards', 'european_union_traffic_inwards','european_union_traffic_outwards', 'non-eu_foreign_traffic_inwards','non-eu_foreign_traffic_outwards'] portsUK # Adding the total column portsUK['Total'] = portsUK.sum(axis=1) ``` ### It is now time to attach geometries to the constructed data ``` print('The number of UK ports present in the global ports file:', len([ukport for ukport in portsUK.index if \ any([True if ukport.lower() in globalports.lower() else False for globalports in ports.port_name])]),'\n') print('The ports present are:\n') [print(ukport) for ukport in portsUK.index if \ any([True if ukport.lower() in globalports.lower() else False for globalports in ports.port_name])] print() ``` ### Time to subset the UK-ports data ``` ports.head() portsUKinGlobal = portsUK[[True if any([True if (ukport.lower() in globalports.lower()) & (iso == 'GBR')\ else False for globalports,iso in zip(ports.port_name,ports.iso3)]) else False for ukport in portsUK.index]] portsUKinGlobal = portsUKinGlobal.sort_index() portsUKinGlobal ``` ### Time to subset the global-ports data, in order to merge the two subsetted DataFrames ``` portsGlobalInUK = ports[([True if any([True if ukport.lower() in globalport.lower()\ else False for ukport in portsUK.index]) \ else False for globalport in ports.port_name]) & (ports.iso3 == 'GBR')] portsGlobalInUK = portsGlobalInUK.sort_values(by=['port_name']) portsGlobalInUK = portsGlobalInUK.reset_index(drop=True) # Change this manually correction later portsGlobalInUK['port_name'].loc[17] = 'HULL' portsGlobalInUK = portsGlobalInUK.sort_values(by=['port_name']) portsGlobalInUK = portsGlobalInUK.reset_index(drop=True) portsGlobalInUK ``` Because there are found one more port UK in the global file, than the other way around, a inspection of the found ports above is needed. It is seen that two ports for Liverpool are detected, a minor and a large one. Comparing with the previous table, it is seen that the Liverpool-port of interest is the third largest in UK, which implies that we manually drop the minor Liverpool port found above. ``` portsGlobalInUK = portsGlobalInUK.drop([20]) portsGlobalInUK = portsGlobalInUK.reset_index(drop=True) portsGlobalInUK = portsGlobalInUK.set_index(portsUKinGlobal.index) # Joining together the subsetted dataframes UKports = portsUKinGlobal.join(portsGlobalInUK) UKports ``` ### Writing the files ``` gpdUKPorts = gpd.GeoDataFrame(UKports,geometry=UKports.geometry,crs = countries.crs) # Based on this answer: https://gis.stackexchange.com/questions/159681/geopandas-cant-save-geojson with open(basePath+'Final Data/UKports.geojson', 'w') as f: f.write(gpdUKPorts.to_json()) UKportsToSave = UKports.drop(['geometry'],axis=1) UKportsToSave.to_csv(basePath+'Final Data/UKports.csv') ```
github_jupyter
``` import tweepy import json import pandas as pd import csv import mysql.connector from mysql.connector import Error #imports for catching the errors from ssl import SSLError from requests.exceptions import Timeout, ConnectionError from urllib3.exceptions import ReadTimeoutError #Twitter API credentials consumer_key = "NDhGN1poxOV4el21shhNpFbbf" consumer_secret = "xk8ZtyEh6Hpq2zucqvcrqSDXm7gTredBC0T8S6T9mSCPZJhEmx" access_token = "825394860190470144-VmRgBQeYWF0MtoBYCrT4IA5ANzmDMwG" access_token_secret = "gkHs9Beab9lPsJA9bMCwCUITRqsTLkGIwdYl6xlav0jIu" #boundingbox ciudad de Madrid obtenido de https://boundingbox.klokantech.com/ madrid = [-3.7475842804,40.3721683069,-3.6409114868,40.4886258195] def connect(user_id, user_name, user_loc, user_follow_count,user_friends_count, user_fav_count,user_status_count, tweet_id,text,created_at,source, reply_id, reply_user_id, retweet_id,retweet_user_id, quote_id,quote_user_id, reply_count,retweet_count,favorite_count,quote_count, hashtags, mention_ids, place_id, place_name, coord): con = mysql.connector.connect(host = 'localhost', database='twitterdb', user='david', password = 'password', charset = 'utf8mb4',auth_plugin='mysql_native_password') cursor = con.cursor() try: if con.is_connected(): query = "INSERT INTO UsersMad (user_id, tweet_id,user_name, user_loc, user_follow_count,user_friends_count, user_fav_count,user_status_count) VALUES (%s,%s, %s, %s, %s, %s, %s, %s)" cursor.execute(query, (user_id, tweet_id, user_name, user_loc, user_follow_count,user_friends_count, user_fav_count,user_status_count)) query2 = "INSERT INTO PostsMad (tweet_id,user_id,text,created_at,source,reply_id, reply_user_id,retweet_id, retweet_user_id,quote_id,quote_user_id,reply_count,retweet_count,favorite_count,quote_count,place_id, place_name, coord,hashtags, mention_ids) VALUES (%s,%s, %s, %s, %s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s,%s, %s, %s, %s)" cursor.execute(query2, (tweet_id,user_id,text,created_at,source, reply_id, reply_user_id, retweet_id, retweet_user_id, quote_id,quote_user_id, reply_count,retweet_count,favorite_count,quote_count, place_id, place_name, coord, hashtags, mention_ids)) con.commit() except Error as e: print(e) print(text) #Carlota: He dejado este print, porque no era capaz de almacenar emojis por la codificacion. #Estoy casi segura de que se ha arreglado, pero por si acaso cursor.close() con.close() return class MyStreamListener(tweepy.StreamListener): def on_data(self,data): # Twitter returns data in JSON format - we need to decode it first try: decoded = json.loads(data) except Exception as e: print ("Error on_data: %s" % str(e)) #we don't want the listener to stop return True #LOCATION METADATA #En caso de estar geolocalizado guardar la geolocalizacion #Si esta geolocalizado dentro de un bounding box (no exacta) if decoded.get('place') is not None: place_id = decoded.get('place').get('id') place_name =decoded.get('place').get('name') else: place_id = 'None' place_name = 'None' #Si es localizacion exacta #Geo is deprecated, they suggest to use simply coordinates if decoded.get('coordinates') is not None: m_coord = decoded.get('coordinates')['coordinates'] #print(m_coord) coord=str(m_coord[0])+';'+str(m_coord[1]) #print(coord) #time.sleep(100) else: coord = 'None' #print(place_id) #USER METADATA user_name = '@' + decoded.get('user').get('screen_name') #nombre cuenta @itdUPM user_id=decoded.get('user').get('id') #id de la cuenta (int) user_loc=decoded.get('user').get('location') user_follow_count=decoded.get('user').get('followers_count') user_friends_count=decoded.get('user').get('friends_count') user_fav_count=decoded.get('user').get('favourites_count') user_status_count=decoded.get('user').get('statuses_count') #POST METADATA created_at = decoded.get('created_at') #Fecha tweet_id = decoded['id'] #tweet id (int64) source = decoded['source'] #string source (web client, android, iphone) interesante??? if decoded.get('truncated'): text = decoded['extended_tweet']['full_text'].replace('\n',' ') else: text = decoded['text'].replace('\n',' ') #Contenido tweet #REPLY METADATA reply_id=decoded['in_reply_to_status_id'] reply_user_id=decoded['in_reply_to_user_id'] #RETWEET if decoded.get('retweeted_status') is not None: retweet_id = decoded['retweeted_status'] ['id'] retweet_user_id = decoded['retweeted_status']['user']['id'] if decoded['retweeted_status']['truncated']: text = decoded['retweeted_status']['extended_tweet']['full_text'].replace('\n',' ') else: text = decoded['retweeted_status']['text'].replace('\n',' ') #Contenido tweet #Carlota: Si es un retweet los campos de nº de retweets favs etc vienen dentro de retweeted status #David: ok bien visto, he añadido el id de usuario retweeteado reply_count = decoded['retweeted_status']['reply_count'] #Number of times this Tweet has been replied to retweet_count = decoded['retweeted_status']['retweet_count'] #Number of times this Tweet has been retweeted favorite_count = decoded['retweeted_status']['favorite_count'] #how many times this Tweet has been liked by Twitter users. quote_count = decoded['retweeted_status']['quote_count'] #hashtags_list=decoded.get('retweeted_status').get('entities').get('hashtags') #mentions=decoded.get('retweeted_status').get('entities').get('user_mentions') #David: para esto hay que crear una cadena de texto recorriendo la lista, el #código estaba en la versión anterior... hashtags_list=decoded['retweeted_status']['entities']['hashtags'] mentions=decoded['retweeted_status']['entities']['user_mentions'] hashtags='' c=0 if len(hashtags_list)>0: for i in range(0, len(hashtags_list)-1): mh=hashtags_list[i].get('text') hashtags=hashtags+mh+';' c=c+1 mh=hashtags_list[c].get('text') hashtags=hashtags+str(mh) else: hashtags='None' mention_ids='' c=0 if len(mentions)>0: for i in range(0, len(mentions)-1): mid=mentions[i].get('id_str') mention_ids=mention_ids+mid+';'#use a different separator! c=c+1 mid=mentions[c].get('id_str') mention_ids=mention_ids+str(mid) else: mention_ids='None' #David: esto no sé si haría falta... este justo es un retweet de un post que a su ves #es un quote de una noticia, osea que hay dos pasos de conexión, pero el retweet #con el quote ya existe... lo guardamos pero hay que tenerlo en cuenta que es redundante #Carlota: Lo quito, porque tienes razon y no habia caido... #David. lo podemos dejar porque no son campos adicionales if decoded['retweeted_status']['is_quote_status']: if 'quoted_status' not in decoded['retweeted_status']: quote_id='None' quote_user_id='None' else: quote_id=decoded['retweeted_status']['quoted_status']['id'] quote_user_id=decoded['retweeted_status']['quoted_status']['user']['id'] else: quote_id='None' quote_user_id='None' else: reply_count = decoded['reply_count'] #Number of times this Tweet has been replied to retweet_count = decoded['retweet_count'] #Number of times this Tweet has been retweeted favorite_count = decoded['favorite_count'] #how many times this Tweet has been liked by Twitter users. quote_count = decoded['quote_count'] retweet_id = 'None' retweet_user_id = 'None' if decoded['is_quote_status']: if 'quoted_status' not in decoded: quote_id='None' quote_user_id='None' else: quote_id=decoded['quoted_status']['id'] quote_user_id=decoded['quoted_status']['user']['id'] else: quote_id='None' quote_user_id='None' hashtags_list=decoded.get('entities').get('hashtags') mentions=decoded.get('entities').get('user_mentions') hashtags='' c=0 if len(hashtags_list)>0: for i in range(0, len(hashtags_list)-1): mh=hashtags_list[i].get('text') hashtags=hashtags+mh+';' c=c+1 mh=hashtags_list[c].get('text') hashtags=hashtags+str(mh) else: hashtags='None' mention_ids='' c=0 if len(mentions)>0: for i in range(0, len(mentions)-1): mid=mentions[i].get('id_str') mention_ids=mention_ids+mid+';'#use a different separator! c=c+1 mid=mentions[c].get('id_str') mention_ids=mention_ids+str(mid) else: mention_ids='None' #insert data just collected into MySQL database connect(user_id, user_name, user_loc, user_follow_count,user_friends_count, user_fav_count,user_status_count, tweet_id,text,created_at,source, reply_id, reply_user_id, retweet_id,retweet_user_id, quote_id,quote_user_id, reply_count,retweet_count,favorite_count,quote_count, hashtags, mention_ids, place_id, place_name, coord) #print("Tweet colleted at: {} ".format(str(created_at))) def on_error(self, status_code): if status_code == 420: #returning False in on_error disconnects the stream return False # returning non-False reconnects the stream, with backoff. if __name__ == '__main__': print ('Starting') #authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) #create the api and the stream object myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener) #Filter the stream by keywords myStream.filter(locations = madrid) ```
github_jupyter
``` import os import sys import subprocess import numpy as np import pandas as pd from io import StringIO os.getcwd() from skempi_consts import * import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 import pylab pylab.rcParams['figure.figsize'] = (10.0, 8.0) df = skempi_df ddg1 = df[df.Protein.isin(G1)].DDG.values ddg2 = df[df.Protein.isin(G2)].DDG.values ddg3 = df[df.Protein.isin(G3)].DDG.values ddg4 = df[df.Protein.isin(G4)].DDG.values ddg5 = df[df.Protein.isin(G5)].DDG.values ddg1235 = df[df.Protein.isin(G1 + G2 + G3 + G5)].DDG.values # plt.hist(ddg1, bins=100, alpha=0.5, label="G1", normed=1, cumulative=False, histtype='bar') # plt.hist(ddg2, bins=100, alpha=0.5, label="G2", normed=1, cumulative=False, histtype='bar') # plt.hist(ddg3, bins=100, alpha=0.5, label="G3", normed=1, cumulative=False, histtype='bar') plt.hist(ddg4, bins=100, alpha=0.5, label="G4", normed=1, cumulative=False, histtype='bar') # plt.hist(ddg5, bins=100, alpha=0.5, label="G5", normed=1, cumulative=False, histtype='bar') plt.hist(ddg1235, bins=100, alpha=0.5, label="G1235", normed=1, cumulative=False, histtype='bar') plt.legend(loc='upper right') plt.title("DDG Distribution") plt.ylabel("Frequency") plt.grid(True) plt.show() skempi_df.head() from skempi_utils import * import skempi_consts as consts num_mut = 0 pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): num_mut += len(row["Mutation(s)_cleaned"].split(',')) pbar.update(1) pbar.close() num_mut from scipy.stats import pearsonr all_features = {} def get_temperature_array(records, agg=np.min): arr = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): arr_obs_mut = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) res_i, chain_id = mut.i, mut.chain_id t = tuple(row.Protein.split('_')) skempi_record = records[t] res = skempi_record[chain_id][res_i] temps = [a.temp for a in res.atoms] arr_obs_mut.append(np.mean(temps)) arr.append(agg(arr_obs_mut)) pbar.update(1) pbar.close() return arr skempi_records = load_skempi_structs(pdb_path="../data/pdbs_n", compute_dist_mat=True) all_features["B-factor"] = temp_arr = get_temperature_array(skempi_records, agg=np.min) pearsonr(temp_arr, skempi_df.DDG) from aaindex import * B = BLOSUM62 C = SKOJ970101 skempi_records = load_skempi_structs(pdb_path="../data/pdbs", compute_dist_mat=True) def comp_ei(mut, skempi_record, B, radius): P = skempi_record.get_profile(mut.chain_id) return EI(mut.m, mut.w, P, mut.i, B) def comp_cp(mut, skempi_record, C, radius): return CP(mut, skempi_record, C, radius) def get_ddg_ei_cp_arrays(M, func, radius=None): arr_ddg = [] arr_obs = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): ddg = row.DDG arr_ddg.append(ddg) arr_obs_mut = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) t = tuple(row.Protein.split('_')) skempi_record = skempi_records[t] obs = func(mut, skempi_record, M, radius) arr_obs_mut.append(obs) arr_obs.append(np.sum(arr_obs_mut)) pbar.update(1) pbar.close() return arr_ddg, arr_obs from itertools import product def grid_search_cp(matrices=[SKOJ970101, BASU010101], radiuses=[4, 5, 6, 7, 8, 9, 10]): res_dict = {} for C, angs in product(matrices, radiuses): key = (str(C), angs) arr_ddg, arr_cp = get_ddg_ei_cp_arrays(C, comp_cp, angs) res_dict[key] = (arr_ddg, arr_cp) cor_cp = pearsonr(arr_ddg, arr_cp) print("%s: CP: %s" % (key, cor_cp,)) return res_dict def grid_search_ei(matrices=[BLOSUM62, SKOJ970101, BASU010101]): res_dict = {} for B in matrices: key = str(B) arr_ddg, arr_ei = get_ddg_ei_cp_arrays(B, comp_ei) res_dict[key] = (arr_ddg, arr_ei) cor_ei = pearsonr(arr_ddg, arr_ei) print("%s: EI: %s" % (key, cor_ei,)) return res_dict # cps = grid_search_cp() def comp_cp_a_b(mut, skempi_record, C, radius): return CP_A_B(mut, skempi_record, C, radius) def get_ddg_cp_a_b_arrays(M, func, radius=None): arr_ddg = [] arr_obs_a = [] arr_obs_b = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): ddg = row.DDG arr_ddg.append(ddg) arr_obs_mut_a = [] arr_obs_mut_b = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) t = tuple(row.Protein.split('_')) skempi_record = skempi_records[t] obs_a, obs_b = func(mut, skempi_record, M, radius) arr_obs_mut_a.append(obs_a) arr_obs_mut_b.append(obs_b) arr_obs_a.append(np.sum(arr_obs_mut_a)) arr_obs_b.append(np.sum(arr_obs_mut_b)) pbar.update(1) pbar.close() return arr_ddg, arr_obs_a, arr_obs_b def grid_search_cp_a_b(matrices=[SKOJ970101, BASU010101], radiuses=[4, 5, 6, 7, 8, 9, 10]): res_dict = {} for C, angs in product(matrices, radiuses): key = (str(C), angs) arr_ddg, arr_cp_a, arr_cp_b = get_ddg_cp_a_b_arrays(C, comp_cp_a_b, angs) arr_cp = np.asarray(arr_cp_a) + np.asarray(arr_cp_b) res_dict[key] = (arr_ddg, arr_cp_a, arr_cp_b) cor_cp_a = pearsonr(arr_ddg, arr_cp_a) cor_cp_b = pearsonr(arr_ddg, arr_cp_b) cor_cp = pearsonr(arr_ddg, arr_cp) print("%s: CP_A: %s, CP_B: %s, CP %s" % (key, cor_cp_a, cor_cp_b, cor_cp)) return res_dict def CP_A_B(mut, skempi, C, radius=6): i, chain_a = mut.i, mut.chain_id m, w = mut.m, mut.w def helper(P, j): return sum([P[(j, a)] * (C[(a, m)] - C[(a, w)]) for a in amino_acids]) retA, retB = 0, 0 for chain_b, j in skempi.get_sphere_indices(chain_a, i,radius): a = skempi[chain_b][j].name if j == i and chain_b == chain_a: assert a == w continue P = skempi.get_profile(chain_b) if chain_b == chain_a: retA += helper(P, j) else: retB += helper(P, j) return retA, retB # cp_a_b_s_orig = grid_search_cp_a_b(matrices=[SKOJ970101, BASU010101], radiuses=[4, 5, 6, 7, 8, 9, 10]) def CP_A_B(mut, skempi, C, radius=6): i, chain_a = mut.i, mut.chain_id m, w = mut.m, mut.w def helper(a, j): return C[(a, m)] - C[(a, w)] retA, retB = 0, 0 for chain_b, j in skempi.get_sphere_indices(chain_a, i, radius): a = skempi[chain_b][j].name if j == i and chain_b == chain_a: assert a == w continue P = skempi.get_profile(chain_b) if chain_b == chain_a: retA += helper(a, j) else: retB += helper(a, j) return retA, retB # cp_a_b_s_no_profile = grid_search_cp_a_b(matrices=[BASU010101], radiuses=[2.5, 3.75, 5.0, 6.25, 7.5, 8.75, 10.0]) def CP_A_B(mut, skempi, C, radius=6): i, chain_a = mut.i, mut.chain_id m, w = mut.m, mut.w def helper(P, j): return sum([0.05 * (C[(a, m)] - C[(a, w)]) for a in amino_acids]) retA, retB = 0, 0 for chain_b, j in skempi.get_sphere_indices(chain_a, i,radius): a = skempi[chain_b][j].name if j == i and chain_b == chain_a: assert a == w continue P = skempi.get_profile(chain_b) if chain_b == chain_a: retA += helper(P, j) else: retB += helper(P, j) return retA, retB # cp_a_b_s_uniform = grid_search_cp_a_b(matrices=[SKOJ970101, BASU010101], radiuses=[6, 7]) eis = grid_search_ei(matrices=[BLOSUM62]) def register_cp_a_b(cp_a_b, prefix): for key, val in cp_a_b.iteritems(): _, cp_a, cp_b = val mat, rad = key all_features[(prefix, "CP_A", mat, rad)] = cp_a all_features[(prefix, "CP_B", mat, rad)] = cp_b def register_cp_a_b_shells(cp_a_b, prefix): for key, val in cp_a_b.iteritems(): _, cp_a, cp_b = val mat, inner, outer = key all_features[(prefix, "CP_A", mat, inner, outer)] = cp_a all_features[(prefix, "CP_B", mat, inner, outer)] = cp_b all_features[(prefix, "CP", mat, inner, outer)] = np.sum([cp_a, cp_b], axis=0) def register_eis(eis): for key, val in eis.iteritems(): _, ei = val all_features[("EI", key)] = ei def CP_A_B(mut, skempi, C, inner, outer): i, chain_a = mut.i, mut.chain_id m, w = mut.m, mut.w retA, retB = 0, 0 for chain_id, j in skempi.get_shell_indices(chain_a, i, inner, outer): a = skempi[chain_id][j].name if j == i and chain_id == chain_a: assert a == w continue P = skempi.get_profile(chain_id) if chain_id == chain_a: retA += C[(a, m)] - C[(a, w)] else: retB += C[(a, m)] - C[(a, w)] return retA, retB def get_cp_a_b_array(M, inner, outer): arr_obs_a = [] arr_obs_b = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): arr_obs_mut_a = [] arr_obs_mut_b = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) t = tuple(row.Protein.split('_')) skempi_record = skempi_records[t] obs_a, obs_b = CP_A_B(mut, skempi_record, M, inner, outer) arr_obs_mut_a.append(obs_a) arr_obs_mut_b.append(obs_b) arr_obs_a.append(np.sum(arr_obs_mut_a)) arr_obs_b.append(np.sum(arr_obs_mut_b)) pbar.update(1) pbar.close() return arr_obs_a, arr_obs_b matrices = [BASU010101] shells = [(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)] def grid_search_cp(matrices=matrices, shells=shells): res_dict = {} grid = [(mat, shell) for mat in matrices for shell in shells] for mat, (inner, outer) in grid: arr_cp_a, arr_cp_b = get_cp_a_b_array(mat, inner, outer) arr_cp = np.asarray(arr_cp_a) + np.asarray(arr_cp_b) arr_ddg = skempi_df.DDG cor_cp_a = pearsonr(arr_ddg, arr_cp_a) cor_cp_b = pearsonr(arr_ddg, arr_cp_b) cor_cp = pearsonr(arr_ddg, arr_cp) key = (str(mat), inner, outer) res_dict[key] = (arr_ddg, arr_cp_a, arr_cp_b) print("%s: CP_A: %s, CP_B: %s, CP %s" % (key, cor_cp_a, cor_cp_b, cor_cp)) return res_dict cp_a_b_s_shells = grid_search_cp(matrices, shells) # register_cp_a_b(cp_a_b_s_uniform, "uniform") # register_cp_a_b(cp_a_b_s_orig, "original") # register_cp_a_b(cp_a_b_s_no_profile, "no_profile") register_cp_a_b_shells(cp_a_b_s_shells, "shells") register_eis(eis) num_muts = np.asarray([len(mut.split(",")) for mut in skempi_df["Mutation(s)_cleaned"]]) pearsonr(skempi_df.DDG, np.log(num_muts)), pearsonr(skempi_df.DDG, num_muts) all_features["#mutations"] = np.log(num_muts) def get_stride_array(func, agg=np.sum): arr_stride = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): arr_obs_mut = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) res_i, chain_id = mut.i, mut.chain_id t = tuple(row.Protein.split('_')) skempi_record = skempi_records[t] d_asa = skempi_record.stride[(chain_id, res_i)] obs = func(d_asa) arr_obs_mut.append(obs) total = skempi_record.stride._total arr_stride.append((agg(arr_obs_mut), total)) pbar.update(1) pbar.close() return arr_stride asa_arr_mutated, asa_arr_total = zip(*get_stride_array(lambda stride: stride["ASA_Chain"]-stride["ASA"])) all_features["sum(ASA_Chain-ASA):mutated"] = asa_arr_mutated pearsonr(skempi_df.DDG, asa_arr_mutated) all_features["sum(ASA_Chain-ASA):total"] = asa_arr_total pearsonr(skempi_df.DDG, asa_arr_total) def get_desc_array(mat, agg=np.mean): arr = [] pbar = tqdm(range(len(skempi_df)), desc="row processed") for i, row in skempi_df.iterrows(): arr_obs_mut = [] for mutation in row["Mutation(s)_cleaned"].split(','): mut = Mutation(mutation) res_i, chain_id = mut.i, mut.chain_id t = tuple(row.Protein.split('_')) skempi_record = skempi_records[t] res = skempi_record[chain_id][res_i] desc = mat[mut.m] - mat[mut.w] arr_obs_mut.append(desc) arr.append(agg(arr_obs_mut)) pbar.update(1) pbar.close() return arr M = FASG760101 mol_arr = get_desc_array(M, np.mean) all_features["MolWeight"] = mol_arr pearsonr(mol_arr, skempi_df.DDG) H = ARGP820101 hyd_arr = get_desc_array(H, np.mean) all_features["Hydrophobic"] = hyd_arr pearsonr(hyd_arr, skempi_df.DDG) DSSP = ["G", "H", "I", "T", "E", "B", "S", "C"] from sklearn import preprocessing lb = preprocessing.LabelBinarizer() lb.fit(DSSP) def get_bin_ss(stride): return lb.transform([stride["SS"]])[0] from sklearn.decomposition import PCA ss_arr, _ = zip(*get_stride_array(get_bin_ss, agg=lambda a: np.sum(a, axis=0))) n_components = 3 ss_arr = PCA(n_components=n_components).fit_transform(ss_arr) [pearsonr(skempi_df.DDG, np.asarray(ss_arr)[:, j]) for j in range(n_components)] class XCor(object): def __init__(self, all_features): self.feat_name_to_indx = {key:i for i, key in enumerate(all_features.keys())} self.xcor_mat = np.corrcoef(np.asarray(all_features.values())) def __getitem__(self, t): feat1, feat2 = t i = self.feat_name_to_indx[feat1] j = self.feat_name_to_indx[feat2] return self.xcor_mat[(i, j)] xcor = XCor(all_features) import itertools def search_min_xcor(all_features, th=0.05): acc = set() for comb in itertools.combinations(all_features.keys(), 2): feat1, feat2 = comb rho = xcor[(feat1, feat2)] if abs(rho) < th: acc.add(feat1) acc.add(feat2) return acc acc_feats = search_min_xcor(all_features) len(acc_feats), acc_feats acc_feats = { '#mutations', 'B-factor', 'Hydrophobic', 'MolWeight', 'sum(ASA_Chain-ASA):mutated', ('EI', 'BLOSUM62'), # ('shells', 'CP_A', 'BASU010101', 0.0, 2.0), ('shells', 'CP_A', 'BASU010101', 2.0, 4.0), ('shells', 'CP_A', 'BASU010101', 4.0, 6.0), # ('shells', 'CP_B', 'BASU010101', 6.0, 8.0), # ('shells', 'CP_B', 'BASU010101', 0.0, 2.0), ('shells', 'CP_B', 'BASU010101', 2.0, 4.0), ('shells', 'CP_B', 'BASU010101', 4.0, 6.0), # ('shells', 'CP_B', 'BASU010101', 6.0, 8.0), } X = np.transpose([all_features[feat] for feat in acc_feats]) # X = np.concatenate([X, np.asarray(ss_arr)], axis=1) X.shape def records_to_xy(skempi_records, load_neg=False): data = [] for record in tqdm(skempi_records, desc="records processed"): r = record assert r.struct is not None data.append([r.features(True), [r.ddg], [r.group, r.is_minus]]) if not load_neg: continue X, y, ix = [np.asarray(d) for d in zip(*data)] return X, y, ix skempi_structs = load_skempi_structs("../data/pdbs", compute_dist_mat=False) skempi_records = load_skempi_records(skempi_structs) X_, y_, ix_ = records_to_xy(skempi_records, load_neg=True) X = X_[:, :] X = np.concatenate([X.T, [temp_arr]], axis=0).T y = y_[:, 0] ix = ix_ X.shape, y.shape, ix.shape df = skempi_df from sklearn.preprocessing import StandardScaler from itertools import combinations as comb def run_cv_test(X, get_regressor, normalize=0): gt, preds, cors = [], [], [] groups = [G1, G2, G3, G4, G5] prots = G1 + G2 + G3 + G4 + G5 for pair in comb(range(len(groups)), 2): group = groups[pair[0]] + groups[pair[1]] rest = list(set(prots) - set(group)) indx_tst = df.Protein.isin(group) indx_trn = df.Protein.isin(rest) # indx_trn = np.logical_not(indx_tst) y_trn = df.DDG[indx_trn] y_true = df.DDG[indx_tst] X_trn = X[indx_trn] X_tst = X[indx_tst] regressor = get_regressor() if normalize == 1: scaler = StandardScaler() scaler.fit(X_trn) X_trn, X_tst = scaler.transform(X_trn), scaler.transform(X_tst) regressor.fit(X_trn, y_trn) y_pred = regressor.predict(X_tst) cor, _ = pearsonr(y_true, y_pred) print("G%d" % (pair[0]+1), "G%d" % (pair[1]+1), "%.3f" % cor) cors.append(cor) preds.extend(y_pred) gt.extend(y_true) return gt, preds, cors from sklearn.ensemble import RandomForestRegressor def get_regressor(): return RandomForestRegressor(n_estimators=50, random_state=0) gt, preds, cors = run_cv_test(X, get_regressor, normalize=1) print("%.3f" % np.mean(cors)) from sklearn.svm import SVR def get_regressor(): return SVR(kernel='rbf') gt, preds, cors = run_cv_test(X, get_regressor, normalize=1) print("%.3f" % np.mean(cors)) def run_cv_test(X, alpha=0.5, normalize=1): gt, preds, cors = [], [], [] groups = [G1, G2, G3, G4, G5] prots = G1 + G2 + G3 + G4 + G5 for pair in comb(range(NUM_GROUPS), 2): group = groups[pair[0]] + groups[pair[1]] rest = list(set(prots) - set(group)) indx_tst = df.Protein.isin(group) indx_trn = df.Protein.isin(rest) y_trn = df.DDG[indx_trn] y_true = df.DDG[indx_tst] X_trn = X[indx_trn] X_tst = X[indx_tst] rf = RandomForestRegressor(n_estimators=50, random_state=0) svr = SVR(kernel='rbf') if normalize == 1: scaler = StandardScaler() scaler.fit(X_trn) X_trn, X_tst = scaler.transform(X_trn), scaler.transform(X_tst) svr.fit(X_trn, y_trn) rf.fit(X_trn, y_trn) y_pred_svr = svr.predict(X_tst) y_pred_rf = rf.predict(X_tst) y_pred = alpha * y_pred_svr + (1-alpha) * y_pred_rf cor, _ = pearsonr(y_true, y_pred) print("G%d" % (pair[0]+1), "G%d" % (pair[1]+1), "%.3f" % cor) cors.append(cor) preds.extend(y_pred) gt.extend(y_true) return gt, preds, cors gt, preds, cors = run_cv_test(X, normalize=1) print("%.3f" % np.mean(cors)) len(gt) def run_holdout_test(X, alpha=0.5, normalize=1): groups = [G1, G2, G3, G4, G5] prots = G1 + G2 + G3 + G4 + G5 indx_trn = df.Protein.isin(prots) indx_tst = np.logical_not(indx_trn) y_trn = df.DDG[indx_trn] y_true = df.DDG[indx_tst] X_trn = X[indx_trn] X_tst = X[indx_tst] rf = RandomForestRegressor(n_estimators=50, random_state=0) svr = SVR(kernel='rbf') if normalize == 1: scaler = StandardScaler() scaler.fit(X_trn) X_trn, X_tst = scaler.transform(X_trn), scaler.transform(X_tst) svr.fit(X_trn, y_trn) rf.fit(X_trn, y_trn) y_pred_svr = svr.predict(X_tst) y_pred_rf = rf.predict(X_tst) y_pred = alpha * y_pred_svr + (1-alpha) * y_pred_rf cor, _ = pearsonr(y_true, y_pred) print("holdout", "%.3f" % cor) return y_true, y_pred, cor gt, preds, cor = run_holdout_test(X, normalize=1) print("%.3f" % cor) len(gt) ```
github_jupyter
``` %matplotlib inline ``` # Probability Calibration for 3-class classification This example illustrates how sigmoid calibration changes predicted probabilities for a 3-class classification problem. Illustrated is the standard 2-simplex, where the three corners correspond to the three classes. Arrows point from the probability vectors predicted by an uncalibrated classifier to the probability vectors predicted by the same classifier after sigmoid calibration on a hold-out validation set. Colors indicate the true class of an instance (red: class 1, green: class 2, blue: class 3). The base classifier is a random forest classifier with 25 base estimators (trees). If this classifier is trained on all 800 training datapoints, it is overly confident in its predictions and thus incurs a large log-loss. Calibrating an identical classifier, which was trained on 600 datapoints, with method='sigmoid' on the remaining 200 datapoints reduces the confidence of the predictions, i.e., moves the probability vectors from the edges of the simplex towards the center. This calibration results in a lower log-loss. Note that an alternative would have been to increase the number of base estimators which would have resulted in a similar decrease in log-loss. ``` print(__doc__) # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD Style. import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import make_blobs from sklearn.ensemble import RandomForestClassifier from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import log_loss np.random.seed(0) # Generate data X, y = make_blobs(n_samples=1000, n_features=2, random_state=42, cluster_std=5.0) X_train, y_train = X[:600], y[:600] X_valid, y_valid = X[600:800], y[600:800] X_train_valid, y_train_valid = X[:800], y[:800] X_test, y_test = X[800:], y[800:] # Train uncalibrated random forest classifier on whole train and validation # data and evaluate on test data clf = RandomForestClassifier(n_estimators=25) clf.fit(X_train_valid, y_train_valid) clf_probs = clf.predict_proba(X_test) score = log_loss(y_test, clf_probs) # Train random forest classifier, calibrate on validation data and evaluate # on test data clf = RandomForestClassifier(n_estimators=25) clf.fit(X_train, y_train) clf_probs = clf.predict_proba(X_test) sig_clf = CalibratedClassifierCV(clf, method="sigmoid", cv="prefit") sig_clf.fit(X_valid, y_valid) sig_clf_probs = sig_clf.predict_proba(X_test) sig_score = log_loss(y_test, sig_clf_probs) # Plot changes in predicted probabilities via arrows plt.figure(0) colors = ["r", "g", "b"] for i in range(clf_probs.shape[0]): plt.arrow(clf_probs[i, 0], clf_probs[i, 1], sig_clf_probs[i, 0] - clf_probs[i, 0], sig_clf_probs[i, 1] - clf_probs[i, 1], color=colors[y_test[i]], head_width=1e-2) # Plot perfect predictions plt.plot([1.0], [0.0], 'ro', ms=20, label="Class 1") plt.plot([0.0], [1.0], 'go', ms=20, label="Class 2") plt.plot([0.0], [0.0], 'bo', ms=20, label="Class 3") # Plot boundaries of unit simplex plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex") # Annotate points on the simplex plt.annotate(r'($\frac{1}{3}$, $\frac{1}{3}$, $\frac{1}{3}$)', xy=(1.0/3, 1.0/3), xytext=(1.0/3, .23), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.plot([1.0/3], [1.0/3], 'ko', ms=5) plt.annotate(r'($\frac{1}{2}$, $0$, $\frac{1}{2}$)', xy=(.5, .0), xytext=(.5, .1), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.annotate(r'($0$, $\frac{1}{2}$, $\frac{1}{2}$)', xy=(.0, .5), xytext=(.1, .5), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.annotate(r'($\frac{1}{2}$, $\frac{1}{2}$, $0$)', xy=(.5, .5), xytext=(.6, .6), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.annotate(r'($0$, $0$, $1$)', xy=(0, 0), xytext=(.1, .1), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.annotate(r'($1$, $0$, $0$)', xy=(1, 0), xytext=(1, .1), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') plt.annotate(r'($0$, $1$, $0$)', xy=(0, 1), xytext=(.1, 1), xycoords='data', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='center', verticalalignment='center') # Add grid plt.grid("off") for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]: plt.plot([0, x], [x, 0], 'k', alpha=0.2) plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2) plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2) plt.title("Change of predicted probabilities after sigmoid calibration") plt.xlabel("Probability class 1") plt.ylabel("Probability class 2") plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) plt.legend(loc="best") print("Log-loss of") print(" * uncalibrated classifier trained on 800 datapoints: %.3f " % score) print(" * classifier trained on 600 datapoints and calibrated on " "200 datapoint: %.3f" % sig_score) # Illustrate calibrator plt.figure(1) # generate grid over 2-simplex p1d = np.linspace(0, 1, 20) p0, p1 = np.meshgrid(p1d, p1d) p2 = 1 - p0 - p1 p = np.c_[p0.ravel(), p1.ravel(), p2.ravel()] p = p[p[:, 2] >= 0] calibrated_classifier = sig_clf.calibrated_classifiers_[0] prediction = np.vstack([calibrator.predict(this_p) for calibrator, this_p in zip(calibrated_classifier.calibrators_, p.T)]).T prediction /= prediction.sum(axis=1)[:, None] # Plot modifications of calibrator for i in range(prediction.shape[0]): plt.arrow(p[i, 0], p[i, 1], prediction[i, 0] - p[i, 0], prediction[i, 1] - p[i, 1], head_width=1e-2, color=colors[np.argmax(p[i])]) # Plot boundaries of unit simplex plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex") plt.grid("off") for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]: plt.plot([0, x], [x, 0], 'k', alpha=0.2) plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2) plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2) plt.title("Illustration of sigmoid calibrator") plt.xlabel("Probability class 1") plt.ylabel("Probability class 2") plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) plt.show() ```
github_jupyter
# VIPERS SHAM Project This notebook is part of the VIPERS-SHAM project: http://arxiv.org/abs/xxxxxxx Copyright 2019 by Ben Granett, granett@gmail.com All rights reserved. This file is released under the "MIT License Agreement". Please see the LICENSE file that should have been included as part of this package. ``` %matplotlib inline import os from matplotlib import pyplot as plt plt.style.use("small.style") from matplotlib.ticker import FormatStrFormatter,ScalarFormatter, MultipleLocator from matplotlib import colors,cm import logging logging.basicConfig(level=logging.INFO) from scipy import interpolate, integrate import numpy as np import growthcalc import load import emulator samples = ['sdss','L1','L2','L3','L4'] redshifts = {'sdss':.06, 'L1':0.6, 'L2':0.7, 'L3':0.8, 'L4':0.9} rmin = 1 n_components = 2 thresh = 0.1 def chi2_svd(d, cmat, thresh=0.1): """ """ u,s,v = np.linalg.svd(cmat) cut = np.abs(s).max()*thresh o = np.abs(s)>cut s = s[o] v = v[o] d_ = np.dot(v, d) chi2 = np.sum(d_**2/s) return chi2 def limits(x, y, t=1): best = y.argmin() x0 = x[best] ybest = y[best] thresh = ybest + t yup = y[best:] b = best + yup.searchsorted(thresh) ydown = y[:best][::-1] a = best - ydown.searchsorted(thresh) if a < 0: a = None if b >= len(x): b = None return best, a, b r_sdss,wp_sdss,cov_sdss = load.load_sdss() sel = r_sdss > rmin r_sdss = r_sdss[sel] wp_sdss = wp_sdss[sel] cov_sdss = cov_sdss[sel,:][:,sel] data = [(r_sdss, wp_sdss, cov_sdss)] for sample in samples[1:]: r,wp = np.loadtxt('../data/vipers/wp_sM{sample}.txt'.format(sample=sample[1]), unpack=True) cmat = np.loadtxt('../data/vipers/cov_{sample}.txt'.format(sample=sample)) sel = r > rmin r = r[sel] wp = wp[sel] cmat = cmat[sel,:][:,sel] data.append((r,wp,cmat)) shamdata = {} for sample in ['sdss','L1','L2','L3','L4']: sham = load.load_sham(sample=sample, template="../data/sham400/nz_{sample}/wp_snap{snapshot:7.5f}.txt") snapshots = sham.keys() snapshots.sort() for key in snapshots: r, wp = sham[key] sel = r > rmin r = r[sel] wp = wp[sel] if not sample in shamdata: shamdata[sample] = [] shamdata[sample].append((key, r, wp)) a_samples = [] interpolators = [] for key in samples: y = [] x = [] for a,r,w in shamdata[key]: sel = r > rmin r = r[sel] y.append(w[sel]) x.append(a) y = np.array(y) x = np.array(x) f = emulator.WpInterpolator(x, r, y, n_components) interpolators.append(f) a_samples.append(1./(1+redshifts[key])) a_samples = np.array(a_samples) G = growthcalc.Growth(amax=10) plt.figure(figsize=(9,3)) markers = ('.','*','*','*','*') left = plt.subplot(121) right = plt.subplot(122) left.set_xlabel("Snapshot redshift") left.set_ylabel("$\chi^2$") left.grid(True) left.set_yscale('log') left.yaxis.set_major_formatter(FormatStrFormatter('%g')) left.xaxis.set_major_locator(MultipleLocator(0.2)) left.xaxis.set_minor_locator(MultipleLocator(0.1)) right.yaxis.set_minor_locator(MultipleLocator(0.1)) right.xaxis.set_minor_locator(MultipleLocator(0.1)) right.set_ylabel("Snapshot redshift") right.set_xlabel("Sample redshift") right.grid(True) right.set_xlim(0,1.1) right.set_ylim(0,1.1) right2 = right.twinx() right2.set_ylabel("$\sigma_8(z)$") lab_sig8 = np.arange(0.3,1.01,0.05) lab_z = G.fid_inv(lab_sig8) zz = np.linspace(-0.3,1.5,100) for gamma in [0.4, 0.55, 0.7, 0.85]: z_w = G.fid_inv(G(zz, gamma=gamma)) l, = right.plot(zz, z_w, c='grey', lw=1, zorder=5) right.text(1.1, 1.15, "$\gamma=%3.2f$"%0.4, color='k', ha='right',va='center', rotation=25,zorder=5,fontsize=12) right.text(1.1, 1.1, "$%3.2f$"%0.55, color='k', ha='right',va='center', rotation=24,zorder=5,fontsize=12) right.text(1.1, 0.99, "$%3.2f$"%0.7, color='k', ha='right',va='center', rotation=22,zorder=5,fontsize=12) right.text(1.1, 0.81,"$%3.2f$"%0.85, color='k', ha='right',va='center', rotation=20,zorder=5,fontsize=12) print zip(lab_z,lab_sig8) right2.set_yticks(lab_z) right2.set_yticklabels("%3.2f"%x for x in lab_sig8) right2.set_ylim(0, 1.2) right2.set_xlim(-0.3, 1.5) right.set_xlim(0,1.1) right.set_ylim(-0.3,1.5) right.set_xticks([0.2,0.4,0.6,0.8,1.]) for i,sample in enumerate(samples): f = interpolators[i] chi2 = [] r,wp,cmat = data[i] for z in zz: wpsham = f(1./(1+z)) d = wp - wpsham c = chi2_svd(d, cmat, thresh=thresh) chi2.append(c) chi2 = np.array(chi2) like = np.exp(-0.5*(chi2-chi2.min())) print "min chi2",sample,chi2.min() lines = left.plot(zz,chi2) chi2_ = [] zcent = [] for asham,rsham,wpsham in shamdata[sample]: d = wp - wpsham c = chi2_svd(d, cmat, thresh=thresh) chi2_.append(c) zcent.append(1./asham - 1) chi2_ = np.array(chi2_) print "min chi2",sample,chi2_.min() left.scatter(zcent,chi2_, marker=markers[i], color=lines[0].get_color(),zorder=10) j = chi2.argmin() if sample=='sdss': left.text(-0.05,1.5,"SDSS",color=lines[0].get_color(),va='bottom',ha='center',fontsize=12) right.text(.08, -0.08, "SDSS", color=lines[0].get_color(),va='center',ha='left',fontsize=12) elif sample=='L1': left.text(zz[-1],chi2[-1]*1.1,'M1',color=lines[0].get_color(),va='bottom',ha='right',fontsize=12) right.text(0.6,0.25,"M1", color=lines[0].get_color(),va='bottom',ha='center',fontsize=12) elif sample=='L2': left.text(zz[j]+0.08,chi2[j],'M2',color=lines[0].get_color(),va='bottom',ha='left',fontsize=12) right.text(0.7,0.35,"M2", color=lines[0].get_color(),va='bottom',ha='center',fontsize=12) elif sample=='L3': left.text(zz[j], chi2[j]*0.9,'M3',color=lines[0].get_color(),va='top',ha='center',fontsize=12) right.text(0.8,0.35,"M3", color=lines[0].get_color(),va='bottom',ha='center',fontsize=12) elif sample=='L4': left.text(zz[50],chi2[50]*1.1,'M4',color=lines[0].get_color(),va='bottom',ha='left',fontsize=12) right.text(0.9,0.6,"M4", color=lines[0].get_color(),va='bottom',ha='center',fontsize=12) a,b,c = limits(zz, chi2) zobs = redshifts[sample] if b is None: # upper limit logging.warning("upper limit! %s %s %s",a,b,c) pass elif c is None: # lower limit logging.warning("lower limit! %s %s %s",a,b,c) plt.arrow(zobs, zz[b], 0, 1.2-zz[b], lw=2.5, head_width=.015, head_length=0.03, color=lines[0].get_color(), zorder=10) else: right.plot([zobs, zobs], [zz[b], zz[c]], lw=3,color=lines[0].get_color(), zorder=10) right.scatter(zobs, zz[a], marker=markers[i], color=lines[0].get_color(),zorder=10) right.set_yticks([-0.2,0,0.2,0.4,0.6,0.8,1.0,1.2,1.4]) left.set_ylim(0.04, 50) right.set_ylim(-0.3,1.5) right2.set_ylim(-0.3,1.5) plt.subplots_adjust(left=0.07,right=.92, bottom=0.18) plt.savefig("../figs/fig8.pdf") ```
github_jupyter
## UTAH FORGE PROJECT'S MISSION Enable cutting-edge research and drilling and technology testing, as well as to allow scientists to identify a replicable, commercial pathway to EGS. In addition to the site itself, the FORGE effort will include a robust instrumentation, data collection, and data dissemination component to capture and share data and activities occurring at FORGE in real time. The innovative research, coupled with an equally-innovative collaboration and management platform, is truly a first of its kind endeavor. More details here https://utahforge.com/ #### The data used in this repository comes from the public data provided by Utah FORGE https://gdr.openei.org/submissions/1111 ##### Some functions adapted from https://sainosmichelle.github.io/elements.html ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import lasio import seaborn as sns %matplotlib inline import warnings warnings.filterwarnings('ignore') ``` #### Read main logs in ft ``` main = lasio.read('./localUTAHFORGEDATA/58-32_main.las') dfmain = main.df() print(dfmain.index) dfmain.head(5) ``` #### Read sonic logs in ft ``` sonic = lasio.read('./localUTAHFORGEDATA/58-32_sonic.las') dfsonicall = sonic.df() dfsonicall['VpVs']= ((1/dfsonicall['DTCO'])/(1/dfsonicall['DTSM'])) dfsonic = dfsonicall[['DT1R','DT2','DT2R','DT4P','DT4S','DTCO','DTRP','DTRS','DTSM','ITT','PR','SPHI','VpVs']] print(dfsonic.index) ``` #### Merge main and sonic logs (not repeated curves) using pandas ``` all_logs = pd.concat([dfmain, dfsonic], axis=1, sort=False) #all_logs.info() fig, ax = plt.subplots(figsize=(25,8)) sns.heatmap(all_logs.isnull(), ax=ax, cmap="magma") plt.grid() plt.show() ``` #### Calculations based on publication "Well-log based prediction of thermal conductivity of sedimentary successions: a case study from the North German Basin. Fuchs, S., and Foster, A. Geophysical Journal International. 2014. 196, pg 291-311. doi: 10.1093/gji/ggt382 ``` #calculate Vsh from GR formula Vsh=(subdata.GR_EDTC-grmin)/(grmax-grmin) all_logs['Vsh'] = all_logs['GR'] - min(all_logs['GR'])/(max(all_logs['GR'])- min(all_logs['GR'])) #calculate NPHI matrix from NPHI porosity and DEN porosity neu_m=subdata.NPOR-subdata.DPHZ all_logs['NPOR_m'] = (all_logs['NPOR']) - (all_logs['DPHZ']) #calculate eq10 #Matrix-TC equation derived from regression analysis for clastic rock types all_logs['eq10'] = (5.281-(2.961*all_logs['NPOR_m'])-(2.797*all_logs['Vsh']))/-272.15 #calculate eq11 #Bulk-TC equation derived from regression analysis for subsurface data all_logs['eq11'] = (4.75-(4.19*all_logs['NPOR'])-(1.81*all_logs['Vsh']))/-272.15 #all_logs.info() #read discrete data - conversion to ft - depth equal to lower depth interval tops = pd.read_csv('s3://geotermaldata/S3UTAHFORGEDATA/58-32_tops.csv') #Thermal Conductivity TC_coredata = pd.read_csv ('s3://geotermaldata/S3UTAHFORGEDATA/58-32_thermal_conductivity_data.csv') TC_coredata['Depth'] = (3.28084*TC_coredata['Lower Depth Interval (m)']) TC_coredata['Matrix_TC']=TC_coredata['matrix thermal conductivity (W/m deg C)'] TC_coredata.set_index('Depth', inplace=True) #XRD lab data XRD_coredata = pd.read_csv ('s3://geotermaldata/S3UTAHFORGEDATA/58-32_xray_diffraction_data.csv') XRD_coredata = XRD_coredata.replace('tr',0) XRD_coredata['Depth'] = (3.28084*XRD_coredata['Lower Depth Range (m)']) XRD_coredata.set_index('Depth', inplace=True) #TC_coredata.tail(15) XRD_coredata.head() #basic plot to inspect data def make_layout_tc (log_df, XRD, TC): import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt fig, axs = plt.subplots(nrows=1, ncols=6, sharey=True, squeeze=True, figsize=(15, 15), gridspec_kw={'wspace': 0.25}) fig.subplots_adjust(left=0.05, bottom=0.05, right=0.975, top=0.7, wspace=0.2, hspace=0.2) axs[0].set_ylabel('Depth (ft)') axs[0].invert_yaxis() axs[0].get_xaxis().set_visible(False) # First track GR/SP/CALI logs to display ax1 = axs[0].twiny() ax1.plot(log_df.GR, log_df.index, '-', color='#2ea869', linewidth=0.5) ax1.set_xlim(0,450) ax1.set_xlabel('GR (API)', color='#2ea869') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.15)) ax2 = axs[0].twiny() ax2.plot(log_df.SP, log_df.index, '-', color='#0a0a0a', linewidth=0.7) ax2.set_xlim(-200,200) ax2.set_xlabel('SP(mV)', color='#0a0a0a') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.075)) ax3 = axs[0].twiny() ax3.plot(log_df.DCAL, log_df.index, '--', color='#9da4a1', linewidth=0.5) ax3.set_xlim(-5,15) ax3.set_xlabel('DCAL (in)', color='#9da4a1') ax3.minorticks_on() ax3.spines['top'].set_position(('axes', 1.0)) ax3.grid(True) axs[0].get_xaxis().set_visible(False) # Second track RHOB/NPHI/PEF logs to display ax1 = axs[1].twiny() ax1.plot(log_df.RHOZ, log_df.index, '-', color='#ea0606', linewidth=0.5) ax1.set_xlim(1.5,3.0) ax1.set_xlabel('RHOB (g/cm3)', color='#ea0606') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.15)) ax2 = axs[1].twiny() ax2.plot(log_df.NPHI, log_df.index, '-', color='#1577e0', linewidth=0.5) ax2.set_xlim(1,0) ax2.set_xlabel('NPHI (v/v)', color='#1577e0') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.075)) ax3 = axs[1].twiny() ax3.plot(log_df.PEFZ, log_df.index, '-', color='#1acb20', linewidth=0.5) ax3.set_xlim(0,15) ax3.set_xlabel('PEFZ (b/e)', color='#1acb20') ax3.minorticks_on() ax3.spines['top'].set_position(('axes', 1.0)) ax3.grid(True) axs[1].get_xaxis().set_visible(False) # Third track Resistivities ax1 = axs[2].twiny() ax1.plot(log_df.AT10, log_df.index, '-', color='#d6dbd7', linewidth=0.5) ax1.set_xlim(0.2,20000) ax1.set_xlabel('AT10 (ohm.m)', color='#d6dbd7') ax1.set_xscale('log') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.15)) ax2 = axs[2].twiny() ax2.plot(log_df.AT30, log_df.index, '-', color='#0a0a0a', linewidth=0.5) ax2.set_xlim(0.2,20000) ax2.set_xlabel('AT30 (ohm.m)', color='#0a0a0a') ax2.set_xscale('log') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.075)) ax3 = axs[2].twiny() ax3.plot(log_df.AT90, log_df.index, '-', color='#ea0606', linewidth=0.5) ax3.set_xlim(0.2,20000) ax3.set_xlabel('AT90 (ohm.m)', color='#ea0606') ax3.set_xscale('log') ax3.minorticks_on() ax3.spines['top'].set_position(('axes', 1.0)) ax3.grid(True) axs[2].get_xaxis().set_visible(False) # Forth track Sonic ax1 = axs[3].twiny() ax1.plot(log_df.DTSM, log_df.index, '-', color='#9da4a1', linewidth=0.5) ax1.set_xlim(200,40) ax1.set_xlabel('DTS (us/ft)', color='#9da4a1') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.15)) ax2 = axs[3].twiny() ax2.plot(log_df.DTCO, log_df.index, '-', color='#0a0a0a', linewidth=0.5) ax2.set_xlim(200,40) ax2.set_xlabel('DTC (us/ft)', color='#0a0a0a') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.075)) ax3 = axs[3].twiny() ax3.plot(log_df.VpVs, log_df.index, '-', color='#e1093f', linewidth=0.5) ax3.set_xlim(1,3) ax3.set_xlabel('VpVs (unitless)', color='#e1093f') ax3.minorticks_on() ax3.spines['top'].set_position(('axes', 1.0)) ax3.grid(True) axs[3].get_xaxis().set_visible(False) # Fifth track XRD to display ax1 = axs[4].twiny() ax1.plot(XRD.Quartz, XRD.index, 'o', color='#eac406') ax1.set_xlim(0,100) ax1.set_xlabel('Quartz %', color='#eac406') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.15)) ax2 = axs[4].twiny() ax2.plot(XRD['K-feldspar'], XRD.index, 'o', color='#05a9f0') ax2.set_xlim(0,100) ax2.set_xlabel('K-feldspar %', color='#05a9f0') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.075)) ax3 = axs[4].twiny() ax3.plot(XRD['Illite'], XRD.index, 'o', color='#94898c') ax3.set_xlim(0,100) ax3.set_xlabel('Illite %', color='#94898c') ax3.minorticks_on() ax3.spines['top'].set_position(('axes', 1.0)) ax3.grid(True) axs[4].get_xaxis().set_visible(False) # Sixth track Temp/TC to display ax1 = axs[5].twiny() ax1.plot(TC.Matrix_TC, TC.index, 'o', color='#6e787c') ax1.set_xlim(0,5) ax1.set_xlabel('Matrix TC Measured W/mC', color='#6e787c') ax1.minorticks_on() ax1.spines['top'].set_position(('axes', 1.075)) ax2 = axs[5].twiny() ax2.plot(log_df.CTEM, log_df.index, '-', color='#ed8712') ax2.set_xlim(0,300) ax2.set_xlabel('Temp degF', color='#ed8712') ax2.minorticks_on() ax2.spines['top'].set_position(('axes', 1.0)) ax2.grid(True) axs[5].get_xaxis().set_visible(False) fig.suptitle('Well Data for UTAH FORGE 58-32',weight='bold', fontsize=20, y=0.9); plt.show() make_layout_tc (all_logs, XRD_coredata, TC_coredata) all_logs.to_csv('./localUTAHFORGEDATA/all_logs.csv') ```
github_jupyter
##### Copyright 2018 The TF-Agents Authors. ### Get Started <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/agents/blob/master/tf_agents/colabs/1_dqn_tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/agents/blob/master/tf_agents/colabs/1_dqn_tutorial.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> ``` # Note: If you haven't installed the following dependencies, run: !apt-get install xvfb !pip install 'gym==0.10.11' !pip install imageio !pip install PILLOW !pip install pyglet !pip install pyvirtualdisplay !pip install tf-agents-nightly !pip install tf-nightly ``` ## Introduction This example shows how to train a [DQN (Deep Q Networks)](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf) agent on the Cartpole environment using the TF-Agents library. ![Cartpole environment](images/cartpole.png) We will walk you through all the components in a Reinforcement Learning (RL) pipeline for training, evaluation and data collection. ## Setup ``` import base64 import imageio import IPython import matplotlib import matplotlib.pyplot as plt import PIL.Image import pyvirtualdisplay import tensorflow as tf from tf_agents.agents.dqn import dqn_agent from tf_agents.agents.dqn import q_network from tf_agents.drivers import dynamic_step_driver from tf_agents.environments import suite_gym from tf_agents.environments import tf_py_environment from tf_agents.environments import trajectory from tf_agents.metrics import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.policies import random_tf_policy from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.utils import common tf.compat.v1.enable_v2_behavior() # Set up a virtual display for rendering OpenAI gym environments. display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() ``` ## Hyperparameters ``` env_name = 'CartPole-v0' # @param num_iterations = 20000 # @param initial_collect_steps = 1000 # @param collect_steps_per_iteration = 1 # @param replay_buffer_capacity = 100000 # @param fc_layer_params = (100,) batch_size = 64 # @param learning_rate = 1e-3 # @param log_interval = 200 # @param num_eval_episodes = 10 # @param eval_interval = 1000 # @param ``` ## Environment Environments in RL represent the task or problem that we are trying to solve. Standard environments can be easily created in TF-Agents using `suites`. We have different `suites` for loading environments from sources such as the OpenAI Gym, Atari, DM Control, etc., given a string environment name. Now let us load the CartPole environment from the OpenAI Gym suite. ``` env = suite_gym.load(env_name) ``` We can render this environment to see how it looks. A free-swinging pole is attached to a cart. The goal is to move the cart right or left in order to keep the pole pointing up. ``` #@test {"skip": true} env.reset() PIL.Image.fromarray(env.render()) ``` The `time_step = environment.step(action)` statement takes `action` in the environment. The `TimeStep` tuple returned contains the environment's next observation and reward for that action. The `time_step_spec()` and `action_spec()` methods in the environment return the specifications (types, shapes, bounds) of the `time_step` and `action` respectively. ``` print 'Observation Spec:' print env.time_step_spec().observation print 'Action Spec:' print env.action_spec() ``` So, we see that observation is an array of 4 floats: the position and velocity of the cart, and the angular position and velocity of the pole. Since only two actions are possible (move left or move right), the `action_spec` is a scalar where 0 means "move left" and 1 means "move right." ``` time_step = env.reset() print 'Time step:' print time_step action = 1 next_time_step = env.step(action) print 'Next time step:' print next_time_step ``` Usually we create two environments: one for training and one for evaluation. Most environments are written in pure python, but they can be easily converted to TensorFlow using the `TFPyEnvironment` wrapper. The original environment's API uses numpy arrays, the `TFPyEnvironment` converts these to/from `Tensors` for you to more easily interact with TensorFlow policies and agents. ``` train_py_env = suite_gym.load(env_name) eval_py_env = suite_gym.load(env_name) train_env = tf_py_environment.TFPyEnvironment(train_py_env) eval_env = tf_py_environment.TFPyEnvironment(eval_py_env) ``` ## Agent The algorithm that we use to solve an RL problem is represented as an `Agent`. In addition to the DQN agent, TF-Agents provides standard implementations of a variety of `Agents` such as [REINFORCE](http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf), [DDPG](https://arxiv.org/pdf/1509.02971.pdf), [TD3](https://arxiv.org/pdf/1802.09477.pdf), [PPO](https://arxiv.org/abs/1707.06347) and [SAC](https://arxiv.org/abs/1801.01290). The DQN agent can be used in any environment which has a discrete action space. To create a DQN Agent, we first need a `Q-Network` that can learn to predict `Q-Values` (expected return) for all actions given an observation from the environment. We can easily create a `Q-Network` using the specs of the observations and actions. We can specify the layers in the network which, in this example, is the `fc_layer_params` argument set to a tuple of `ints` representing the sizes of each hidden layer (see the Hyperparameters section above). ``` q_net = q_network.QNetwork( train_env.observation_spec(), train_env.action_spec(), fc_layer_params=fc_layer_params) ``` We also need an `optimizer` to train the network we just created, and a `train_step_counter` variable to keep track of how many times the network was updated. ``` optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate) train_step_counter = tf.compat.v2.Variable(0) tf_agent = dqn_agent.DqnAgent( train_env.time_step_spec(), train_env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn=dqn_agent.element_wise_squared_loss, train_step_counter=train_step_counter) tf_agent.initialize() ``` ## Policies In TF-Agents, policies represent the standard notion of policies in RL: given a `time_step` produce an action or a distribution over actions. The main method is `policy_step = policy.step(time_step)` where `policy_step` is a named tuple `PolicyStep(action, state, info)`. The `policy_step.action` is the `action` to be applied to the environment, `state` represents the state for stateful (RNN) policies and `info` may contain auxiliary information such as log probabilities of the actions. Agents contain two policies: the main policy that is used for evaluation/deployment (agent.policy) and another policy that is used for data collection (agent.collect_policy). ``` eval_policy = tf_agent.policy collect_policy = tf_agent.collect_policy ``` We can also independently create policies that are not part of an agent. For example, a random policy: ``` random_policy = random_tf_policy.RandomTFPolicy(train_env.time_step_spec(), train_env.action_spec()) ``` ## Metrics and Evaluation The most common metric used to evaluate a policy is the average return. The return is the sum of rewards obtained while running a policy in an environment for an episode, and we usually average this over a few episodes. We can compute the average return metric as follows. ``` #@test {"skip": true} def compute_avg_return(environment, policy, num_episodes=10): total_return = 0.0 for _ in range(num_episodes): time_step = environment.reset() episode_return = 0.0 while not time_step.is_last(): action_step = policy.action(time_step) time_step = environment.step(action_step.action) episode_return += time_step.reward total_return += episode_return avg_return = total_return / num_episodes return avg_return.numpy()[0] compute_avg_return(eval_env, random_policy, num_eval_episodes) # Please also see the metrics module for standard implementations of different # metrics. ``` ## Replay Buffer In order to keep track of the data collected from the environment, we will use the TFUniformReplayBuffer. This replay buffer is constructed using specs describing the tensors that are to be stored, which can be obtained from the agent using `tf_agent.collect_data_spec`. ``` replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=tf_agent.collect_data_spec, batch_size=train_env.batch_size, max_length=replay_buffer_capacity) ``` For most agents, the `collect_data_spec` is a `Trajectory` named tuple containing the observation, action, reward etc. ## Data Collection Now let us execute the random policy in the environment for a few steps and record the data (observations, actions, rewards etc) in the replay buffer. ``` #@test {"skip": true} def collect_step(environment, policy): time_step = environment.current_time_step() action_step = policy.action(time_step) next_time_step = environment.step(action_step.action) traj = trajectory.from_transition(time_step, action_step, next_time_step) # Add trajectory to the replay buffer replay_buffer.add_batch(traj) for _ in range(initial_collect_steps): collect_step(train_env, random_policy) # This loop is so common in RL, that we provide standard implementations of # these. For more details see the drivers module. ``` In order to sample data from the replay buffer, we will create a `tf.data` pipeline which we can feed to the agent for training later. We can specify the `sample_batch_size` to configure the number of items sampled from the replay buffer. We can also optimize the data pipline using parallel calls and prefetching. In order to save space, we only store the current observation in each row of the replay buffer. But since the DQN Agent needs both the current and next observation to compute the loss, we always sample two adjacent rows for each item in the batch by setting `num_steps=2`. ``` # Dataset generates trajectories with shape [Bx2x...] dataset = replay_buffer.as_dataset( num_parallel_calls=3, sample_batch_size=batch_size, num_steps=2).prefetch(3) iterator = iter(dataset) ``` ## Training the agent The training loop involves both collecting data from the environment and optimizing the agent's networks. Along the way, we will occasionally evaluate the agent's policy to see how we are doing. The following will take ~5 minutes to run. ``` #@test {"skip": true} %%time # (Optional) Optimize by wrapping some of the code in a graph using TF function. tf_agent.train = common.function(tf_agent.train) # Reset the train step tf_agent.train_step_counter.assign(0) # Evaluate the agent's policy once before training. avg_return = compute_avg_return(eval_env, tf_agent.policy, num_eval_episodes) returns = [avg_return] for _ in range(num_iterations): # Collect a few steps using collect_policy and save to the replay buffer. for _ in range(collect_steps_per_iteration): collect_step(train_env, tf_agent.collect_policy) # Sample a batch of data from the buffer and update the agent's network. experience, unused_info = next(iterator) train_loss = tf_agent.train(experience) step = tf_agent.train_step_counter.numpy() if step % log_interval == 0: print('step = {0}: loss = {1}'.format(step, train_loss.loss)) if step % eval_interval == 0: avg_return = compute_avg_return(eval_env, tf_agent.policy, num_eval_episodes) print('step = {0}: Average Return = {1}'.format(step, avg_return)) returns.append(avg_return) ``` ## Visualization ### Plots We can plot return vs global steps to see the performance of our agent. In `Cartpole-v0`, the environment gives a reward of +1 for every time step the pole stays up, and since the maximum number of steps is 200, the maximum possible return is also 200. ``` #@test {"skip": true} steps = range(0, num_iterations + 1, eval_interval) plt.plot(steps, returns) plt.ylabel('Average Return') plt.xlabel('Step') plt.ylim(top=250) ``` ### Videos It is helpful to visualize the performance of an agent by rendering the environment at each step. Before we do that, let us first create a function to embed videos in this colab. ``` def embed_mp4(filename): """Embeds an mp4 file in the notebook.""" video = open(filename,'rb').read() b64 = base64.b64encode(video) tag = ''' <video width="640" height="480" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4"> Your browser does not support the video tag. </video>'''.format(b64.decode()) return IPython.display.HTML(tag) ``` The following code visualizes the agent's policy for a few episodes: ``` num_episodes = 3 video_filename = 'imageio.mp4' with imageio.get_writer(video_filename, fps=60) as video: for _ in range(num_episodes): time_step = eval_env.reset() video.append_data(eval_py_env.render()) while not time_step.is_last(): action_step = tf_agent.policy.action(time_step) time_step = eval_env.step(action_step.action) video.append_data(eval_py_env.render()) embed_mp4(video_filename) ```
github_jupyter
# Chapter 11 *Modeling and Simulation in Python* Copyright 2021 Allen Downey License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print('Downloaded ' + local) download('https://raw.githubusercontent.com/AllenDowney/' + 'ModSimPy/master/modsim.py') # import functions from modsim from modsim import * ``` [Click here to run this chapter on Colab](https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master//chapters/chap11.ipynb) In this chapter, we develop a model of an epidemic as it spreads in a susceptible population, and use it to evaluate the effectiveness of possible interventions. My presentation of the model in the next few chapters is based on an excellent article by David Smith and Lang Moore, "The SIR Model for Spread of Disease," *Journal of Online Mathematics and its Applications*, December 2001, available at <http://modsimpy.com/sir>. ## The Freshman Plague Every year at Olin College, about 90 new students come to campus from around the country and the world. Most of them arrive healthy and happy, but usually at least one brings with them some kind of infectious disease. A few weeks later, predictably, some fraction of the incoming class comes down with what we call "The Freshman Plague". In this chapter we introduce a well-known model of infectious disease, the Kermack-McKendrick model, and use it to explain the progression of the disease over the course of the semester, predict the effect of possible interventions (like immunization) and design the most effective intervention campaign. So far we have done our own modeling; that is, we've chosen physical systems, identified factors that seem important, and made decisions about how to represent them. In this chapter we start with an existing model and reverse-engineer it. Along the way, we consider the modeling decisions that went into it and identify its capabilities and limitations. ## The SIR model The Kermack-McKendrick model is an example of an **SIR model**, so-named because it represents three categories of people: - **S**: People who are "susceptible", that is, capable of contracting the disease if they come into contact with someone who is infected. - **I**: People who are "infectious", that is, capable of passing along the disease if they come into contact with someone susceptible. - **R**: People who are "recovered". In the basic version of the model, people who have recovered are considered to be immune to reinfection. That is a reasonable model for some diseases, but not for others, so it should be on the list of assumptions to reconsider later. Let's think about how the number of people in each category changes over time. Suppose we know that people with the disease are infectious for a period of 4 days, on average. If 100 people are infectious at a particular point in time, and we ignore the particular time each one became infected, we expect about 1 out of 4 to recover on any particular day. Putting that a different way, if the time between recoveries is 4 days, the recovery rate is about 0.25 recoveries per day, which we'll denote with the Greek letter gamma, $\gamma$, or the variable name `gamma`. If the total number of people in the population is $N$, and the fraction currently infectious is $i$, the total number of recoveries we expect per day is $\gamma i N$. Now let's think about the number of new infections. Suppose we know that each susceptible person comes into contact with 1 person every 3 days, on average, in a way that would cause them to become infected if the other person is infected. We'll denote this contact rate with the Greek letter beta, $\beta$. It's probably not reasonable to assume that we know $\beta$ ahead of time, but later we'll see how to estimate it based on data from previous outbreaks. If $s$ is the fraction of the population that's susceptible, $s N$ is the number of susceptible people, $\beta s N$ is the number of contacts per day, and $\beta s i N$ is the number of those contacts where the other person is infectious. In summary: - The number of recoveries we expect per day is $\gamma i N$; dividing by $N$ yields the fraction of the population that recovers in a day, which is $\gamma i$. - The number of new infections we expect per day is $\beta s i N$; dividing by $N$ yields the fraction of the population that gets infected in a day, which is $\beta s i$. This model assumes that the population is closed; that is, no one arrives or departs, so the size of the population, $N$, is constant. ## The SIR equations If we treat time as a continuous quantity, we can write differential equations that describe the rates of change for $s$, $i$, and $r$ (where $r$ is the fraction of the population that has recovered): $$\begin{aligned} \frac{ds}{dt} &= -\beta s i \\ \frac{di}{dt} &= \beta s i - \gamma i\\ \frac{dr}{dt} &= \gamma i\end{aligned}$$ To avoid cluttering the equations, I leave it implied that $s$ is a function of time, $s(t)$, and likewise for $i$ and $r$. SIR models are examples of **compartment models**, so-called because they divide the world into discrete categories, or compartments, and describe transitions from one compartment to another. Compartments are also called **stocks** and transitions between them are called **flows**. In this example, there are three stocks---susceptible, infectious, and recovered---and two flows---new infections and recoveries. Compartment models are often represented visually using stock and flow diagrams (see <http://modsimpy.com/stock>). The following figure shows the stock and flow diagram for an SIR model. ![Stock and flow diagram for an SIR model.](https://github.com/AllenDowney/ModSim/raw/main/figs/stock_flow1.png) Stocks are represented by rectangles, flows by arrows. The widget in the middle of the arrows represents a valve that controls the rate of flow; the diagram shows the parameters that control the valves. ## Implementation For a given physical system, there are many possible models, and for a given model, there are many ways to represent it. For example, we can represent an SIR model as a stock-and-flow diagram, as a set of differential equations, or as a Python program. The process of representing a model in these forms is called **implementation**. In this section, we implement the SIR model in Python. I'll represent the initial state of the system using a `State` object with state variables `S`, `I`, and `R`; they represent the fraction of the population in each compartment. We can initialize the `State` object with the *number* of people in each compartment, assuming there is one infected student in a class of 90: ``` init = State(S=89, I=1, R=0) show(init) ``` And then convert the numbers to fractions by dividing by the total: ``` init /= init.sum() show(init) ``` For now, let's assume we know the time between contacts and time between recoveries: ``` tc = 3 # time between contacts in days tr = 4 # recovery time in days ``` We can use them to compute the parameters of the model: ``` beta = 1 / tc # contact rate in per day gamma = 1 / tr # recovery rate in per day ``` I'll use a `System` object to store the parameters and initial conditions. The following function takes the system parameters and returns a new `System` object: ``` def make_system(beta, gamma): init = State(S=89, I=1, R=0) init /= init.sum() return System(init=init, t_end=7*14, beta=beta, gamma=gamma) ``` The default value for `t_end` is 14 weeks, about the length of a semester. Here's what the `System` object looks like. ``` system = make_system(beta, gamma) show(system) ``` ## The update function At any point in time, the state of the system is represented by a `State` object with three variables, `S`, `I` and `R`. So I'll define an update function that takes as parameters the current time, a `State` object, and a `System` object: ``` def update_func(t, state, system): s, i, r = state infected = system.beta * i * s recovered = system.gamma * i s -= infected i += infected - recovered r += recovered return State(S=s, I=i, R=r) ``` The first line uses a feature we have not seen before, **multiple assignment**. The value on the right side is a `State` object that contains three values. The left side is a sequence of three variable names. The assignment does just what we want: it assigns the three values from the `State` object to the three variables, in order. The variables `s`, `i` and `r`, are lowercase to distinguish them from the state variables, `S`, `I` and `R`. The update function computes `infected` and `recovered` as a fraction of the population, then updates `s`, `i` and `r`. The return value is a `State` that contains the updated values. We can call `update_func` like this: ``` state = update_func(0, init, system) show(state) ``` The result is the new `State` object. You might notice that this version of `update_func` does not use one of its parameters, `t`. I include it anyway because update functions sometimes depend on time, and it is convenient if they all take the same parameters, whether they need them or not. ## Running the simulation Now we can simulate the model over a sequence of time steps: ``` def run_simulation1(system, update_func): state = system.init for t in range(0, system.t_end): state = update_func(t, state, system) return state ``` The parameters of `run_simulation` are the `System` object and the update function. The `System` object contains the parameters, initial conditions, and values of `0` and `t_end`. We can call `run_simulation` like this: ``` final_state = run_simulation1(system, update_func) show(final_state) ``` The result indicates that after 14 weeks (98 days), about 52% of the population is still susceptible, which means they were never infected, almost 48% have recovered, which means they were infected at some point, and less than 1% are actively infected. ## Collecting the results The previous version of `run_simulation` only returns the final state, but we might want to see how the state changes over time. We'll consider two ways to do that: first, using three `TimeSeries` objects, then using a new object called a `TimeFrame`. Here's the first version: ``` def run_simulation2(system, update_func): S = TimeSeries() I = TimeSeries() R = TimeSeries() state = system.init S[0], I[0], R[0] = state for t in range(0, system.t_end): state = update_func(t, state, system) S[t+1], I[t+1], R[t+1] = state return S, I, R ``` First, we create `TimeSeries` objects to store the results. Next we initialize `state` and the first elements of `S`, `I` and `R`. Inside the loop, we use `update_func` to compute the state of the system at the next time step, then use multiple assignment to unpack the elements of `state`, assigning each to the corresponding `TimeSeries`. At the end of the function, we return the values `S`, `I`, and `R`. This is the first example we have seen where a function returns more than one value. We can run the function like this: ``` S, I, R = run_simulation2(system, update_func) ``` We'll use the following function to plot the results: ``` def plot_results(S, I, R): S.plot(style='--', label='Susceptible') I.plot(style='-', label='Infected') R.plot(style=':', label='Resistant') decorate(xlabel='Time (days)', ylabel='Fraction of population') ``` And run it like this: ``` plot_results(S, I, R) ``` It takes about three weeks (21 days) for the outbreak to get going, and about five weeks (35 days) to peak. The fraction of the population that's infected is never very high, but it adds up. In total, almost half the population gets sick. ## Now with a TimeFrame If the number of state variables is small, storing them as separate `TimeSeries` objects might not be so bad. But a better alternative is to use a `TimeFrame`, which is another object defined in the ModSim library. A `TimeFrame` is a kind of a `DataFrame`, which we used earlier to store world population estimates. Here's a more concise version of `run_simulation` using a `TimeFrame`: ``` def run_simulation(system, update_func): frame = TimeFrame(columns=system.init.index) frame.loc[0] = system.init for t in range(0, system.t_end): frame.loc[t+1] = update_func(t, frame.loc[t], system) return frame ``` The first line creates an empty `TimeFrame` with one column for each state variable. Then, before the loop starts, we store the initial conditions in the `TimeFrame` at `0`. Based on the way we've been using `TimeSeries` objects, it is tempting to write: ``` frame[0] = system.init ``` But when you use the bracket operator with a `TimeFrame` or `DataFrame`, it selects a column, not a row. To select a row, we have to use `loc`, like this: ``` frame.loc[0] = system.init ``` Since the value on the right side is a `State`, the assignment matches up the index of the `State` with the columns of the `TimeFrame`; that is, it assigns the `S` value from `system.init` to the `S` column of `frame`, and likewise with `I` and `R`. We use the same feature to write the loop more concisely, assigning the `State` we get from `update_func` directly to the next row of `frame`. Finally, we return `frame`. We can call this version of `run_simulation` like this: ``` results = run_simulation(system, update_func) ``` And plot the results like this: ``` plot_results(results.S, results.I, results.R) ``` As with a `DataFrame`, we can use the dot operator to select columns from a `TimeFrame`. ## Summary This chapter presents an SIR model of infectious disease and two ways to collect the results, using several `TimeSeries` objects or a single `TimeFrame`. In the next chapter we'll use the model to explore the effect of immunization and other interventions. But first you might want to work on these exercises. ## Exercises **Exercise** Suppose the time between contacts is 4 days and the recovery time is 5 days. After 14 weeks, how many students, total, have been infected? Hint: what is the change in `S` between the beginning and the end of the simulation? ``` # Solution goes here # Solution goes here # Solution goes here ```
github_jupyter
# Solving 10 Queens using pygenetic In this example we are going to walk through the usage of GAEngine to solve the N-Queens problem The objective would be to place queens on single board such that all are in safe position <b>Each configuration of board represents a potential candidate solution for the problem</b> ## 1. Chromosome Representation <img src="nQueens-Chromosome.png" style="width:700px;"> For the given chess board, the chromosome is encoded as the row number in which each the queen is present in each column of the chess board. It can also be encoded as the column number in which each the queen is present in each row of the chess board (as done in this code) This can be easily achieved by using the `RangeFactory` of `pygenetic`. <br/> The `RangeFactory` takes the following parameters * minValue = minimum value a gene can take = 0 <br/> * maxValue = minimum value a gene can take = 9 <br/> * duplicates = if duplicates are allowed = False <br/> * noOfGenes = number of genes in the chromosome = 10 ``` from pygenetic import ChromosomeFactory factory = ChromosomeFactory.ChromosomeRangeFactory(minValue=0,maxValue=9,noOfGenes=10,duplicates=False) ``` You can also check if the factory works as expected by calling `createChromosome` function and observing the chromosome produced by the factory ``` # Code to test if factory works as expected for i in range(5): print('Chromosome created: ', factory.createChromosome()) ``` ## 2. Fitness function Fitness for a given chromosome is the number of non-intersecting queens for that given chess board configuration. Hence the highest fitness for a N X N chess board is N. Hence, we have a maximization GA problem with the aim of achieving fitness value N. We can easily define such fitness functions in python taking a chromosome as a parameter ``` def fitness(board): fitness = 0 for i in range(len(board)): isSafe = True for j in range(len(board)): if i!=j: # Shouldn't be present on same row/diagonal if board[i] == board[j] or abs(board[i] - board[j])==abs(i-j): isSafe = False break if(isSafe==True): fitness += 1 return fitness ``` We need then create a `GAEngine` instance from the `pygenetic` package and set the following * `factory` = the range factory instance we had intially created * `population_size = 500` would be a good number for this problem * `cross_prob = 0.8` * `mut_prob = 0.2` * `fitness_type = ('equal', 10)` since our objective in this GA is to achieve the fitness value of 10 ``` from pygenetic import GAEngine ga = GAEngine.GAEngine(factory,population_size=500,fitness_type=('equal',10),mut_prob = 0.2,cross_prob = 0.8) ``` We can now add the fitness function we had defined to this `GAEngine` instance ``` ga.setFitnessHandler(fitness) ``` ## 3. Determing other attributes of the GA Many Standard Crossover, Mutation, Selection and Fitness functions are present in the `Utils` module of the `pygenetic` package. ``` from pygenetic import Utils ``` ### Crossover Traditional crossover methods such as 1-point, 2-point crossover cannot be used since it create duplicate genes in the offsprings. In the popularly used `distinct` crossover, the first half of the chromosome is kept the same while the second half is obtained by sequentially traversing the second chromosome and adding elements only if that element is not already present. <img src="nQueens-crossover.png" style="width:700px;"> This can be done using the `addCrossoverHandler` of the pygenetic module which takes as parameters * crossover_function = the crossover function to be used * weight = the weightage the crossover function needs to be given (mainly used when multiple crossovers are added) ``` ga.addCrossoverHandler(Utils.CrossoverHandlers.distinct, 4) ``` ### Mutation The use of the mutation technique of `swap` as shown in the diagram also ensures that each element in the chromosome is a unique number and that there are no duplicates. This is a suitable for mutation function for this problem <img src="nQueens-mutation.png" style="width:700px"> This can be done using the `addMutationHandler` of the pygenetic module which takes as parameters * mutation_function = the mutation function to be used * weight = the weightage the mutation function needs to be given (mainly used when multiple mutations are added) ``` ga.addMutationHandler(Utils.MutationHandlers.swap,2) ``` ## Selection The selection function `best` chooses the best (1 - cross_prob) percent of the population. Hence, this function is one of the possible selection handlers which can be used in our genetic algorithm ``` ga.setSelectionHandler(Utils.SelectionHandlers.best) ``` ## 4. Time to Evolve This can be easily done using the `evolve` function of the GAEngine instance. It takes the `noOfIterations` as a parameter. Let's evolve it for 100 generations ``` ga.evolve(100) ``` We can get the best member by using the `best_fitness` attribute of the `GAEngine`. It returns a tuple having * chromsome having best fitness * best fitness value ``` best = ga.best_fitness print(best) ``` We can decode the chromosome into a chess board accordingly ``` def print_board(chromosome): for i in chromosome: for x in range(i): print("-",end=' ') print('Q', end=' ') for x in range(len(chromosome)-i-1): print("-",end=' ') print() print('Best Board is') print_board(ga.best_fitness[0]) ``` ## 5. Plotting the Statistics - The functionality for plotting the best, worst, average fitness values across iterations is present in `plot_statistics` function of statistics.py module. The function takes a list of attributes to be plotted. - These attributes can be `best-fitness`,`worst-fitness`,`avg-fitness`, `'diversity`, `mutation_rate` - The diversity and mutation rate values over iterations can also be visualized ``` import matplotlib.pyplot as plt fig = ga.statistics.plot_statistics(['best-fitness','worst-fitness','avg-fitness']) plt.show() fig = ga.statistics.plot_statistics(['diversity']) plt.show() fig = ga.statistics.plot_statistics(['mutation_rate']) plt.show() ```
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Cargamos-librerias" data-toc-modified-id="Cargamos-librerias-1">Cargamos librerias</a></span><ul class="toc-item"><li><span><a href="#metricas-de-evaluacion-(sigmas)-+-funciones-de-utilidad" data-toc-modified-id="metricas-de-evaluacion-(sigmas)-+-funciones-de-utilidad-1.1">metricas de evaluacion (sigmas) + funciones de utilidad</a></span></li><li><span><a href="#Datos-de-entrenamiento!" data-toc-modified-id="Datos-de-entrenamiento!-1.2">Datos de entrenamiento!</a></span></li><li><span><a href="#usamos-🐼" data-toc-modified-id="usamos-🐼-1.3">usamos 🐼</a></span></li><li><span><a href="#preprocesamiento-para-X-y-Y" data-toc-modified-id="preprocesamiento-para-X-y-Y-1.4">preprocesamiento para X y Y</a></span></li></ul></li><li><span><a href="#ML-con-Scikit-learn" data-toc-modified-id="ML-con-Scikit-learn-2">ML con Scikit-learn</a></span><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Regression-Logistica" data-toc-modified-id="Regression-Logistica-2.0.1">Regression Logistica</a></span><ul class="toc-item"><li><span><a href="#Coeficientes" data-toc-modified-id="Coeficientes-2.0.1.1">Coeficientes</a></span></li></ul></li></ul></li><li><span><a href="#predecir-probabilidades" data-toc-modified-id="predecir-probabilidades-2.1">predecir probabilidades</a></span></li><li><span><a href="#SGDclassifier-(Regression-Logistica)" data-toc-modified-id="SGDclassifier-(Regression-Logistica)-2.2">SGDclassifier (Regression Logistica)</a></span><ul class="toc-item"><li><span><a href="#Actividad:-Evalua!" data-toc-modified-id="Actividad:-Evalua!-2.2.1">Actividad: Evalua!</a></span></li></ul></li><li><span><a href="#Regularizacion" data-toc-modified-id="Regularizacion-2.3">Regularizacion</a></span></li></ul></li><li><span><a href="#Actividad:" data-toc-modified-id="Actividad:-3">Actividad:</a></span><ul class="toc-item"><li><span><a href="#Metodos-de-ensembles" data-toc-modified-id="Metodos-de-ensembles-3.1">Metodos de ensembles</a></span></li><li><span><a href="#predecir-probabilidades" data-toc-modified-id="predecir-probabilidades-3.2">predecir probabilidades</a></span></li><li><span><a href="#Modelos-de-arboles:-feature-importance" data-toc-modified-id="Modelos-de-arboles:-feature-importance-3.3">Modelos de arboles: feature importance</a></span></li><li><span><a href="#Mejorando-la-regla-de-decision" data-toc-modified-id="Mejorando-la-regla-de-decision-3.4">Mejorando la regla de decision</a></span><ul class="toc-item"><li><span><a href="#en-vez-de-0.5-usaremos-un-percentil" data-toc-modified-id="en-vez-de-0.5-usaremos-un-percentil-3.4.1">en vez de 0.5 usaremos un percentil</a></span></li></ul></li><li><span><a href="#Probabilidad-de-corte" data-toc-modified-id="Probabilidad-de-corte-3.5">Probabilidad de corte</a></span></li></ul></li><li><span><a href="#Actividad:" data-toc-modified-id="Actividad:-4">Actividad:</a></span></li></ul></div> ![](extra/atlas.png) # Cargamos librerias ``` %matplotlib inline %config InlineBackend.figure_format='retina' import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy as sc import pandas as pd import sklearn import matplotlib.pyplot as plt import seaborn as sns import os from IPython.display import display import sys ``` ## metricas de evaluacion (sigmas) + funciones de utilidad ![http://i.imgur.com/Hflz2lG.jpg](http://i.imgur.com/Hflz2lG.jpg) ``` from sklearn.metrics import roc_curve, auc def AMSScore(s,b): return np.sqrt (2.*( (s + b + 10.)*np.log(1.+s/(b+10.))-s)) def eval_model(Y_true_train,Y_pred_train,w_train,Y_true_test,Y_pred_test,w_test): ratio = float(len(X_train)) /float(len(X_test)) TruePositive_train = w_train*(Y_true_train==1.0)*(1.0/ratio) TrueNegative_train = w_train*(Y_true_train==0.0)*(1.0/ratio) TruePositive_valid = w_test*(Y_true_test==1.0)*(1.0/(1-ratio)) TrueNegative_valid = w_test*(Y_true_test==0.0)*(1.0/(1-ratio)) s_train = sum ( TruePositive_train*(Y_pred_train==1.0) ) b_train = sum ( TrueNegative_train*(Y_pred_train==1.0) ) s_test = sum ( TruePositive_valid*(Y_pred_test==1.0) ) b_test = sum ( TrueNegative_valid*(Y_pred_test==1.0) ) score_train = AMSScore(s_train,b_train) score_test = AMSScore(s_test,b_test) print('--- Resultados --') print('- AUC train: {:.3f} '.format(sk.metrics.roc_auc_score(Y_train,Y_train_pred))) print('- AUC test : {:.3f} '.format(sk.metrics.roc_auc_score(Y_test,Y_test_pred))) print('- AMS train: {:.3f} sigma'.format(score_train)) print('- AMS test : {:.3f} sigma'.format(score_test)) return score_train, score_test def plot_roc(clf,Y_test,Y_test_prob): fpr, tpr, thresholds = roc_curve(Y_test, Y_test_prob) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, alpha=0.3, label=str(clf.__class__.__name__)) plt.plot(np.linspace(0,1,100),np.linspace(0,1,100), lw=2, alpha=0.3, label='Suerte') plt.legend(loc='lower right') plt.xlim([0,1]) plt.ylim([0,1]) plt.tight_layout() return ``` ## Datos de entrenamiento! Quieres saber mas? Visita [http://higgsml.lal.in2p3.fr/documentation](http://higgsml.lal.in2p3.fr/documentation) ``` !wget ``` ## usamos 🐼 ``` df=pd.read_csv('datos/training.csv') print(df.shape) df.head(1) ``` ## preprocesamiento para X y Y ``` Y = df['Label'].replace(to_replace=['s','b'],value=[1,0]).values weights = df['Weight'].values X = df.drop(['EventId','Label','Weight'],axis=1).values from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test,w_train,w_test = train_test_split(X,Y,weights,train_size=0.3) print(X_train.shape,Y_train.shape,w_train.shape) print(X_test.shape,Y_test.shape,w_test.shape) ``` # ML con Scikit-learn ![[](http://scikit-learn.org/stable/)](extra/sklearn_logo.png) ### Regression Logistica ** Modelo :** $h_{\theta}(x) = g(\theta^{T}x) = g(\sum \theta_i x_i +b)$ con $g(z)=\frac{1}{1+e^{-z}}$ ** optimizador, metrica?** ``` from sklearn.linear_model import LogisticRegression clf = LogisticRegression(verbose=1) clf.fit(X_train,Y_train) ``` #### Coeficientes $$\sum \theta_i x_i + b $$ ``` print('a = {}'.format(clf.coef_)) print('b = {}'.format(clf.intercept_)) sns.distplot(clf.coef_,kde=False) plt.show() ``` ## predecir probabilidades ``` Y_train_pred = clf.predict(X_train) Y_test_pred = clf.predict(X_test) Y_train_prob=clf.predict_proba(X_train)[:,1] Y_test_prob =clf.predict_proba(X_test)[:,1] print('AUC:') print('train: {:2.4f}'.format(sk.metrics.roc_auc_score(Y_train,Y_train_pred))) print('test: {:2.4f}'.format(sk.metrics.roc_auc_score(Y_test,Y_test_pred))) eval_model(Y_train,Y_train_pred,w_train,Y_test,Y_test_pred,w_test) x = np.linspace(-30,30,100) plt.plot(x,1.0/(1+np.exp(-x))) plt.show() from sklearn.metrics import roc_curve, auc fpr, tpr, thresholds = roc_curve(Y_test, Y_test_prob) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, alpha=0.3, label=str(clf.__class__.__name__)) plt.plot(np.linspace(0,1,100),np.linspace(0,1,100), lw=2, alpha=0.3, label='Suerte') plt.legend(loc='lower right') plt.xlim([0,1]) plt.ylim([0,1]) plt.xlabel('Falsos Positivos') plt.ylabel('Falsos Negativos') plt.tight_layout() plt.show() ``` ## SGDclassifier (Regression Logistica) ** Modelo :** $h_{\theta}(x) = g(\theta^{T}x)$ con $g(z)=\frac{1}{1+e^{-z}}$ ** Costo :** $$J(\theta)=-\frac{1}{m}\sum_{i=1}^{m}y^{i}\log(h_\theta(x^{i}))+(1-y^{i})\log(1-h_\theta(x^{i}))$$ ** Optimizador:** Descenso de gradient Ojo, la derivada del costo es: $$ \frac{\partial}{\partial\theta_{j}}J(\theta) =\sum_{i=1}^{m}(h_\theta(x^{i})-y^i)x_j^i$$ ``` from sklearn.linear_model import SGDClassifier clf = SGDClassifier(loss='log',verbose=1,max_iter=500) clf.fit(X_train,Y_train) ``` ### Actividad: Evalua! ## Regularizacion ** Costo :** $$J(\theta)=-\frac{1}{m}\sum_{i=1}^{m}y^{i}\log(h_\theta(x^{i}))+(1-y^{i})\log(1-h_\theta(x^{i}))$$ ** $L2$**: $$ + \alpha \sum \theta_i^2$$ ** $L1$**: $$ + \frac{\lambda}{1}\sum |\theta_i|$$ ``` from sklearn.linear_model import SGDClassifier clf = SGDClassifier(loss='log',alpha=0.5,l1_ratio=0.2,verbose=1,max_iter=500) clf.fit(X_train,Y_train) ``` # Actividad: * Entrena un modelo para investigar el efecto de solo suar regularizacion L2 (apaga L1) * Entrena un modelo para investigar el efecto de solo suar regularizacion L1 (apaga L2) * Checa histogramas de tus pesos (coef) ## Metodos de ensembles ``` from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(verbose=1) clf.fit(X_train,Y_train) ``` ## predecir probabilidades ``` Y_train_pred = clf.predict(X_train) Y_test_pred = clf.predict(X_test) Y_train_prob=clf.predict_proba(X_train)[:,1] Y_test_prob =clf.predict_proba(X_test)[:,1] eval_model(Y_train,Y_train_pred,w_train,Y_test,Y_test_pred,w_test) plot_roc(clf,Y_test,Y_test_prob) ``` ## Modelos de arboles: feature importance ``` importances = clf.feature_importances_ indices = np.argsort(importances)[::-1] # Print the feature ranking print("Feature ranking:") for f in range(X.shape[1]): print('{:d}. X_{:d} ({:2.4f})'.format(f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest plt.figure() plt.title("Feature importances") plt.bar(range(X.shape[1]), importances[indices], align="center") plt.xticks(range(X.shape[1]), indices) plt.xlim([-1, X.shape[1]]) plt.show() ``` ## Mejorando la regla de decision ### en vez de 0.5 usaremos un percentil ## Probabilidad de corte ``` sns.distplot(Y_train_prob) plt.show() pcut = np.percentile(Y_train_prob,80) pcut Y_train_pred = Y_train_prob > pcut Y_test_pred = Y_test_prob > pcut eval_model(Y_train,Y_train_pred,w_train,Y_test,Y_test_pred,w_test) ``` # Actividad: * Escoge algun algoritmo que no hayamos visto. * Trata de entender la idea central en 5 minutos. * Identifica los componentes (Modelo, funcion objectivo, optimizador) * Entrenar un algoritmo. * Optimizar los hiperparametros.
github_jupyter
![](http://i67.tinypic.com/2jcbwcw.png) ## Data-X: Titanic Survival Analysis Data from: https://www.kaggle.com/c/titanic/data **Authors:** Several public Kaggle Kernels, edits by Alexander Fred Ojala & Kevin Li <img src="data/Titanic_Variable.png"> # Note Install xgboost package in your pyhton enviroment: try: ``` $ conda install py-xgboost ``` ``` ''' # You can also install the package by running the line below # directly in your notebook '''; #!conda install py-xgboost --y ``` ## Import packages ``` # No warnings import warnings warnings.filterwarnings('ignore') # Filter out warnings # data analysis and wrangling import pandas as pd import numpy as np import random as rnd # visualization import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # machine learning from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC, LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB # Gaussian Naive Bayes from sklearn.linear_model import Perceptron from sklearn.linear_model import SGDClassifier #stochastic gradient descent from sklearn.tree import DecisionTreeClassifier import xgboost as xgb # Plot styling sns.set(style='white', context='notebook', palette='deep') plt.rcParams[ 'figure.figsize' ] = 9 , 5 ``` ### Define fancy plot to look at distributions ``` # Special distribution plot (will be used later) def plot_distribution( df , var , target , **kwargs ): row = kwargs.get( 'row' , None ) col = kwargs.get( 'col' , None ) facet = sns.FacetGrid( df , hue=target , aspect=4 , row = row , col = col ) facet.map( sns.kdeplot , var , shade= True ) facet.set( xlim=( 0 , df[ var ].max() ) ) facet.add_legend() plt.tight_layout() ``` ## References to material we won't cover in detail: * **Gradient Boosting:** http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/ * **Naive Bayes:** http://scikit-learn.org/stable/modules/naive_bayes.html * **Perceptron:** http://aass.oru.se/~lilien/ml/seminars/2007_02_01b-Janecek-Perceptron.pdf ## Input Data ``` train_df = pd.read_csv('data/train.csv') test_df = pd.read_csv('data/test.csv') combine = [train_df, test_df] # NOTE! When we change train_df or test_df the objects in combine # will also change # (combine is only a pointer to the objects) # combine is used to ensure whatever preprocessing is done # on training data is also done on test data ``` # Exploratory Data Anlysis (EDA) We will analyze the data to see how we can work with it and what makes sense. ``` train_df print(train_df.columns) # preview the data train_df.head(10) # General data statistics train_df.describe() # Data Frame information (null, data type etc) train_df.info() ``` ### Comment on the Data <div class='alert alert-info'> `PassengerId` is a random number and thus does not contain any valuable information. `Survived, Passenger Class, Age Siblings Spouses, Parents Children` and `Fare` are numerical values -- so we don't need to transform them, but we might want to group them (i.e. create categorical variables). `Sex, Embarked` are categorical features that we need to map to integer values. `Name, Ticket` and `Cabin` might also contain valuable information. </div> # Preprocessing Data ``` # check dimensions of the train and test datasets print("Shapes Before: (train) (test) = ", \ train_df.shape, test_df.shape) # Drop columns 'Ticket', 'Cabin', need to do it for both test # and training train_df = train_df.drop(['Ticket', 'Cabin'], axis=1) test_df = test_df.drop(['Ticket', 'Cabin'], axis=1) combine = [train_df, test_df] print("Shapes After: (train) (test) =", train_df.shape, test_df.shape) # Check if there are null values in the datasets print(train_df.isnull().sum()) print() print(test_df.isnull().sum()) ``` # Data Preprocessing ``` train_df.head(5) ``` ### Hypothesis The Title of the person is a feature that can predict survival ``` # List example titles in Name column train_df.Name[:5] # from the Name column we will extract title of each passenger # and save that in a column in the dataset called 'Title' # if you want to match Titles or names with any other expression # refer to this tutorial on regex in python: # https://www.tutorialspoint.com/python/python_reg_expressions.htm # Create new column called title for dataset in combine: dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.',\ expand=False) # Double check that our titles makes sense (by comparing to sex) pd.crosstab(train_df['Title'], train_df['Sex']) # same for test set pd.crosstab(test_df['Title'], test_df['Sex']) # We see common titles like Miss, Mrs, Mr, Master are dominant, we will # correct some Titles to standard forms and replace the rarest titles # with single name 'Rare' for dataset in combine: dataset['Title'] = dataset['Title'].\ replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr',\ 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') #Mademoiselle dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') #Madame # Now that we have more logical titles, and a few groups # we can plot the survival chance for each title train_df[['Title', 'Survived']].groupby(['Title']).mean() # We can also plot it sns.countplot(x='Survived', hue="Title", data=train_df, order=[1,0]) plt.xticks(range(2),['Made it','Deceased']); # Title dummy mapping for dataset in combine: binary_encoded = pd.get_dummies(dataset.Title) newcols = binary_encoded.columns dataset[newcols] = binary_encoded train_df.head() train_df = train_df.drop(['Name', 'Title', 'PassengerId'], axis=1) test_df = test_df.drop(['Name', 'Title'], axis=1) combine = [train_df, test_df] train_df.shape, test_df.shape ``` ## Gender column ``` # Map Sex to binary categories for dataset in combine: dataset['Sex'] = dataset['Sex'] \ .map( {'female': 1, 'male': 0} ).astype(int) train_df.head() ``` ### Handle missing values for age We will now guess values of age based on sex (male / female) and socioeconomic class (1st,2nd,3rd) of the passenger. The row indicates the sex, male = 0, female = 1 More refined estimate than only median / mean etc. ``` guess_ages = np.zeros((2,3),dtype=int) #initialize guess_ages # Fill the NA's for the Age columns # with "qualified guesses" for idx,dataset in enumerate(combine): if idx==0: print('Working on Training Data set\n') else: print('-'*35) print('Working on Test Data set\n') print('Guess values of age based on sex and pclass of the passenger...') for i in range(0, 2): for j in range(0,3): guess_df = dataset[(dataset['Sex'] == i) \ &(dataset['Pclass'] == j+1)]['Age'].dropna() # Extract the median age for this group # (less sensitive) to outliers age_guess = guess_df.median() # Convert random age float to int guess_ages[i,j] = int(age_guess) print('Guess_Age table:\n',guess_ages) print ('\nAssigning age values to NAN age values in the dataset...') for i in range(0, 2): for j in range(0, 3): dataset.loc[ (dataset.Age.isnull()) & (dataset.Sex == i) \ & (dataset.Pclass == j+1),'Age'] = guess_ages[i,j] dataset['Age'] = dataset['Age'].astype(int) print() print('Done!') train_df.head() # Split into age bands and look at survival rates train_df['AgeBand'] = pd.cut(train_df['Age'], 5) train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False)\ .mean().sort_values(by='AgeBand', ascending=True) # Plot distributions of Age of passangers who survived # or did not survive plot_distribution( train_df , var = 'Age' , target = 'Survived' ,\ row = 'Sex' ) # Change Age column to # map Age ranges (AgeBands) to integer values of categorical type for dataset in combine: dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0 dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1 dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2 dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3 dataset.loc[ dataset['Age'] > 64, 'Age']=4 train_df.head() # Note we could just run # dataset['Age'] = pd.cut(dataset['Age'], 5,labels=[0,1,2,3,4]) # remove AgeBand from before train_df = train_df.drop(['AgeBand'], axis=1) combine = [train_df, test_df] train_df.head() ``` # Create variable for Family Size How did the number of people the person traveled with impact the chance of survival? ``` # SibSp = Number of Sibling / Spouses # Parch = Parents / Children for dataset in combine: dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1 # Survival chance with FamilySize train_df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean().sort_values(by='Survived', ascending=False) # Plot it, 1 is survived sns.countplot(x='Survived', hue="FamilySize", data=train_df, order=[1,0]); # Binary variable if the person was alone or not for dataset in combine: dataset['IsAlone'] = 0 dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1 train_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean() # We will only use the binary IsAlone feature for further analysis train_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1) test_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1) combine = [train_df, test_df] train_df.head() # We can also create new features based on intuitive combinations for dataset in combine: dataset['Age*Class'] = dataset.Age * dataset.Pclass train_df.loc[:, ['Age*Class', 'Age', 'Pclass']].head(8) ``` # Port the person embarked from Let's see how that influences chance of survival ``` # To replace Nan value in 'Embarked', we will use the mode # in 'Embaraked'. This will give us the most frequent port # the passengers embarked from freq_port = train_df.Embarked.dropna().mode()[0] freq_port # Fill NaN 'Embarked' Values in the datasets for dataset in combine: dataset['Embarked'] = dataset['Embarked'].fillna(freq_port) train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False) # Let's plot it sns.countplot(x='Survived', hue="Embarked", data=train_df, order=[1,0]); # Create categorical dummy variables for Embarked values for dataset in combine: binary_encoded = pd.get_dummies(dataset.Embarked) newcols = binary_encoded.columns dataset[newcols] = binary_encoded train_df.head() # Drop Embarked for dataset in combine: dataset.drop('Embarked', axis=1, inplace=True) ``` ## Handle continuous values in the Fare column ``` # Fill the NA values in the Fares column with the median test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True) test_df.head() # q cut will find ranges equal to the quantile of the data train_df['FareBand'] = pd.qcut(train_df['Fare'], 4) train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True) for dataset in combine: dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0 dataset.loc[(dataset['Fare'] > 7.91) & \ (dataset['Fare'] <= 14.454), 'Fare'] = 1 dataset.loc[(dataset['Fare'] > 14.454) & \ (dataset['Fare'] <= 31), 'Fare'] = 2 dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3 dataset['Fare'] = dataset['Fare'].astype(int) train_df = train_df.drop(['FareBand'], axis=1) combine = [train_df, test_df] train_df.head ``` ## Finished ``` train_df.head(7) # All features are approximately on the same scale # no need for feature engineering / normalization test_df.head(7) # Check correlation between features # (uncorrelated features are generally more powerful predictors) colormap = plt.cm.viridis plt.figure(figsize=(12,12)) plt.title('Pearson Correlation of Features', y=1.05, size=15) sns.heatmap(train_df.astype(float).corr().round(2)\ ,linewidths=0.1,vmax=1.0, square=True, cmap=colormap, \ linecolor='white', annot=True); ``` # Next Up: Machine Learning! Now we will Model, Predict, and Choose algorithm for conducting the classification Try using different classifiers to model and predict. Choose the best model from: * Logistic Regression * KNN * SVM * Naive Bayes * Decision Tree * Random Forest * Perceptron * XGBoost ## Setup Train and Validation Set ``` X = train_df.drop("Survived", axis=1) # Training & Validation data Y = train_df["Survived"] # Response / Target Variable # Since we don't have labels for the test data # this won't be used. It's only for Kaggle Submissions X_submission = test_df.drop("PassengerId", axis=1).copy() print(X.shape, Y.shape) # Split training and test set so that we test on 20% of the data # Note that our algorithms will never have seen the validation # data during training. This is to evaluate how good our estimators are. np.random.seed(1337) # set random seed for reproducibility from sklearn.model_selection import train_test_split X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2) print(X_train.shape, Y_train.shape) print(X_val.shape, Y_val.shape) ``` ## Scikit-Learn general ML workflow 1. Instantiate model object 2. Fit model to training data 3. Let the model predict output for unseen data 4. Compare predicitons with actual output to form accuracy measure # Logistic Regression ``` logreg = LogisticRegression() # instantiate logreg.fit(X_train, Y_train) # fit Y_pred = logreg.predict(X_val) # predict acc_log = round(logreg.score(X_val, Y_val) * 100, 2) # evaluate acc_log # Support Vector Machines svc = SVC() svc.fit(X_train, Y_train) Y_pred = svc.predict(X_val) acc_svc = round(svc.score(X_val, Y_val) * 100, 2) acc_svc knn = KNeighborsClassifier(n_neighbors = 3) knn.fit(X_train, Y_train) Y_pred = knn.predict(X_val) acc_knn = round(knn.score(X_val, Y_val) * 100, 2) acc_knn # Perceptron perceptron = Perceptron() perceptron.fit(X_train, Y_train) Y_pred = perceptron.predict(X_val) acc_perceptron = round(perceptron.score(X_val, Y_val) * 100, 2) acc_perceptron # XGBoost gradboost = xgb.XGBClassifier(n_estimators=1000) gradboost.fit(X_train, Y_train) Y_pred = gradboost.predict(X_val) acc_perceptron = round(gradboost.score(X_val, Y_val) * 100, 2) acc_perceptron # Random Forest random_forest = RandomForestClassifier(n_estimators=1000) random_forest.fit(X_train, Y_train) Y_pred = random_forest.predict(X_val) acc_random_forest = round(random_forest.score(X_val, Y_val) * 100, 2) acc_random_forest # Look at importnace of features for random forest def plot_model_var_imp( model , X , y ): imp = pd.DataFrame( model.feature_importances_ , columns = [ 'Importance' ] , index = X.columns ) imp = imp.sort_values( [ 'Importance' ] , ascending = True ) imp[ : 10 ].plot( kind = 'barh' ) print ('Training accuracy Random Forest:',model.score( X , y )) plot_model_var_imp(random_forest, X_train, Y_train) # How to create a Kaggle submission: Y_submission = random_forest.predict(X_submission) submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": Y_submission }) submission.to_csv('titanic.csv', index=False) ``` # Legacy code (not used anymore) ```python # Map title string values to numbers so that we can make predictions title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} for dataset in combine: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) # Handle missing values train_df.head() ``` ```python # Drop the unnecessary Name column (we have the titles now) train_df = train_df.drop(['Name', 'PassengerId'], axis=1) test_df = test_df.drop(['Name'], axis=1) combine = [train_df, test_df] train_df.shape, test_df.shape ``` ```python # Create categorical dummy variables for Embarked values for dataset in combine: dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int) train_df.head() ```
github_jupyter
Now it's your turn to test your new knowledge of **missing values** handling. You'll probably find it makes a big difference. # Setup The questions will give you feedback on your work. Run the following cell to set up the feedback system. ``` # Set up code checking import os if not os.path.exists("../input/train.csv"): os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv") os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv") from learntools.core import binder binder.bind(globals()) from learntools.ml_intermediate.ex2 import * print("Setup Complete") ``` In this exercise, you will work with data from the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course). ![Ames Housing dataset image](https://i.imgur.com/lTJVG4e.png) Run the next code cell without changes to load the training and validation sets in `X_train`, `X_valid`, `y_train`, and `y_valid`. The test set is loaded in `X_test`. ``` import pandas as pd from sklearn.model_selection import train_test_split # Read the data X_full = pd.read_csv('../input/train.csv', index_col='Id') X_test_full = pd.read_csv('../input/test.csv', index_col='Id') # Remove rows with missing target, separate target from predictors X_full.dropna(axis=0, subset=['SalePrice'], inplace=True) y = X_full.SalePrice X_full.drop(['SalePrice'], axis=1, inplace=True) # To keep things simple, we'll use only numerical predictors X = X_full.select_dtypes(exclude=['object']) X_test = X_test_full.select_dtypes(exclude=['object']) # Break off validation set from training data X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=0) ``` Use the next code cell to print the first five rows of the data. ``` X_train.head() ``` You can already see a few missing values in the first several rows. In the next step, you'll obtain a more comprehensive understanding of the missing values in the dataset. # Step 1: Preliminary investigation Run the code cell below without changes. ``` # Shape of training data (num_rows, num_columns) print(X_train.shape) # Number of missing values in each column of training data missing_val_count_by_column = (X_train.isnull().sum()) print(missing_val_count_by_column[missing_val_count_by_column > 0]) ``` ### Part A Use the above output to answer the questions below. ``` # Fill in the line below: How many rows are in the training data? num_rows = ____ # Fill in the line below: How many columns in the training data # have missing values? num_cols_with_missing = ____ # Fill in the line below: How many missing entries are contained in # all of the training data? tot_missing = ____ # Check your answers step_1.a.check() #%%RM_IF(PROD)%% num_rows = 1168 num_cols_with_missing = 3 tot_missing = 212 + 6 + 58 step_1.a.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_1.a.hint() #_COMMENT_IF(PROD)_ step_1.a.solution() ``` ### Part B Considering your answers above, what do you think is likely the best approach to dealing with the missing values? ``` # Check your answer (Run this code cell to receive credit!) step_1.b.check() #_COMMENT_IF(PROD)_ step_1.b.hint() ``` To compare different approaches to dealing with missing values, you'll use the same `score_dataset()` function from the tutorial. This function reports the [mean absolute error](https://en.wikipedia.org/wiki/Mean_absolute_error) (MAE) from a random forest model. ``` from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error # Function for comparing different approaches def score_dataset(X_train, X_valid, y_train, y_valid): model = RandomForestRegressor(n_estimators=100, random_state=0) model.fit(X_train, y_train) preds = model.predict(X_valid) return mean_absolute_error(y_valid, preds) ``` # Step 2: Drop columns with missing values In this step, you'll preprocess the data in `X_train` and `X_valid` to remove columns with missing values. Set the preprocessed DataFrames to `reduced_X_train` and `reduced_X_valid`, respectively. ``` # Fill in the line below: get names of columns with missing values ____ # Your code here # Fill in the lines below: drop columns in training and validation data reduced_X_train = ____ reduced_X_valid = ____ # Check your answers step_2.check() #%%RM_IF(PROD)%% # Get names of columns with missing values cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()] # Drop columns in training and validation data reduced_X_train = X_train.drop(cols_with_missing, axis=1) reduced_X_valid = X_valid.drop(cols_with_missing, axis=1) step_2.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_2.hint() #_COMMENT_IF(PROD)_ step_2.solution() ``` Run the next code cell without changes to obtain the MAE for this approach. ``` print("MAE (Drop columns with missing values):") print(score_dataset(reduced_X_train, reduced_X_valid, y_train, y_valid)) ``` # Step 3: Imputation ### Part A Use the next code cell to impute missing values with the mean value along each column. Set the preprocessed DataFrames to `imputed_X_train` and `imputed_X_valid`. Make sure that the column names match those in `X_train` and `X_valid`. ``` from sklearn.impute import SimpleImputer # Fill in the lines below: imputation ____ # Your code here imputed_X_train = ____ imputed_X_valid = ____ # Fill in the lines below: imputation removed column names; put them back imputed_X_train.columns = ____ imputed_X_valid.columns = ____ # Check your answers step_3.a.check() #%%RM_IF(PROD)%% # Imputation my_imputer = SimpleImputer() imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train)) imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid)) step_3.a.assert_check_failed() #%%RM_IF(PROD)%% # Imputation my_imputer = SimpleImputer() imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train)) imputed_X_valid = pd.DataFrame(my_imputer.fit_transform(X_valid)) # Imputation removed column names; put them back imputed_X_train.columns = X_train.columns imputed_X_valid.columns = X_valid.columns step_3.a.assert_check_failed() #%%RM_IF(PROD)%% # Imputation my_imputer = SimpleImputer() imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train)) imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid)) # Imputation removed column names; put them back imputed_X_train.columns = X_train.columns imputed_X_valid.columns = X_valid.columns step_3.a.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_3.a.hint() #_COMMENT_IF(PROD)_ step_3.a.solution() ``` Run the next code cell without changes to obtain the MAE for this approach. ``` print("MAE (Imputation):") print(score_dataset(imputed_X_train, imputed_X_valid, y_train, y_valid)) ``` ### Part B Compare the MAE from each approach. Does anything surprise you about the results? Why do you think one approach performed better than the other? ``` # Check your answer (Run this code cell to receive credit!) step_3.b.check() #_COMMENT_IF(PROD)_ step_3.b.hint() ``` # Step 4: Generate test predictions In this final step, you'll use any approach of your choosing to deal with missing values. Once you've preprocessed the training and validation features, you'll train and evaluate a random forest model. Then, you'll preprocess the test data before generating predictions that can be submitted to the competition! ### Part A Use the next code cell to preprocess the training and validation data. Set the preprocessed DataFrames to `final_X_train` and `final_X_valid`. **You can use any approach of your choosing here!** in order for this step to be marked as correct, you need only ensure: - the preprocessed DataFrames have the same number of columns, - the preprocessed DataFrames have no missing values, - `final_X_train` and `y_train` have the same number of rows, and - `final_X_valid` and `y_valid` have the same number of rows. ``` # Preprocessed training and validation features final_X_train = ____ final_X_valid = ____ # Check your answers step_4.a.check() #%%RM_IF(PROD)%% # Imputation final_imputer = SimpleImputer(strategy='median') final_X_train = pd.DataFrame(final_imputer.fit_transform(X_train)) final_X_valid = pd.DataFrame(final_imputer.transform(X_valid)) # Imputation removed column names; put them back final_X_train.columns = X_train.columns final_X_valid.columns = X_valid.columns step_4.a.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_4.a.hint() #_COMMENT_IF(PROD)_ step_4.a.solution() ``` Run the next code cell to train and evaluate a random forest model. (*Note that we don't use the `score_dataset()` function above, because we will soon use the trained model to generate test predictions!*) ``` # Define and fit model model = RandomForestRegressor(n_estimators=100, random_state=0) model.fit(final_X_train, y_train) # Get validation predictions and MAE preds_valid = model.predict(final_X_valid) print("MAE (Your approach):") print(mean_absolute_error(y_valid, preds_valid)) ``` ### Part B Use the next code cell to preprocess your test data. Make sure that you use a method that agrees with how you preprocessed the training and validation data, and set the preprocessed test features to `final_X_test`. Then, use the preprocessed test features and the trained model to generate test predictions in `preds_test`. In order for this step to be marked correct, you need only ensure: - the preprocessed test DataFrame has no missing values, and - `final_X_test` has the same number of rows as `X_test`. ``` # Fill in the line below: preprocess test data final_X_test = ____ # Fill in the line below: get test predictions preds_test = ____ # Check your answers step_4.b.check() #%%RM_IF(PROD)%% # Preprocess test data final_X_test = pd.DataFrame(final_imputer.transform(X_test)) # Get test predictions preds_test = model.predict(final_X_test) step_4.b.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_4.b.hint() #_COMMENT_IF(PROD)_ step_4.b.solution() ``` Run the next code cell without changes to save your results to a CSV file that can be submitted directly to the competition. ``` # Save test predictions to file output = pd.DataFrame({'Id': X_test.index, 'SalePrice': preds_test}) output.to_csv('submission.csv', index=False) ``` # Submit your results Once you have successfully completed Step 4, you're ready to submit your results to the leaderboard! (_You also learned how to do this in the previous exercise. If you need a reminder of how to do this, please use the instructions below._) First, you'll need to join the competition if you haven't already. So open a new window by clicking on [this link](https://www.kaggle.com/c/home-data-for-ml-course). Then click on the **Join Competition** button. ![join competition image](https://i.imgur.com/wLmFtH3.png) Next, follow the instructions below: #$SUBMIT_TO_COMP$ # Keep going Move on to learn what **[categorical variables](#$NEXT_NOTEBOOK_URL$)** are, along with how to incorporate them into your machine learning models. Categorical variables are very common in real-world data, but you'll get an error if you try to plug them into your models without processing them first!
github_jupyter
``` import numpy as np import cv2 import matplotlib.pyplot as plt from tensorflow.keras import models import tensorflow.keras.backend as K import tensorflow as tf from sklearn.metrics import f1_score import requests import xmltodict import json plateCascade = cv2.CascadeClassifier('indian_license_plate.xml') #detect the plate and return car + plate image def plate_detect(img): plateImg = img.copy() roi = img.copy() plate_part = np.array([]) plateRect = plateCascade.detectMultiScale(plateImg,scaleFactor = 1.2, minNeighbors = 7) for (x,y,w,h) in plateRect: roi_ = roi[y:y+h, x:x+w, :] plate_part = roi[y:y+h, x:x+w, :] cv2.rectangle(plateImg,(x+2,y),(x+w-3, y+h-5),(0,255,0),3) #print(type(roi)) #print(roi.shape) return plateImg, plate_part #normal function to display def display_img(img): img_ = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) plt.imshow(img_) plt.show() def find_contours(dimensions, img) : #finding all contours in the image using #retrieval mode: RETR_TREE #contour approximation method: CHAIN_APPROX_SIMPLE cntrs, _ = cv2.findContours(img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #Approx dimensions of the contours lower_width = dimensions[0] upper_width = dimensions[1] lower_height = dimensions[2] upper_height = dimensions[3] #Check largest 15 contours for license plate character respectively cntrs = sorted(cntrs, key=cv2.contourArea, reverse=True)[:15] ci = cv2.imread('contour.jpg') x_cntr_list = [] target_contours = [] img_res = [] for cntr in cntrs : #detecting contour in binary image and returns the coordinates of rectangle enclosing it intX, intY, intWidth, intHeight = cv2.boundingRect(cntr) #checking the dimensions of the contour to filter out the characters by contour's size if intWidth > lower_width and intWidth < upper_width and intHeight > lower_height and intHeight < upper_height : x_cntr_list.append(intX) char_copy = np.zeros((44,24)) #extracting each character using the enclosing rectangle's coordinates. char = img[intY:intY+intHeight, intX:intX+intWidth] char = cv2.resize(char, (20, 40)) cv2.rectangle(ci, (intX,intY), (intWidth+intX, intY+intHeight), (50,21,200), 2) #plt.imshow(ci, cmap='gray') char = cv2.subtract(255, char) char_copy[2:42, 2:22] = char char_copy[0:2, :] = 0 char_copy[:, 0:2] = 0 char_copy[42:44, :] = 0 char_copy[:, 22:24] = 0 img_res.append(char_copy) # List that stores the character's binary image (unsorted) #return characters on ascending order with respect to the x-coordinate #plt.show() #arbitrary function that stores sorted list of character indeces indices = sorted(range(len(x_cntr_list)), key=lambda k: x_cntr_list[k]) img_res_copy = [] for idx in indices: img_res_copy.append(img_res[idx])# stores character images according to their index img_res = np.array(img_res_copy) return img_res def segment_characters(image) : #pre-processing cropped image of plate #threshold: convert to pure b&w with sharpe edges #erod: increasing the backgroung black #dilate: increasing the char white img_lp = cv2.resize(image, (333, 75)) img_gray_lp = cv2.cvtColor(img_lp, cv2.COLOR_BGR2GRAY) _, img_binary_lp = cv2.threshold(img_gray_lp, 200, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) img_binary_lp = cv2.erode(img_binary_lp, (3,3)) img_binary_lp = cv2.dilate(img_binary_lp, (3,3)) LP_WIDTH = img_binary_lp.shape[0] LP_HEIGHT = img_binary_lp.shape[1] img_binary_lp[0:3,:] = 255 img_binary_lp[:,0:3] = 255 img_binary_lp[72:75,:] = 255 img_binary_lp[:,330:333] = 255 #estimations of character contours sizes of cropped license plates dimensions = [LP_WIDTH/6, LP_WIDTH/2, LP_HEIGHT/10, 2*LP_HEIGHT/3] #plt.imshow(img_binary_lp, cmap='gray') #plt.show() cv2.imwrite('contour.jpg',img_binary_lp) #getting contours char_list = find_contours(dimensions, img_binary_lp) return char_list #It is the harmonic mean of precision and recall #Output range is [0, 1] #Works for both multi-class and multi-label classification def f1score(y, y_pred): return f1_score(y, tf.math.argmax(y_pred, axis=1), average='micro') def custom_f1score(y, y_pred): return tf.py_function(f1score, (y, y_pred), tf.double) model = models.load_model('license_plate_character.pkl', custom_objects= {'custom_f1score': custom_f1score}) def fix_dimension(img): new_img = np.zeros((28,28,3)) for i in range(3): new_img[:,:,i] = img return new_img def show_results(pl_char): dic = {} characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' for i,c in enumerate(characters): dic[i] = c output = [] for i,ch in enumerate(pl_char): img_ = cv2.resize(ch, (28,28), interpolation=cv2.INTER_AREA) img = fix_dimension(img_) img = img.reshape(1,28,28,3) y_ = model.predict_classes(img)[0] character = dic[y_] # output.append(character) plate_number = ''.join(output) return plate_number # final_plate = show_results(char) # print(final_plate) def get_vehicle_info(plate_number): r = requests.get("http://www.regcheck.org.uk/api/reg.asmx/CheckIndia?RegistrationNumber={0}&username=tom123".format(str(plate_number))) data = xmltodict.parse(r.content) jdata = json.dumps(data) df = json.loads(jdata) df1 = json.loads(df['Vehicle']['vehicleJson']) return df1 import re def plate_info(numberPlate): pattern = '^[A-Z]{2}[0-9]{1,2}([A-Z])?([A-Z]*)?[0-9]{4}$' if len(numberPlate) > 10: numberPlate = numberPlate[-10:] return get_vehicle_info(numberPlate) # else: # return get_vehicle_info(numberPlate) elif re.match(pattern,numberPlate) != None: return get_vehicle_info(numberPlate) else: return None cam = cv2.VideoCapture('videoplay.mp4') #license_video.mp4 have to be yours, I haven't uploaded for privacy concern if cam.isOpened() == False: print("Video not imported") plate_list = [] info_list = [] while(cam.isOpened()): ret, frame = cam.read() if ret == True: car_plate, plate_img = plate_detect(frame) cv2.imshow("License Video",car_plate) if len(plate_img) > 0: plate_char = segment_characters(plate_img) #print(plate_char) number_plate = show_results(plate_char) if number_plate not in plate_list: final_result = plate_info(number_plate) if final_result != None: plate_list.append(number_plate) info_list.append(final_result) #print(final_result) if cv2.waitKey(1) == 27: break else: break print(info_list[0]) cam.release() cv2.destroyAllWindows() #For privacy reasons, the shown result is also not of the video used ```
github_jupyter
Diodes === The incident flux and the current that is generated by a photodiode subjected to it are related by $$ \begin{equation} \begin{split} I(A)=&\sum_{i,j}P_{i,j}(W)R_{j}(A/W)+D(A)\\ P_{i,j}(W)=&I_{i,j}(Hz)E_{j}(\text{keV})\\ R_{j}(A/W)=&\frac{e(C)}{E_{h}(\text{keV})}[1-e^{-\mu(E_{j})\rho d}] \end{split} \end{equation} $$ where P the incident power, R the spectral responsivity, D the dark current, $E_i$ the energy of the incident photon, $E_j$ the energy of the detected photon, $E_{h}$ the energy to create an electron-hole pair, $I_{i,j}$ the detected flux of line $j$ due to line $i$ and diode density $\rho$, mass attenuation coefficient $\mu$ and thickness $d$. The relationship between the detected flux and the flux at the sample position is given by $$ \begin{equation} I_{i,j}(Hz)=I_{0}(Hz) w_i Y_{i,j} = I_{s}(Hz)\frac{w_i Y_{i,j}}{\sum_k w_k T_{s}(E_{k})} \end{equation} $$ with the following factors * $I_0$: total flux before detection * $I_s$: the total flux seen by the sample * $T_s$: the "transmission" between source and sample (product of several transmission factors and optics efficiency) * $w_k$: the fraction of primary photons with energy $E_{k}$ * $Y_{i,j}$: the "rate" of detected line $j$ due to source line $i$ (not including detector attenuation) The line fractions at the sample position are $$ \begin{equation} \begin{split} I_{i,s}=& I_0 w_i T_{s}(E_{i})\\ w_{i,s} =& \frac{I_{i,s}}{\sum_k I_{k,s}} = \frac{w_i T_{s}(E_{i})}{\sum_k w_k T_{s}(E_{k})} \end{split} \end{equation} $$ The relationship between the flux reaching the sample and the current measured by a pn-diode can be summarized as $$ \begin{equation} \begin{split} I(A)=&I_{s}(Hz)C_s(C)+D(A)\\ C_s(C) =& \frac{\sum_{i,j} w_i Y_{i,j}C_j}{\sum_k w_k T_{s}(E_{k})}\\ C_j(C) =& E_{j}(\text{keV})\frac{e(C)}{E_{h}(\text{keV})}[1-e^{-\mu(E_{j})\rho d}]\\ \end{split} \end{equation} $$ where $C_s$ the charge generated per photon reaching the sample and $C_j$ the charge generated per photon reaching the diode. A simplified relationship with a lookup table can be used $$ \begin{equation} C_s(C) = \sum_i w_i \mathrm{LUT}(E_i) \end{equation} $$ Finally in order to allow a fast read-out, current is converted to frequency by an oscillator $$ \begin{equation} I(\text{Hz})=\frac{F_{\text{max}}(Hz)}{V_{\text{max}}(V)} \frac{V_{\text{max}}(V)}{I_{\text{max}}(A)}I(A)+F_{0}(Hz) \end{equation} $$ where $F_{\text{max}}$ the maximal frequency that can be detected, $F_{0}$ a fixed offset, $V_{\text{max}}$ the maximal output voltage of the ammeter and input voltage of the oscillator, $\frac{V_{\text{max}}(V)}{I_{\text{max}}(A)}$ the "gain" of the ammeter. Sometimes $I_{\text{max}}(A)$ is referred to as the diode "gain". Absolute diode -------------- An absolute diode has a spectral responsivity $R(A/W)$ which behaves as theoretically expected ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline from spectrocrunch.detectors import diode det = diode.factory("sxm_ptb") print(det) det.model = False energy = det.menergy R = det.spectral_responsivity(energy) plt.plot(energy,R,marker='o',linestyle="",label='measured') det.model = True energy = np.linspace(1,10,100) R = det.spectral_responsivity(energy) plt.plot(energy,R,label='model') plt.legend() plt.xlabel('Energy (keV)') plt.ylabel('Spectral responsivity (A/W)') plt.show() ``` Calibrated diode ---------------- The spectral responsivity $R(A/W)$ of a calibrated diode is determined by the difference in response with an absolute diode ``` det = diode.factory("sxm_idet",npop=4) print(det) det.model = False energy = det.menergy R = det.spectral_responsivity(energy) plt.plot(energy,R,marker='o',linestyle="",label='measured') det.model = True energy = np.linspace(1,12,100) R = det.spectral_responsivity(energy) plt.plot(energy,R,label='model') det.model = False R = det.spectral_responsivity(energy) plt.plot(energy,R,label='used') plt.legend(loc='best') plt.xlabel('Energy (keV)') plt.ylabel('Spectral responsivity (A/W)') plt.show() ``` Direct detection ------------------ When $Y_{i,j}$ only contains transmission factors (i.e. not fluorescence/scattering from a secondary target) the diode measures $I_s$ directly. The relationship between flux $I_s(Hz)$ and diode response $I(Hz)$ is determined by the spectral responsivity which should be known (absolute diode) or calibrated (with respect to an absolute diode): ``` from spectrocrunch.optics import xray as xrayoptics atmpath = xrayoptics.Filter(material="vacuum", thickness=1) det = diode.factory("sxm_idet",optics=[atmpath]) print(det) Is = 3e9 energy = np.linspace(2,10,100) for gain in [1e7]: for model in [False,True]: det.gain = gain det.model = model I = det.fluxtocps(energy[:, np.newaxis], Is).to("Hz").magnitude plt.plot(energy,I,label="{:.0e} V/A{}".\ format(gain," (model)" if model else "")) plt.gca().axhline(y=det.oscillator.Fmax.to("Hz").magnitude,label="Fmax",\ color='k',linestyle='--') plt.title("Flux = {:.0e} Hz".format(Is)) plt.legend(loc='best') plt.xlabel('Energy (keV)') plt.ylabel('Response (Hz)') plt.show() ``` Indirect detection ------------------ The conversion factors $Y_{i,j}$ can be calculated from the cross-sections of the secondary target. ### Without optics When the indirect diode measures the flux downstream from the optics (or there are no optics at all), the relationship between flux and measured count-rate is known (because $T_s$ is known): ``` atmpath = xrayoptics.Filter(material="vacuum", thickness=1) iodet = diode.factory("sxm_iodet1",optics=[atmpath]) iodet.gain = 1e9 print(iodet.geometry) Is = 5e9 energy = np.linspace(1,10,50) I = iodet.fluxtocps(energy[:, np.newaxis], Is).to("Hz").magnitude plt.plot(energy,I) plt.gca().axhline(y=iodet.oscillator.Fmax.to("Hz").magnitude,label="Fmax",\ color='k',linestyle='--') plt.title("Flux = {:.0e} Hz".format(Is)) plt.xlabel('Energy (keV)') plt.ylabel('Response (Hz)') plt.show() ``` ### With optics In case the indirect diode is upstream from the optics, transmission $T_s$ needs to be calibrated with a direct diode. This is done by measuring a changing flux at fixed energy, e.g. by scanning a series of attenuators. The flux is calculated from the direct diode and used to calibrate the response of the indirect diode: ``` iodet = diode.factory("sxm_iodet1",optics=[atmpath, "KB"]) iodet.gain = 1e8 idet = diode.factory("sxm_idet") idet.gain = 1e6 energy = 7 idetresp = np.linspace(3e4,5e4,100) fluxmeas = idet.cpstoflux(energy,np.random.poisson(idetresp)) iodetresp = np.random.poisson(np.linspace(2e5,3e5,100)) fitinfo = iodet.calibrate(iodetresp,fluxmeas,energy,caliboption="optics") print(iodet.geometry) plt.plot(fluxmeas,iodetresp,marker='o',linestyle="") plt.plot(fluxmeas,iodet.fluxtocps(energy,fluxmeas)) label = "\n".join(["{} = {}".format(k,v) for k,v in fitinfo.items()]) plt.annotate(label,xy=(0.5,0.1),xytext=(0.5,0.1),\ xycoords="axes fraction",textcoords="axes fraction") plt.title("Gain = {:~.0e}".format(iodet.gain)) plt.xlabel('Flux (Hz)') plt.ylabel('Response (Hz)') plt.show() ``` Note that the slope is $C_s(C)$ (the charge generated per photon reaching the sample, expressed here in units of elementary charge) and the intercept $D(A)$ (the dark current of the diode). ### Manual calibration Calibration can also be done manually for a single flux-reponse pair. The response is expected to be $I(Hz)$ but it can also be $I(A)$. If you want a linear energy interpolation, calibration can also be simplified in which case it simply stores a lookup table for $C_s(C)$. ``` #Specify quantities manually with units: #from spectrocrunch.patch.pint import ureg #current = ureg.Quantity(1e-8,"A") for simple in [True, False]: iodet = diode.factory("sxm_iodet1",optics=[atmpath, "KB"],simplecalibration=simple) iodet.gain = 1e8 # Calibrate with Hz-Hz pair cps = 100000 flux = 1e9 energy = 6 iodet.calibrate(cps,flux,energy,caliboption="optics") current = iodet.fluxtocurrent(energy,flux) # Calibrate with A-Hz pair energy = 10 current *= 0.5 iodet.calibrate(current,flux,energy,caliboption="optics") label = "C$_s$ table" if simple else "Calibrated T$_s$" print(label) print(iodet) print("") energy = np.linspace(6,10,10) response = [iodet.fluxtocps(en,flux).magnitude for en in energy] plt.plot(energy,response,label=label) plt.legend() plt.title("Gain = {:~.0e}, Flux = {:.0e}".format(iodet.Rout,flux)) plt.xlabel('Energy (keV)') plt.ylabel('Response (Hz)') plt.show() ```
github_jupyter
# Accessing C Struct Data This notebook illustrates the use of `@cfunc` to connect to data defined in C. ## Via CFFI Numba can map simple C structure types (i.e. with scalar members only) into NumPy structured `dtype`s. Let's start with the following C declarations: ``` from cffi import FFI src = """ /* Define the C struct */ typedef struct my_struct { int i1; float f2; double d3; float af4[7]; } my_struct; /* Define a callback function */ typedef double (*my_func)(my_struct*, size_t); """ ffi = FFI() ffi.cdef(src) ``` We can create `my_struct` data by doing: ``` # Make a array of 3 my_struct mydata = ffi.new('my_struct[3]') ptr = ffi.cast('my_struct*', mydata) for i in range(3): ptr[i].i1 = 123 + i ptr[i].f2 = 231 + i ptr[i].d3 = 321 + i for j in range(7): ptr[i].af4[j] = i * 10 + j ``` Using `numba.core.typing.cffi_utils.map_type` we can convert the `cffi` type into a Numba `Record` type. ``` from numba.core.typing import cffi_utils cffi_utils.map_type(ffi.typeof('my_struct'), use_record_dtype=True) ``` The function type can be mapped in a signature: ``` sig = cffi_utils.map_type(ffi.typeof('my_func'), use_record_dtype=True) sig ``` and `@cfunc` can take that signature directly: ``` from numba import cfunc, carray @cfunc(sig) def foo(ptr, n): base = carray(ptr, n) # view pointer as an array of my_struct tmp = 0 for i in range(n): tmp += base[i].i1 * base[i].f2 / base[i].d3 + base[i].af4.sum() return tmp ``` Testing the cfunc via the `.ctypes` callable: ``` addr = int(ffi.cast('size_t', ptr)) print("address of data:", hex(addr)) result = foo.ctypes(addr, 3) result ``` ## Manually creating a Numba `Record` type Sometimes it is useful to create a `numba.types.Record` type directly. The easiest way is to use the `Record.make_c_struct()` method. Using this method, the field offsets are calculated from the natural size and alignment of prior fields. In the example below, we will manually create the *my_struct* structure from above. ``` from numba import types my_struct = types.Record.make_c_struct([ # Provides a sequence of 2-tuples i.e. (name:str, type:Type) ('i1', types.int32), ('f2', types.float32), ('d3', types.float64), ('af4', types.NestedArray(dtype=types.float32, shape=(7,))) ]) my_struct ``` Here's another example to demonstrate the offset calculation: ``` padded = types.Record.make_c_struct([ ('i1', types.int32), ('pad0', types.int8), # padding bytes to move the offsets ('f2', types.float32), ('pad1', types.int8), # padding bytes to move the offsets ('d3', types.float64), ]) padded ``` Notice how the byte at `pad0` and `pad1` moves the offset of `f2` and `d3`. A function signature can also be created manually: ``` new_sig = types.float64(types.CPointer(my_struct), types.uintp) print('signature:', new_sig) # Our new signature matches the previous auto-generated one. print('signature matches:', new_sig == sig) ```
github_jupyter
# Final Project ## Daniel Blessing ## Can we use historical data from professional league of legends games to try and predict the results of future contests? ## Load Data ``` from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # ensemble models we're trying out from sklearn.model_selection import train_test_split # train test split for CV from sklearn.metrics import accuracy_score, f1_score # two evalutaion metrics for binary classification from sklearn.pipeline import Pipeline # robust pipeline from sklearn.impute import * from sklearn.preprocessing import * from sklearn.compose import * # preprocessing importance from sklearn.base import BaseEstimator #for randomized CV from sklearn.model_selection import RandomizedSearchCV # data pocessing import numpy as np import pandas as pd # load data from local else download it from github filename = 'Dev.csv' remote_location = 'https://raw.githubusercontent.com/Drblessing/predcting_LoL/master/Lol.csv' try: # Local version df = pd.read_csv(filename,index_col = 0) except FileNotFoundError or ParserError: # Grab the remote file and save it df = pd.read_csv(remote_location,index_col = 0) df.to_csv(filename) # create X,y datasets and train_test split them y = df['bResult'] df = df.drop(columns = ['bResult']) X = df X_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.8, shuffle=True,random_state = 42) # Legacy Feature Engineering '''pregame_data = Lol[['bResult','blueTopChamp','blueJungleChamp','blueMiddleChamp','blueADCChamp','blueSupportChamp', 'blueBans','redTopChamp','redJungleChamp','redMiddleChamp','redADCChamp','redSupportChamp','redBans']] # process list of bans into individual columns pregame_data_b = pregame_data.assign(names=pregame_data.blueBans.str.split(",")) pregame_data_r = pregame_data.assign(names=pregame_data.redBans.str.split(",")) blue_bans = pregame_data_b.names.apply(pd.Series) red_bans = pregame_data_r.names.apply(pd.Series) blue_names = {0: "b1", 1: "b2",2:"b3",3:"b4",4:"b5"} red_names = {0:"r1",1:"r2",2:"r3",3:"r4",4:"r5"} blue_bans = blue_bans.rename(columns=blue_names) red_bans = red_bans.rename(columns=red_names) pregame_data = pd.concat([pregame_data, blue_bans,red_bans], axis=1) # drop legacy columns pregame_data = pregame_data.drop(columns = ['blueBans','redBans']) # define y and drop it y = pregame_data['bResult'] pregame_data = pregame_data.drop(columns = ['bResult']) # fix blue bans strings pregame_data.b1 = pregame_data.b1.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.b2 = pregame_data.b2.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.b3 = pregame_data.b3.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.b4 = pregame_data.b4.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.b5 = pregame_data.b5.str.replace('[','').str.replace(']','').str.replace("'",'') # fix red bans strings pregame_data.r1 = pregame_data.r1.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.r2 = pregame_data.r2.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.r3 = pregame_data.r3.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.r4 = pregame_data.r4.str.replace('[','').str.replace(']','').str.replace("'",'') pregame_data.r5 = pregame_data.r5.str.replace('[','').str.replace(']','').str.replace("'",'')'''; ``` ## Visuatlizations ``` # visualizations import matplotlib.pyplot as plt from collections import Counter x = ['Blue win','Red win'] heights = [0,0] heights[0] = sum(y) heights[1] = len(y) - sum(y) plt.bar(x,heights); plt.ylabel('Number of Games won'); plt.xlabel('Team'); plt.title('Number of wins by team color in competitive LoL 2015-2017'); # check general accuracy of naive model bw = sum(y)/len(y) print(f'Percentage of games won by blue team: {bw*100:.2f} %') # load champs champs = Counter(X['blueADCChamp']) l = champs.keys() v = champs.values() # get rid of one off champs l = [l_ for l_ in l if champs[l_] > 1] v = [v_ for v_ in v if v_ > 1] plt.pie(v,labels=l); plt.title('Distribution of ADC champs for competitive Lol 2015-2017') ``` ## Model Building ``` # define categorical variables, all of our data categorical_columns = (X.dtypes == object) # impute missing values and hot encode categories cat_pipe = Pipeline([('imputer', SimpleImputer(strategy = 'constant', fill_value='Unknown', add_indicator=True)), ('ohe', OneHotEncoder(handle_unknown='ignore'))]) # process categorical variables preprocessing = ColumnTransformer([('categorical', cat_pipe, categorical_columns)], remainder='passthrough') # Helper class for RandomizedSearchCV class DummyEstimator(BaseEstimator): "Pass through class, methods are present but do nothing." def fit(self): pass def score(self): pass # create pipeline pipe = Pipeline(steps = [('preprocessing', preprocessing), ('clf', DummyEstimator())]) search_space = [ {'clf': [ExtraTreesClassifier(n_jobs=-1,random_state=42)], 'clf__criterion': ['gini', 'entropy'], 'clf__min_samples_leaf': np.linspace(1, 30, 5, dtype=int), 'clf__bootstrap': [True, False], 'clf__class_weight': [None, 'balanced', 'balanced_subsample'], 'clf__n_estimators': np.linspace(50, 500, 8, dtype=int)}, {'clf': [RandomForestClassifier(n_jobs=-1,random_state=42)], 'clf__criterion': ['gini', 'entropy'], 'clf__min_samples_leaf': np.linspace(1, 10, 4, dtype=int), 'clf__bootstrap': [True, False], 'clf__class_weight': [None, 'balanced', 'balanced_subsample'], 'clf__n_estimators': np.linspace(50, 300, 5, dtype=int)}] gs = RandomizedSearchCV(pipe, search_space, scoring='accuracy', # accuracy for game prediction n_iter=30, cv=5, n_jobs=-1) gs.fit(X, y); gs.best_score_, gs.best_params_ # Results: ''' (0.5510498687664042, {'clf__n_estimators': 178, 'clf__min_samples_leaf': 30, 'clf__criterion': 'gini', 'clf__class_weight': None, 'clf__bootstrap': True, 'clf': ExtraTreesClassifier(bootstrap=True, min_samples_leaf=30, n_estimators=178, n_jobs=-1, random_state=42)})''' ``` ## Evaluation Metric ``` pipe = Pipeline([('preprocessing', preprocessing), ('clf', ExtraTreesClassifier( bootstrap = True, min_samples_leaf = 15, n_estimators = 114, n_jobs = -1, criterion = 'gini', class_weight = None, random_state=42))]) pipe.fit(X_train,y_train); y_pred = pipe.predict(X_val) accuracy = accuracy_score(y_val,y_pred) f1 = f1_score(y_val,y_pred) print(f"accuracy: {accuracy:,.6f}") print(f"f1: {f1:,.6f}") ``` ## Results ``` print(f'Model accuracy: {accuracy*100:.2f} %') print(f'Naive accuracy: {bw*100:.2f} %') print(f'Prediction improvement from model: {abs(bw-accuracy)*100:.2f} %') ```
github_jupyter
``` %load_ext autoreload %pylab inline %autoreload 2 import seaborn as sns import pandas as pd import numpy as np import sys sys.path.append('..') import tensorflow as tf from tuning_manifold.fnp_model import Predictor from tuning_manifold.util import negloglik, pearson tfk = tf.keras # construct a model with architecture matching the saved file neurons = 16 stimuli = 2048 # make this longer because we draw additional samples to measure prediction cell_latent_dim = 24 image_shape = [36, 64, 1] architecture = [[17,16],[5,8],[3,4],[3,4],16,'same','batch'] inputs = [tfk.Input([stimuli, neurons], name='responses'), tfk.Input([stimuli, *image_shape], name='stimuli')] predictor = Predictor(cell_latent_dim=cell_latent_dim, architecture=architecture, cummulative=True, contrastive_weight=0, l2_weight=0) model = tfk.Model(inputs, predictor(inputs)) model.compile(loss=negloglik, metrics=[pearson, 'mse'], optimizer=tf.optimizers.Adam(learning_rate=1e-3, clipnorm=10)) model.load_weights('fnp_mouse_visual') # Load data into memory. Follow instruction in the PNO directory to # download the test dataset from dataset import FileTreeDataset dat = FileTreeDataset('../pno/data/Lurz2020/static20457-5-9-preproc0', 'images', 'responses') trials = range(len(dat)) stimuli = np.stack([dat[i][0][0] for i in trials], axis=0) responses = np.stack([dat[i][1] for i in trials], axis=0) # compare to the same units used in the PNO experiment test_units = np.load('20457-5-9_test_units.npy') trials = dat.trial_info.tiers == 'train' # this indicates not repeated test_stimuli = stimuli[np.newaxis, trials, ..., np.newaxis].astype(np.float32) test_responses = responses[np.newaxis, trials, ...][..., np.isin(dat.neurons.unit_ids, test_units) ].astype(np.float32) # Can use the version of these in the predictor to use samples from # distribution, or these to sample the mean (when testing) import tensorflow as tf import tensorflow_probability as tfp from tuning_manifold.fnp_model import DeepSetSimple, HigherRankOperator, image_to_distribution from tuning_manifold.util import interpolate_bilinear tfk = tf.keras tfpl = tfp.layers predictor = model.layers[2] location_predictor = predictor.location_predictor # draw samples from the distribution and move them from the batch dimension heatmap_to_dist_mean = tf.keras.layers.Lambda(lambda x: tf.expand_dims(image_to_distribution(x).mean(), axis=1)) mean_location_predictor = tfk.Sequential([ # Perform convolution on each g-response image and output flattend version location_predictor.layers[0], # Exclusive set collapse DeepSetSimple(True), # Take the collapsed image and convert to distribution HigherRankOperator(heatmap_to_dist_mean) ], name='mean_location_predictor') feature_mlp = predictor.feature_mlp feature_mlp.layers[5] = tfpl.MultivariateNormalTriL(cell_latent_dim, convert_to_tensor_fn=lambda x: x.mean()) def compute_summary(predictor, inputs, return_im_feat=False, samples=1): responses, stimuli = inputs # convolve input stimuli g = predictor.im_conv_wrapper(stimuli) gr = predictor.crc([responses, g]) sample_locations = mean_location_predictor(gr) # extract the image feature for each trial x neuron estimate of the location bs, stimuli, Ny, Nx, Nc = g.shape bs, stimuli, neurons, samples, coordinates = sample_locations.shape tf.assert_equal(coordinates, 2) im_feat = interpolate_bilinear(tf.reshape(g, [-1, Ny, Nx, Nc]), tf.reshape(sample_locations, [-1, neurons * samples, 2])) im_feat = tf.reshape(im_feat, [-1, stimuli, neurons, samples, Nc]) # construct vector for each trial that includes information about the responses # and the feature, including a STA type response response_samples = tf.tile(responses[:, :, :, None, None], [1, 1, 1, samples, 1]) x2 = tf.concat([im_feat, im_feat * response_samples, response_samples], axis=-1) # then let those interact through an MLP and then compute an average feature. # again for trial N this is computed only using information from the other # trials. This should compute a summary statistics describing a neuron (other # than the spatial location) based on those other trials. cell_summary = feature_mlp(x2) if not return_im_feat: return sample_locations, cell_summary else: return sample_locations, cell_summary, im_feat def compute_rs(model, inputs, max_trial=1000, trials=[10, 25, 50, 100, 250, 500, 1000]): import scipy responses, stimuli = inputs r = responses[:,:max_trial,...] s = stimuli[:,:max_trial,...] predictor = model.layers[-1] sample_location, cell_summary = compute_summary(predictor, (r, s)) im_conv = predictor.im_conv_wrapper.operator g = im_conv(stimuli[0, max_trial:]) rs = [] for trial in trials: trial_sample_locations = sample_location[0, -1, :, 0, :] w, b = cell_summary[0, trial-1, :, 0, :-1], cell_summary[0, trial-1, :, 0, -1] w = tf.expand_dims(w, 0) b = tf.expand_dims(b, 0) locations = tf.reshape(trial_sample_locations, [1, trial_sample_locations.shape[0], trial_sample_locations.shape[-1]]) locations = tf.tile(locations, [g.shape[0], 1, 1]) im_feat = interpolate_bilinear(g, locations) t = tf.reduce_sum(tf.multiply(im_feat, w), axis=-1) + b t = tf.nn.elu(t) + 1 r = [scipy.stats.pearsonr(responses[0, max_trial:, i], t[:, i].numpy())[0] for i in range(t.shape[1])] rs.append(r) return trials, np.array(rs) all_rs = [] for i in np.arange(0, 1000, 10): trials, rs = compute_rs(model, (test_responses[:, :, i:i+10], test_stimuli), max_trial=1024, trials=np.arange(25,1025,25)) all_rs.append(rs) all_rs = np.concatenate(all_rs, axis=1) plt.semilogx(trials, np.mean(all_rs, axis=1), 'k.-') plt.xlabel('Observation set size (K)') plt.ylabel('Pearson R'); sns.despine(trim=False) ```
github_jupyter
[source](../../api/alibi_detect.ad.adversarialae.rst) # Adversarial Auto-Encoder ## Overview The adversarial detector follows the method explained in the [Adversarial Detection and Correction by Matching Prediction Distributions](https://arxiv.org/abs/2002.09364) paper. Usually, autoencoders are trained to find a transformation $T$ that reconstructs the input instance $x$ as accurately as possible with loss functions that are suited to capture the similarities between x and $x'$ such as the mean squared reconstruction error. The novelty of the adversarial autoencoder (AE) detector relies on the use of a classification model-dependent loss function based on a distance metric in the output space of the model to train the autoencoder network. Given a classification model $M$ we optimise the weights of the autoencoder such that the [KL-divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between the model predictions on $x$ and on $x'$ is minimised. Without the presence of a reconstruction loss term $x'$ simply tries to make sure that the prediction probabilities $M(x')$ and $M(x)$ match without caring about the proximity of $x'$ to $x$. As a result, $x'$ is allowed to live in different areas of the input feature space than $x$ with different decision boundary shapes with respect to the model $M$. The carefully crafted adversarial perturbation which is effective around x does not transfer to the new location of $x'$ in the feature space, and the attack is therefore neutralised. Training of the autoencoder is unsupervised since we only need access to the model prediction probabilities and the normal training instances. We do not require any knowledge about the underlying adversarial attack and the classifier weights are frozen during training. The detector can be used as follows: * An adversarial score $S$ is computed. $S$ equals the K-L divergence between the model predictions on $x$ and $x'$. * If $S$ is above a threshold (explicitly defined or inferred from training data), the instance is flagged as adversarial. * For adversarial instances, the model $M$ uses the reconstructed instance $x'$ to make a prediction. If the adversarial score is below the threshold, the model makes a prediction on the original instance $x$. This procedure is illustrated in the diagram below: ![adversarialae](image/adversarialae.png) The method is very flexible and can also be used to detect common data corruptions and perturbations which negatively impact the model performance. The algorithm works well on tabular and image data. ## Usage ### Initialize Parameters: * `threshold`: threshold value above which the instance is flagged as an adversarial instance. * `encoder_net`: `tf.keras.Sequential` instance containing the encoder network. Example: ```python encoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(32, 32, 3)), Conv2D(32, 4, strides=2, padding='same', activation=tf.nn.relu, kernel_regularizer=l1(1e-5)), Conv2D(64, 4, strides=2, padding='same', activation=tf.nn.relu, kernel_regularizer=l1(1e-5)), Conv2D(256, 4, strides=2, padding='same', activation=tf.nn.relu, kernel_regularizer=l1(1e-5)), Flatten(), Dense(40) ] ) ``` * `decoder_net`: `tf.keras.Sequential` instance containing the decoder network. Example: ```python decoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(40,)), Dense(4 * 4 * 128, activation=tf.nn.relu), Reshape(target_shape=(4, 4, 128)), Conv2DTranspose(256, 4, strides=2, padding='same', activation=tf.nn.relu, kernel_regularizer=l1(1e-5)), Conv2DTranspose(64, 4, strides=2, padding='same', activation=tf.nn.relu, kernel_regularizer=l1(1e-5)), Conv2DTranspose(3, 4, strides=2, padding='same', activation=None, kernel_regularizer=l1(1e-5)) ] ) ``` * `ae`: instead of using a separate encoder and decoder, the AE can also be passed as a `tf.keras.Model`. * `model`: the classifier as a `tf.keras.Model`. Example: ```python inputs = tf.keras.Input(shape=(input_dim,)) outputs = tf.keras.layers.Dense(output_dim, activation=tf.nn.softmax)(inputs) model = tf.keras.Model(inputs=inputs, outputs=outputs) ``` * `hidden_layer_kld`: dictionary with as keys the number of the hidden layer(s) in the classification model which are extracted and used during training of the adversarial AE, and as values the output dimension for the hidden layer. Extending the training methodology to the hidden layers is optional and can further improve the adversarial correction mechanism. * `model_hl`: instead of passing a dictionary to `hidden_layer_kld`, a list with tf.keras models for the hidden layer K-L divergence computation can be passed directly. * `w_model_hl`: Weights assigned to the loss of each model in `model_hl`. Also used to weight the K-L divergence contribution for each model in `model_hl` when computing the adversarial score. * `temperature`: Temperature used for model prediction scaling. Temperature <1 sharpens the prediction probability distribution which can be beneficial for prediction distributions with high entropy. * `data_type`: can specify data type added to metadata. E.g. *'tabular'* or *'image'*. Initialized adversarial detector example: ```python from alibi_detect.ad import AdversarialAE ad = AdversarialAE( encoder_net=encoder_net, decoder_net=decoder_net, model=model, temperature=0.5 ) ``` ### Fit We then need to train the adversarial detector. The following parameters can be specified: * `X`: training batch as a numpy array. * `loss_fn`: loss function used for training. Defaults to the custom adversarial loss. * `w_model`: weight on the loss term minimizing the K-L divergence between model prediction probabilities on the original and reconstructed instance. Defaults to 1. * `w_recon`: weight on the mean squared error reconstruction loss term. Defaults to 0. * `optimizer`: optimizer used for training. Defaults to [Adam](https://arxiv.org/abs/1412.6980) with learning rate 1e-3. * `epochs`: number of training epochs. * `batch_size`: batch size used during training. * `verbose`: boolean whether to print training progress. * `log_metric`: additional metrics whose progress will be displayed if verbose equals True. * `preprocess_fn`: optional data preprocessing function applied per batch during training. ```python ad.fit(X_train, epochs=50) ``` The threshold for the adversarial score can be set via ```infer_threshold```. We need to pass a batch of instances $X$ and specify what percentage of those we consider to be normal via `threshold_perc`. Even if we only have normal instances in the batch, it might be best to set the threshold value a bit lower (e.g. $95$%) since the the model could have misclassified training instances leading to a higher score if the reconstruction picked up features from the correct class or some instances might look adversarial in the first place. ```python ad.infer_threshold(X_train, threshold_perc=95, batch_size=64) ``` ### Detect We detect adversarial instances by simply calling `predict` on a batch of instances `X`. We can also return the instance level adversarial score by setting `return_instance_score` to True. The prediction takes the form of a dictionary with `meta` and `data` keys. `meta` contains the detector's metadata while `data` is also a dictionary which contains the actual predictions stored in the following keys: * `is_adversarial`: boolean whether instances are above the threshold and therefore adversarial instances. The array is of shape *(batch size,)*. * `instance_score`: contains instance level scores if `return_instance_score` equals True. ```python preds_detect = ad.predict(X, batch_size=64, return_instance_score=True) ``` ### Correct We can immediately apply the procedure sketched out in the above diagram via ```correct```. The method also returns a dictionary with `meta` and `data` keys. On top of the information returned by ```detect```, 3 additional fields are returned under `data`: * `corrected`: model predictions by following the adversarial detection and correction procedure. * `no_defense`: model predictions without the adversarial correction. * `defense`: model predictions where each instance is corrected by the defense, regardless of the adversarial score. ```python preds_correct = ad.correct(X, batch_size=64, return_instance_score=True) ``` ## Examples ### Image [Adversarial detection on CIFAR10](../../examples/ad_ae_cifar10.nblink)
github_jupyter
# **Testing for Stuctural Breaks in Time Series Data with a Chow Test** ## **I. Introduction** I've written a bit on forecasting future stock prices and distributions of future stock prices. I'm proud of the models I built for those articles, but they will eventually be no more predictive than a monkey throwing darts at a board. Perhaps they'll perform worse. This will happen because the underlying system, of which we are modeling an aspect, will change. For an extreme example, a company whose stock we are trying to model goes out of business. The time series just ends. For a more subtle example, let's look at the relationship between oil prices and dollar exchange rates. I took historical real USD exchange rates measured against a broad basket of currencies and oil prices (WTI) going from January 1986 to February 2019 and indexed them to January 2000. I then took the natural logarithm of each, because this would give us the growth rate if we differenced the data and is a common transformation with time series data (and for dealing with skewed variables in non-time series analysis). As you can see, they appear inversely related over time. When one goes up, the other goes down. This makes sense because when people outside the US want to buy oil, they often need to use USD for the transaction. Oil prices rise and they need to exchange more of their domestic currency to buy the same amount. This in turn strengthens the dollar and the exchange rate goes down as demand for USD increases and supply of foreign currencies increase. (An exchange rate of 1 means it takes 1 USD to buy 1 unit of foreign currency. If it is 2, it takes 2 USD to buy 1 unit of foreign currency. If it is 0.5, 1 USD buys 2 units of the foreign currency). But, does the inverse relationship remain constant over time? Are there periods where a movement in one corresponds to a larger movement in the other relative to other times? This type of change in the relationship between oil prices and USD exchange rates could occur for a variety of reasons. For example, a major currency crisis across a region driving up demand for safe USD, while reducing demand for oil as the economy weakens. Perhaps a bunch of currencies disappear and one major one forms as the countries join a monetary union, like the EU. ``` # for linear algebra and mathematical functions import numpy as np # for dataframe manipulation import pandas as pd # for data visualization import matplotlib.pyplot as plt # for setting plot size import matplotlib as mpl # for changing the plot size in the Jupyter Notebook output %matplotlib inline # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # reads in data on historical oil prices and dollar exchange rates full_data = pd.read_csv('Oil Data.csv') # generates a variable for the growth rate of the Real Trade Weighted U.S. Dollar Index: # Broad, Goods indexed to January 2000 index_value = float(full_data.loc[full_data.Date == '01-2000']['TWEXBPA'].values) full_data['broad_r'] = list(full_data.TWEXBPA / index_value) full_data['ebroad_r'] = np.log(full_data.broad_r) # generates a variable for the growth rate of the Real Trade Weighted U.S. Dollar Index: # Major Currencies, Goods indexed to January 2000 index_value = float(full_data.loc[full_data.Date == '01-2000']['TWEXMPA'].values) full_data['major_r'] = list(full_data.TWEXMPA / index_value) full_data['emajor_r'] = np.log(full_data.major_r) # generates a variable for the growth rate of the Real Trade Weighted U.S. Dollar Index: # Other Important Trading Partners, Goods indexed to January 2000 index_value = float(full_data.loc[full_data.Date == '01-2000']['TWEXOPA'].values) full_data['oitp_r'] = list(full_data.TWEXOPA / index_value) full_data['eoitp_r'] = np.log(full_data.oitp_r) # generates a variable for the growth rate of Crude Oil Prices: West Texas Intermediate # (WTI) - Cushing, Oklahoma indexed to January 2000 index_value = float(full_data.loc[full_data.Date == '01-2000']['MCOILWTICO'].values) # adjusts for inflation prior to indexing to January 2000 full_data['po_r'] = full_data.MCOILWTICO / (full_data.Fred_CPIAUCNS / 100) / index_value full_data['epo_r'] = np.log(full_data.po_r) # creates a column for month full_data.Date = pd.to_datetime(full_data.Date) full_data['month'] = full_data.Date.map(lambda x: x.month) # creates a list of all the variables of interest variables_to_keep = ['epo_r', 'Date', 'month', 'ebroad_r', 'emajor_r', 'eoitp_r'] # creates a new dataframe containing only the variables of interest my_data = full_data[variables_to_keep] # creates dummy variables for each month, dropping January to avoid multicollinearity my_data = pd.concat([my_data, pd.get_dummies(my_data.month, drop_first = True)], axis = 1) # sets the Date as the index my_data.index = pd.DatetimeIndex(my_data.Date) # drops these columns for a tidy data set my_data = my_data.drop(['month', 'Date'], axis = 1) # the code below plots the real oil price growth rate with the USD vs Broad Currency Basket # exchange growth rate # Create some mock data time = my_data.index epo_r = my_data.epo_r ebroad_r = my_data.ebroad_r fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('Date (Monthly)') ax1.set_ylabel('Natural Log of Oil Prices', color = color) ax1.plot(time, epo_r, color=color) ax1.tick_params(axis = 'y', labelcolor = color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('Natural Log of USD Exchange Rate vs. Broad Currency Basket', color = color) # we already handled the x-label with ax1 ax2.plot(time, ebroad_r, color = color) ax2.tick_params(axis = 'y', labelcolor = color) plt.title('Natural Log of Oil Prices and USD Exchange Rates indexed to January 2000') fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() ``` ## **II. Detecting a Suspected Break at a Known Date: The Chow Test** The Chow Test tests if the true coefficients in two different regression models are equal. The null hypothesis is they are equal and the alternative hypothesis is they are not. Another way of saying this is that the null hypothesis is the model before the possible break point is the same as the model after the possible break point. The alternative hypothesis is the model fitting each periods are different. It formally tests this by performing an F-test on the Chow Statistic which is (RSS_pooled - (RSS1 + RSS2))/(number of independent variables plus 1 for the constant) divided by (RSS1 + RSS2)/(Number of observations in subsample 1 + Number of observations in subsample 2 - 2*(number of independent variables plus 1 for the constant). The models in each of the models (pooled, 1, 2) must have normally distributed error with mean 0, as well as independent and identically distributed errors, to satisfy the Gauss-Markov assumptions. I use the Chow test to test for a structural break at the introduction of the Euro in January 1999. This seems a reasonable possible structural break, because a handful of major currencies, and some minor ones, disappeared and a new very important currency was created. The creation of the Euro certainly qualifies as a major shock to currency markets and perhaps to the oil vs. dollar relationship. ``` #imports the chowtest package as ct, which is written by yours truly import chowtest as ct ``` Translating the independently and identically distributed residual requirement to English translates as constant mean and variance without serial correlation in the residuals. To test for this, I tested for auto-correlation and heteroskedasticity in my residuals. I did the same tests on their growth rates (the difference in natural logs). I also plotted the residuals and estimated their mean. The auto-correlation function plots strongly suggest that the residuals from the simple OLS model have strong auto-correlation, while the residuals from the OLS of the growth rates are not auto-correlated. ``` # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # to reduce typing, I saved ebroad_r as X and epo_r as y X = pd.DataFrame(my_data[['ebroad_r']]) y = pd.DataFrame(my_data.epo_r) # to reduce typing, I saved the differenced ebroad_r as X_diff and epo_r as y_diff X_diff = X.diff().dropna() y_diff = y.diff().dropna() # saves the residuals from the undifferenced X and y OLS model un_diffed_resids = ct.linear_residuals(X, y).residuals # saves the residuals from the differenced X and y OLS model diffed_resids = ct.linear_residuals(X_diff, y_diff).residuals # plots the ACF for the residuals of the OLS regression of epo_r on ebroad_r pd.plotting.autocorrelation_plot(un_diffed_resids) plt.show() # plots the ACF for the residuals of the OLS regression of the differenced epo_r on # differenced ebroad_r pd.plotting.autocorrelation_plot(diffed_resids) plt.show() ``` The Breusch-Pagan Test shows that heteroskedasticity is present in the OLS model. It is also present in the model of growth rates, but is much less severe. ``` from statsmodels.stats.diagnostic import het_breuschpagan # tests for heteroskedasticity in the full-sample residuals print('F-statistic for the Breusch-Pagan Test the OLS model: ' + str(het_breuschpagan(un_diffed_resids, X)[2])) print('p-value for the Breusch-Pagan F-Test the OLS model: ' + str(het_breuschpagan(un_diffed_resids, X)[3])) # tests for heteroskedasticity in the full-sample residuals print('F-statistic for the Breusch-Pagan Test the growth rate OLS model: ' + str(het_breuschpagan(diffed_resids, X_diff)[2])) print('p-value for the Breusch-Pagan R-Test the growth rate OLS model: ' + str(het_breuschpagan(diffed_resids, X_diff)[3])) ``` The histograms of residuals show a bell-curve shape to the residuals of the OLS model looking at growth rates. The histogram of residuals for the regular OLS model show a possibly double-humped shape. ``` # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # plots the histogram of residuals plt.hist(un_diffed_resids) # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # plots the histogram of residuals plt.hist(diffed_resids) ``` The normality tests for the residuals from each model are both failures. ``` # imports the normality test from scipy.stats from scipy.stats import normaltest # performs the normality test on the residuals from the non-differenced OLS model print(normaltest(un_diffed_resids)) # performs the normality test on the residuals from the differenced OLS model print(normaltest(diffed_resids)) ``` Despite failing the normality tests, the mean of the residuals of both models are essentially 0. The model of growth rates has residuals that are are independently distributed and bell-shaped based on the ACF plot, even though there is evidence of heteroskedasticity at the 0.05 significance level. For these reasons, I will proceed with my analysis using the growth rate model and assume my Chow Test result will be robust to the non-normality of residuals. ``` print('Mean of OLS residuals: ' + str(np.mean(un_diffed_resids))) print('Mean of OLS model of growth rate residuals: ' + str(np.mean(diffed_resids))) ``` I come to the same conclusion for the models estimating before and after the split dates and proceed with the Chow Test. ``` # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # creates split dates for our sample period stop = '1999-01-01' start = '1999-02-01' # plots the ACF for the residuals of the OLS regression of the differenced epo_r on # differenced ebroad_r pd.plotting.autocorrelation_plot(ct.linear_residuals(X_diff.loc[:stop], y_diff.loc[:stop]).residuals) plt.show() # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # tests for heteroskedasticity in the full-sample residuals print('F-statistic for the Breusch-Pagan Test the growth rate OLS model: ' + str(het_breuschpagan(ct.linear_residuals(X_diff.loc[:stop], y_diff.loc[:stop]).residuals, X_diff.loc[:stop])[2])) print('p-value for the Breusch-Pagan F-Test the growth rate OLS model: ' + str(het_breuschpagan(ct.linear_residuals(X_diff.loc[:stop], y_diff.loc[:stop]).residuals, X_diff.loc[:stop])[3])) print('Mean of OLS model of growth rate residuals pre-Euro: ' + str(np.mean(ct.linear_residuals(X_diff.loc[:stop], y_diff.loc[:stop]).residuals))) # plots the histogram of residuals plt.hist(ct.linear_residuals(X_diff.loc[:stop], y_diff.loc[:stop]).residuals) plt.show # sets the plot size to 12x8 mpl.rcParams['figure.figsize'] = (12,8) # plots the ACF for the residuals of the OLS regression of the differenced epo_r on # differenced ebroad_r pd.plotting.autocorrelation_plot(ct.linear_residuals(X_diff[start:], y_diff[start:]).residuals) plt.show() # tests for heteroskedasticity in the full-sample residuals print('F-statistic for the Breusch-Pagan Test the growth rate OLS model: ' + str(het_breuschpagan(ct.linear_residuals(X_diff.loc[start:], y_diff.loc[start:]).residuals, X_diff.loc[start:])[2])) print('p-value for the Breusch-Pagan F-Test the growth rate OLS model: ' + str(het_breuschpagan(ct.linear_residuals(X_diff.loc[start:], y_diff.loc[start:]).residuals, X_diff.loc[start:])[3])) print('Mean of OLS model of growth rate residuals pre-Euro: ' + str(np.mean(ct.linear_residuals(X_diff.loc[start:], y_diff.loc[start:]).residuals))) # plots the histogram of residuals plt.hist(ct.linear_residuals(X_diff.loc[start:], y_diff.loc[start:]).residuals) ``` The result of the Chow Test is a Chow Test statistic of about 4.24 tested against an F-distribution with 2 and 394 degrees of freedom. The p-value is about 0.0009, meaning if the models before and after the split date are actually the same and we did an infinite number of trials, 0.09% of our results would show this level of difference in the models due to sampling error. It is safe to say that the model of real oil price and dollar exchange growth rates is different pre-Euro and post-Euro introduction. ``` # performs the Chow Test ct.ChowTest(X.diff().dropna(), y.diff().dropna(), stop, start) ```
github_jupyter
### About The goal of this script is to process a few common keyphrase datasets, including - **Tokenize**: by default using method from Meng et al. 2017, which fits more for academic text since it splits strings by hyphen etc. and makes tokens more fine-grained. - keep [_<>,\(\)\.\'%] - replace digits with < digit > - split by [^a-zA-Z0-9_<>,#&\+\*\(\)\.\'%] - **Determine present/absent phrases**: determine whether a phrase appears verbatim in a text. This is believed a very important step for the evaluation of keyphrase-related tasks, since in general extraction methods cannot recall any phrases don't appear in the source text. ``` import os import sys import re import json import numpy as np from collections import defaultdict module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) module_path = os.path.abspath(os.path.join('../onmt')) if module_path not in sys.path: sys.path.append(module_path) import kp_evaluate import onmt.keyphrase.utils as utils dataset_names = ['inspec', 'krapivin', 'nus', 'semeval', 'kp20k', 'duc', 'stackexchange'] dataset_names = ['inspec', 'krapivin', 'nus', 'semeval', 'duc'] json_base_dir = '/Users/memray/project/kp/OpenNMT-kpg/data/keyphrase/json/' # path to the json folder for dataset_name in dataset_names: print(dataset_name) input_json_path = os.path.join(json_base_dir, dataset_name, '%s_test.json' % dataset_name) output_json_path = os.path.join(json_base_dir, dataset_name, '%s_test_meng17token.json' % dataset_name) doc_count, present_doc_count, absent_doc_count = 0, 0, 0 tgt_num, present_tgt_num, absent_tgt_num = [], [], [] # with open(input_json_path, 'r') as input_json, open(output_json_path, 'w') as output_json: with open(input_json_path, 'r') as input_json: for json_line in input_json: json_dict = json.loads(json_line) if dataset_name == 'stackexchange': json_dict['abstract'] = json_dict['question'] json_dict['keywords'] = json_dict['tags'] del json_dict['question'] del json_dict['tags'] title = json_dict['title'] abstract = json_dict['abstract'] fulltext = json_dict['fulltext'] if 'fulltext' in json_dict else '' keywords = json_dict['keywords'] if isinstance(keywords, str): keywords = keywords.split(';') json_dict['keywords'] = keywords # remove all the abbreviations/acronyms in parentheses in keyphrases keywords = [re.sub(r'\(.*?\)|\[.*?\]|\{.*?\}', '', kw) for kw in keywords] # tokenize text title_token = utils.meng17_tokenize(title) abstract_token = utils.meng17_tokenize(abstract) fulltext_token = utils.meng17_tokenize(fulltext) keywords_token = [utils.meng17_tokenize(kw) for kw in keywords] # replace numbers title_token = utils.replace_numbers_to_DIGIT(title_token, k=2) abstract_token = utils.replace_numbers_to_DIGIT(abstract_token, k=2) fulltext_token = utils.replace_numbers_to_DIGIT(fulltext_token, k=2) keywords_token = [utils.replace_numbers_to_DIGIT(kw, k=2) for kw in keywords_token] src_token = title_token+["."] + abstract_token + fulltext_token tgts_token = keywords_token # print(json_dict) # print(src_token) # print(tgts_token) # split tgts by present/absent src_seq = src_token tgt_seqs = tgts_token present_tgt_flags, _, _ = utils.if_present_duplicate_phrases(src_seq, tgt_seqs) present_tgts = [tgt for tgt, present in zip(tgt_seqs, present_tgt_flags) if present] absent_tgts = [tgt for tgt, present in zip(tgt_seqs, present_tgt_flags) if ~present] doc_count += 1 present_doc_count = present_doc_count + 1 if len(present_tgts) > 0 else present_doc_count absent_doc_count = absent_doc_count + 1 if len(absent_tgts) > 0 else absent_doc_count tgt_num.append(len(tgt_seqs)) present_tgt_num.append(len(present_tgts)) absent_tgt_num.append(len(absent_tgts)) # write to output json tokenized_dict = {'src': src_token, 'tgt': tgts_token, 'present_tgt': present_tgts, 'absent_tgt': absent_tgts} json_dict['meng17_tokenized'] = tokenized_dict # output_json.write(json.dumps(json_dict) + '\n') print('#doc=%d, #present_doc=%d, #absent_doc=%d, #tgt=%d, #present=%d, #absent=%d, %%absent=%.3f%%' % (doc_count, present_doc_count, absent_doc_count, sum(tgt_num), sum(present_tgt_num), sum(absent_tgt_num), sum(absent_tgt_num) / sum(tgt_num) * 100.0)) ``` ### source=title+abstract ``` inspec #doc=500, #present_doc=497, #absent_doc=381, #tgt=4913, #present=3858, #absent=1055 krapivin #doc=460, #present_doc=437, #absent_doc=417, #tgt=2641, #present=1485, #absent=1156 nus #doc=211, #present_doc=207, #absent_doc=195, #tgt=2461, #present=1263, #absent=1198 semeval #doc=100, #present_doc=100, #absent_doc=99, #tgt=1507, #present=671, #absent=836 kp20k #doc=19987, #present_doc=19048, #absent_doc=16357, #tgt=105181, #present=66595, #absent=38586 duc #doc=308, #present_doc=308, #absent_doc=38, #tgt=2484, #present=2421, #absent=63 stackexchange #doc=16000, #present_doc=13475, #absent_doc=10984, #tgt=43131, #present=24809, #absent=18322 ``` ### source=title+abstract+fulltext ``` inspec #doc=500, #present_doc=497, #absent_doc=381, #tgt=4913, #present=3858, #absent=1055 krapivin #doc=460, #present_doc=460, #absent_doc=238, #tgt=2641, #present=2218, #absent=423 nus #doc=211, #present_doc=211, #absent_doc=126, #tgt=2461, #present=2158, #absent=303 semeval #doc=100, #present_doc=100, #absent_doc=65, #tgt=1507, #present=1373, #absent=134 duc #doc=308, #present_doc=308, #absent_doc=38, #tgt=2484, #present=2421, #absent=63 ```
github_jupyter
# Misc tests used for evaluating how well RSSI translates to distance Note - this notebook still needs to be cleaned. We include it here so this work won't be lost ``` %matplotlib inline import pandas as pd import matplotlib import matplotlib.pyplot as plt onemeter_file_path = '../data/rssi_distance/expt4/expt_07_11_' data = pd.read_csv(onemeter_file_path+'1m.dat', skiprows=1, skipfooter=1, parse_dates=True, sep=' ', header=None, names=['MAC', 'RSSI', 'TIME']) macs = ['D9:CB:6E:1F:48:82,', 'F2:50:9D:7E:C8:0C,'] signal_strength_1m = [] for mac in macs: signal_strength_1m.append(pd.rolling_mean(data[data['MAC'] == mac]['RSSI'], 5, min_periods=4)) # Get a threshold value of signal strength for inide and outside the case based on an accuracy level def getThresholds(accuracy, arr_vals): result = [] for i in xrange(len(arr_vals)): sample_num = int((1-accuracy)*len(arr_vals[i])) result.append(sorted(arr_vals[i])[sample_num]) return result for badge in signal_strength_1m: badge.plot(kind='hist', alpha=0.5) plt.xlabel('Signal Strength') plt.ylabel('Count') plt.title('Distribution of signal values for 1 meter distance') plt.legend(macs, loc='upper right') [out_90, in_90] = getThresholds(0.9, [signal_strength_1m[0], signal_strength_1m[1]]) plt.axvline(x=out_90, linewidth=2.0, color='r') plt.axvline(x=in_90, linewidth=2.0, color='r') # D9 is outside the case and F2 is inside ... menttion on the graph def getDistance(rssi, n, a): return 10**((a-rssi)/(10*n)) ``` ### Compare the obtained constants against experiment conducted with multiple badges ### Combine signal distribution from multiple badge experiment as follows: ### Focus only on the 2 badges facing front in the top two levels (4 badges in total) ### Combine the data from 3 badges outside the case and treat the one outside the case separately ### Plot the distribution for the two groups of badges from the experiment and the function for distance using both these constants ``` multibadge_file_path = '../data/rssi_distance/expt6/expt_07_11_' raw_data = [] for i in xrange(2,9,2): raw_data.append(pd.read_csv(multibadge_file_path+str(i)+'f.dat', header=None, sep=' ', skiprows=1, skipfooter=1, parse_dates=True, names=['MAC', 'RSSI', 'TIME'])) macs = [['F2:50:9D:7E:C8:0C,'], ['D9:CB:6E:1F:48:82,', 'CD:A3:F0:C5:68:73,', 'D2:67:85:48:D5:EF,']] for i,distance in enumerate(raw_data): vals = [] for mac in macs: temp = distance[distance['MAC'].isin(mac)]['RSSI'] vals.append(pd.rolling_mean(temp, 5, min_periods=4)) [inside, outside] = getThresholds(0.9, [vals[0], vals[1]]) plt.figure(figsize=(10,7)) for j,val in enumerate(vals): val.plot(kind='hist', alpha=0.5) plt.xlabel('Signal Strength') plt.ylabel('Count') plt.title('Signal Strength Distribution For ' + str(2*(i+1)) + ' ft') plt.axvline(x=outside, linewidth=2.0, color='r', label='outside') plt.axvline(x=inside, linewidth=2.0, color='purple', label='inside') plt.legend(['outside', 'inside'], loc='upper left') signal_level = range(-70,-50) [outside, inside] = getThresholds(0.9, [signal_strength_1m[0], signal_strength_1m[1]]) distances = [[getDistance(level, 2.4, A)*3.33 for level in signal_level] for A in [outside, inside]] for i in xrange(len(distances)): plt.plot(signal_level, distances[i], linewidth=2.0) plt.xlabel('Signal strength (dB)') plt.ylabel('Distance (feet)') plt.title("Variation of distance with RSSI value for different 'n'") plt.legend(['outside', 'inside'], loc='upper right') labels = ['inside', 'outside'] for i,mac in enumerate(macs): vals = [] for distance in raw_data: temp = distance[distance['MAC'].isin(mac)]['RSSI'] vals.append(pd.rolling_mean(temp, 5, min_periods=4)) thresholds = getThresholds(0.9, vals) plt.figure(figsize=(10,7)) for j,val in enumerate(vals): val.plot(kind='hist', alpha=0.5) plt.axvline(x=thresholds[j], linewidth=2.0, color='red') plt.xlabel('Signal Strength') plt.ylabel('Count') plt.title('Signal Strength Distribution For Groups of badges across 2ft-8ft : ' + labels[i]) ``` ## Analysis for experiment with all badges inside the case and the receiver outside the case ``` cased_badges_file_path = '../data/rssi_distance/expt7/expt_07_29_' raw_data = [] for i in xrange(2,11,2): raw_data.append(pd.read_csv(cased_badges_file_path+str(i)+'f.dat', header=None, sep=' ', skiprows=1, skipfooter=1, parse_dates=True, names=['MAC', 'RSSI', 'TIME'])) vals = [] for i,distance in enumerate(raw_data): temp = distance['RSSI'] vals.append(pd.rolling_mean(temp, 5, min_periods=4)) thresholds = getThresholds(0.9, vals) plt.figure(figsize=(10,7)) for j,val in enumerate(vals): val.plot(kind='hist', alpha=0.5) plt.axvline(x=thresholds[j], linewidth=2.0, color='red', label=str(j)) plt.xlabel('Signal Strength') plt.ylabel('Count') plt.title('Signal Strength Distribution For 4 Badges In a Case (Receiver Outside) across 2ft-10ft : ') plt.legend(['t1', 't2', 't3', 't4', 't5','2ft', '4ft', '6ft', '8ft', '10ft'], loc='upper left') ``` ## Analysis For Badges and Receiver Inside the Case ``` receiver_inside_file_path = '../data/rssi_distance/expt8/expt_07_29_' raw_data = [] for i in xrange(2,11,2): raw_data.append(pd.read_csv(receiver_inside_file_path+str(i)+'f.dat', header=None, sep=' ', skiprows=1, skipfooter=1, parse_dates=True, names=['MAC', 'RSSI', 'TIME'])) vals = [] for i,distance in enumerate(raw_data): temp = distance['RSSI'] vals.append(pd.rolling_mean(temp, 5, min_periods=4)) thresholds = getThresholds(0.9, vals) plt.figure(figsize=(10,7)) for j,val in enumerate(vals): val.plot(kind='hist', alpha=0.5) plt.axvline(x=thresholds[j], linewidth=2.0, color='red', label=str(j)) plt.xlabel('Signal Strength') plt.ylabel('Count') plt.title('Signal Strength Distribution For 4 Badges In a Case (Receiver Inside) across 2ft-10ft : ') plt.legend(['t1', 't2', 't3', 't4', 't5','2ft', '4ft', '6ft', '8ft', '10ft'], loc='upper left') ```
github_jupyter
# Displacement controlled normal contact *** In this notebook we will make a contact model which solves a normal contact problem with a specified displacement. For normal contact problems with specified loads see the 'recreating the hertz solition numerically' example. Here again we will use the hertz solution as an easy way to verify that we are getting sensible results. First lets import everything we will need (no one actually writes these first it's just convention to put them at the top of the file) ``` %matplotlib inline import slippy.surface as s # surface generation and manipulation import slippy.contact as c # contact modelling import numpy as np # numerical functions import matplotlib.pyplot as plt # plotting ``` ## Making the surfaces In order to solve the problem the geometry must be set. As we are solving the hertz problem we will use an analytically defined round surface and an analytically defined flat surface. For your own analyses the geometry data can come from experimental data or be generated randomly. For more information on this see examples about the surface class and the analytical surfaces. Importantly at least one of the surfaces must be discrete to be used in a contact model. ``` flat_surface = s.FlatSurface(shift=(0, 0)) round_surface = s.RoundSurface((1, 1, 1), extent=(0.006, 0.006), shape=(255, 255), generate=True) ``` ## Setting the materials The material for each surface must also be set. This material controls the deformation behaviour of the surface, the fricition and wear behaviour must be set separately. Please see tutorials on adding sub models to the step for more information. ``` # set materials steel = c.Elastic('Steel', {'E': 200e9, 'v': 0.3}) aluminum = c.Elastic('Aluminum', {'E': 70e9, 'v': 0.33}) flat_surface.material = aluminum round_surface.material = steel ``` ## Making a contact model Now we have surfaces and materials, but we need a contact model to hold this information and control the solving of model steps, this will become more important when we have multiple steps but for now think of the contact model as a container that all of the information is put in. ``` # create model my_model = c.ContactModel('model-1', round_surface, flat_surface) ``` ## Making a model step and adding it to the model A step defines what happens to the surfaces during a set period. Here we will add a step that sets the interferance between the surfaces from the point of first touching. The resulting loads on the surfaces and deflections at each point on the surface will be found. This can then be combined with ther sub models to specify friction or wear behaviour etc. however in this example we will simply compare the results back to the hertz solution. In order to do this we will use the analytical hertz solver to generate a sensible interferance. ``` # Find the analytical result analy_result = c.hertz_full([1, 1], [np.inf, np.inf], [200e9, 70e9], [0.3, 0.33], 100) # Make the model step my_step = c.StaticStep(step_name='This is the step name', interference=analy_result['total_deflection']) # Add the step to the model my_model.add_step(my_step) ``` ## Model steps The steps of the model are stored in the steps property of the model, this is an ordered dictionary, with the keys being the same as the step names. To retrieve a step you can index thie dictionary with the step name. However, if you try to add two steps with the same name the first will be overwritten. ``` my_model.steps ``` ## Solving the model The entire model can then be solved using the solve method of the contact model. This will run through all the steps in order and return the model state at the end of the last step. Other information can be saved using output requests, but as we only have one step there is no need for this. Before running, by default the model will data check it's self, this action checks that each step and sub model can be solved with the information from the current state. It dosen't check for numerical stabiltiy or accuracy. This can be skipped if necessary. ``` final_state = my_model.solve() ``` ## Checking the model against the analytical result Now lets check the model results against the analytical result from the hertz solution. Althoug this particular step directly sets the interferance, most steps in slippy are solved iteratively, so it is a good idea to check that the set parameter converged to the desired value: ``` print('Solution converged at: ', final_state['interference'], ' interferance') print('Set interferance was:', analy_result['total_deflection']) ``` Lets check the maximum pressure, contact area and total load all match up with the analytical values: ``` print('Analytical total load: ', 100) print('Numerical total load: ', round_surface.grid_spacing**2*sum(final_state['loads_z'].flatten())) print('Analytical max pressure: ', analy_result['max_pressure']) print('Numerical max pressure: ', max(final_state['loads_z'].flatten())) print('Analytical contact area: ', analy_result['contact_area']) print('Numerical contact area: ', round_surface.grid_spacing**2* sum(final_state['contact_nodes'].flatten())) ``` ## Checking the form of the result We can also check that the individual surface loads line up with the analytical solution: ``` fig, axes = plt.subplots(1, 3, figsize=(20, 4)) X,Y = round_surface.get_points_from_extent() X,Y = X-X[-1,-1]/2 , Y-Y[-1,-1]/2 Z_n = final_state['loads_z'] axes[0].imshow(Z_n) axes[0].set_title('Numerical Result') R = np.sqrt(X**2+Y**2) Z_a = analy_result['pressure_f'](R) axes[1].imshow(Z_a) axes[1].set_title('Analytical Result') axes[2].imshow(np.abs(Z_a-Z_n)) for im in axes[2].get_images(): im.set_clim(0, analy_result['max_pressure']) _ = axes[2].set_title('Absolute Error') ``` ## Other items in the state dict Other items can be listed from the state dict by the following code: ``` print(list(final_state.keys())) ``` * 'just_touching_gap' The gap between the surface at the point when they first touch * 'surface_1_points' The points of the first surface which are in the solution domain * 'surface_2_points' The points of the second surface which are in the solution domain * 'time' The current modelled time which is 0 at the start of the model. This is used for submodels which introdce time dependent behaviour * 'time_step' The current time step, again used for submodels * 'new_step' Ture if this is the first substep in a model step * 'off_set' The tangential displacement between the surfaces at the end of the step * 'loads_z' The loads acting on each point of the surface * 'total_displacement_z' The total displacement of each point of the surface pair * 'surface_1_displacement_z' The displacement of each point on surface 1 * 'surface_2_displacement_z' The displacement of each point on surface 2 * 'contact_nodes' A boolean array showing which nodes are in contact, to find the percentage in contact simply take the mean of this array * 'total_normal_load' The total load pressing the surfaces together * 'interference' The distance the surfaces have pushed into eachother from the point of first touching * 'converged' True if the step converged to a soltuion * 'gap' The gap between the surfaces when loaded, including deformation ``` # getting the deformed gap between the surfaces def_gap = (final_state['gap']) plt.imshow(def_gap) ``` # Saving outputs You can also save outputs from the model by using an output request, but this is not needed for single step models
github_jupyter
# Cell Editing DataGrid cells can be edited using in-place editors built into DataGrid. Editing can be initiated by double clicking on a cell or by starting typing the new value for the cell. DataGrids are not editable by default. Editing can be enabled by setting `editable` property to `True`. Selection enablement is required for editing to work and it is set automatically to `cell` mode if it is `none` when editing is enabled. ### Cursor Movement Editing is initiated for the `cursor` cell. Cursor cell is the same as the selected cell if there is a single cell selected. If there are multiple cells / rectangles selected then cursor cell is the cell where the last selection rectangle was started. Cursor can be moved in four directions by using the following keyboard keys. - **Down**: Enter - **Up**: Shift + Enter - **Right**: Tab - **Left**: Shift + Tab Once done with editing a cell, cursor can be moved to next cell based on the keyboard hit following the rules above. ``` from ipydatagrid import DataGrid from json import load import pandas as pd with open("./cars.json") as fobj: data = load(fobj) df = pd.DataFrame(data["data"]).drop("index", axis=1) datagrid = DataGrid(df, editable=True, layout={"height": "200px"}) datagrid ``` All grid views are updated simultaneously to reflect cell edit changes. ``` datagrid # keep track of changed cells changed_cells = {} def create_cell_key(cell): return "{row}:{column}".format(row=cell["row"], column=cell["column_index"]) def track_changed_cell(cell): key = create_cell_key(cell) changed_cells[key] = cell ``` Changes to cell values can be tracked by subscribing to `on_cell_change` event as below. ``` def on_cell_changed(cell): track_changed_cell(cell) print( "Cell at primary key {row} and column '{column}'({column_index}) changed to {value}".format( row=cell["row"], column=cell["column"], column_index=cell["column_index"], value=cell["value"], ) ) datagrid.on_cell_change(on_cell_changed) ``` A cell's value can also be changed programmatically by using the DataGrid methods `set_cell_value` and `set_cell_value_by_index` ``` datagrid.set_cell_value("Cylinders", 2, 12) ``` Whether new cell values are entered using UI or programmatically, both the DataGrid cell rendering and the underlying python data are updated. ``` datagrid.data.iloc[2]["Cylinders"] datagrid.set_cell_value_by_index("Horsepower", 3, 169) datagrid.data.iloc[3]["Origin"] def select_all_changed_cells(): datagrid.clear_selection() for cell in changed_cells.values(): datagrid.select(cell["row"], cell["column_index"]) return datagrid.selected_cells ``` Show all cells changed using UI or programmatically by selecting them. ``` select_all_changed_cells() ```
github_jupyter
``` #convert ``` # babilim.training.losses > A package containing all losses. ``` #export from collections import defaultdict from typing import Any import json import numpy as np import babilim from babilim.core.itensor import ITensor from babilim.core.logging import info from babilim.core.tensor import Tensor from babilim.core.module import Module #export class Loss(Module): def __init__(self, reduction: str = "mean"): """ A loss is a statefull object which computes the difference between the prediction and the target. :param log_std: When true the loss will log its standard deviation. (default: False) :param log_min: When true the loss will log its minimum values. (default: False) :param log_max: When true the loss will log its maximal values. (default: False) :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__() self._accumulators = defaultdict(list) self.reduction = reduction if reduction not in ["none", "mean", "sum"]: raise NotImplementedError() def call(self, y_pred: Any, y_true: Any) -> ITensor: """ Implement a loss function between preds and true outputs. **DO NOT**: * Overwrite this function (overwrite `self.loss(...)` instead) * Call this function (call the module instead `self(y_pred, y_true)`) Arguments: :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ loss = self.loss(y_pred, y_true) if loss.is_nan().any(): raise ValueError("Loss is nan. Loss value: {}".format(loss)) if self.reduction == "mean": loss = loss.mean() elif self.reduction == "sum": loss = loss.sum() return loss def loss(self, y_pred: Any, y_true: Any) -> ITensor: """ Implement a loss function between preds and true outputs. **`loss` must be overwritten by subclasses.** **DO NOT**: * Call this function (call the module instead `self(y_pred, y_true)`) Arguments: :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ raise NotImplementedError("Every loss must implement the call method.") def log(self, name: str, value: ITensor) -> None: """ Log a tensor under a name. These logged values then can be used for example by tensorboard loggers. :param name: The name under which to log the tensor. :param value: The tensor that should be logged. """ if isinstance(value, ITensor): val = value.numpy() if len(val.shape) > 0: self._accumulators[name].append(val) else: self._accumulators[name].append(np.array([val])) else: self._accumulators[name].append(np.array([value])) def reset_avg(self) -> None: """ Reset the accumulation of tensors in the logging. Should only be called by a tensorboard logger. """ self._accumulators = defaultdict(list) def summary(self, samples_seen, summary_writer=None, summary_txt=None, log_std=False, log_min=False, log_max=False) -> None: """ Write a summary of the accumulated logs into tensorboard. :param samples_seen: The number of samples the training algorithm has seen so far (not iterations!). This is used for the x axis in the plot. If you use the samples seen it is independant of the batch size. If the network was trained for 4 batches with 32 batch size or for 32 batches with 4 batchsize does not matter. :param summary_writer: The summary writer to use for writing the summary. If none is provided it will use the tensorflow default. :param summary_txt: The file where to write the summary in csv format. """ results = {} if summary_writer is not None: for k in self._accumulators: if not self._accumulators[k]: continue combined = np.concatenate(self._accumulators[k], axis=0) summary_writer.add_scalar("{}".format(k), combined.mean(), global_step=samples_seen) results[f"{k}"] = combined.mean() if log_std: results[f"{k}_std"] = combined.std() summary_writer.add_scalar("{}_std".format(k), results[f"{k}_std"], global_step=samples_seen) if log_min: results[f"{k}_min"] = combined.min() summary_writer.add_scalar("{}_min".format(k), results[f"{k}_min"], global_step=samples_seen) if log_max: results[f"{k}_max"] = combined.max() summary_writer.add_scalar("{}_max".format(k), results[f"{k}_max"], global_step=samples_seen) else: import tensorflow as tf for k in self._accumulators: if not self._accumulators[k]: continue combined = np.concatenate(self._accumulators[k], axis=0) tf.summary.scalar("{}".format(k), combined.mean(), step=samples_seen) results[f"{k}"] = combined.mean() if log_std: results[f"{k}_std"] = combined.std() tf.summary.scalar("{}_std".format(k), results[f"{k}_std"], step=samples_seen) if log_min: results[f"{k}_min"] = combined.min() tf.summary.scalar("{}_min".format(k), results[f"{k}_min"], step=samples_seen) if log_max: results[f"{k}_max"] = combined.max() tf.summary.scalar("{}_max".format(k), results[f"{k}_max"], step=samples_seen) if summary_txt is not None: results["samples_seen"] = samples_seen for k in results: results[k] = f"{results[k]:.5f}" with open(summary_txt, "a") as f: f.write(json.dumps(results)+"\n") @property def avg(self): """ Get the average of the loged values. This is helpfull to print values that are more stable than values from a single iteration. """ avgs = {} for k in self._accumulators: if not self._accumulators[k]: continue combined = np.concatenate(self._accumulators[k], axis=0) avgs[k] = combined.mean() return avgs #export class NativeLossWrapper(Loss): def __init__(self, loss, reduction: str = "mean"): """ Wrap a native loss as a babilim loss. The wrapped object must have the following signature: ```python Callable(y_pred, y_true, log_val) -> Tensor ``` where log_val will be a function which can be used for logging scalar tensors/values. :param loss: The loss that should be wrapped. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) self.native_loss = loss self._auto_device() def _auto_device(self): if babilim.is_backend(babilim.PYTORCH_BACKEND): import torch self.native_loss = self.native_loss.to(torch.device(self.device)) return self def loss(self, y_pred: Any, y_true: Any) -> ITensor: """ Compute the loss using the native loss function provided in the constructor. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ # Unwrap arguments tmp = y_true._asdict() y_true_tmp = {k: tmp[k].native for k in tmp} y_true = type(y_true)(**y_true_tmp) tmp = y_pred._asdict() y_pred_tmp = {k: tmp[k].native for k in tmp} y_pred = type(y_pred)(**y_pred_tmp) # call function result = self.native_loss(y_pred=y_pred, y_true=y_true, log_val=lambda name, tensor: self.log(name, Tensor(data=tensor, trainable=True))) return Tensor(data=result, trainable=True) #export class SparseCrossEntropyLossFromLogits(Loss): def __init__(self, reduction: str = "mean"): """ Compute a sparse cross entropy. This means that the preds are logits and the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) if babilim.is_backend(babilim.PYTORCH_BACKEND): from torch.nn import CrossEntropyLoss self.loss_fun = CrossEntropyLoss(reduction="none") else: from tensorflow.nn import sparse_softmax_cross_entropy_with_logits self.loss_fun = sparse_softmax_cross_entropy_with_logits def loss(self, y_pred: ITensor, y_true: ITensor) -> ITensor: """ Compute the sparse cross entropy assuming y_pred to be logits. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ y_true = y_true.cast("int64") if babilim.is_backend(babilim.PYTORCH_BACKEND): return Tensor(data=self.loss_fun(y_pred.native, y_true.native), trainable=True) else: return Tensor(data=self.loss_fun(labels=y_true.native, logits=y_pred.native), trainable=True) #export class BinaryCrossEntropyLossFromLogits(Loss): def __init__(self, reduction: str = "mean"): """ Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) if babilim.is_backend(babilim.PYTORCH_BACKEND): from torch.nn import BCEWithLogitsLoss self.loss_fun = BCEWithLogitsLoss(reduction="none") else: from tensorflow.nn import sigmoid_cross_entropy_with_logits self.loss_fun = sigmoid_cross_entropy_with_logits def loss(self, y_pred: ITensor, y_true: ITensor) -> ITensor: """ Compute the sparse cross entropy assuming y_pred to be logits. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ if babilim.is_backend(babilim.PYTORCH_BACKEND): return Tensor(data=self.loss_fun(y_pred.native, y_true.native), trainable=True) else: return Tensor(data=self.loss_fun(labels=y_true.native, logits=y_pred.native), trainable=True) #export class SmoothL1Loss(Loss): def __init__(self, reduction: str = "mean"): """ Compute a binary cross entropy. This means that the preds are logits and the targets are a binary (1 or 0) tensor of same shape as logits. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) if babilim.is_backend(babilim.PYTORCH_BACKEND): from torch.nn import SmoothL1Loss self.loss_fun = SmoothL1Loss(reduction="none") else: from tensorflow.keras.losses import huber self.loss_fun = huber self.delta = 1.0 def loss(self, y_pred: ITensor, y_true: ITensor) -> ITensor: """ Compute the sparse cross entropy assuming y_pred to be logits. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ if babilim.is_backend(babilim.PYTORCH_BACKEND): return Tensor(data=self.loss_fun(y_pred.native, y_true.native), trainable=True) else: return Tensor(data=self.loss_fun(labels=y_true.native, logits=y_pred.native, delta=self.delta), trainable=True) #export class MeanSquaredError(Loss): def __init__(self, reduction: str = "mean"): """ Compute the mean squared error. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) def loss(self, y_pred: ITensor, y_true: ITensor, axis: int=-1) -> ITensor: """ Compute the mean squared error. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param axis: (Optional) The axis along which to compute the mean squared error. """ return ((y_pred - y_true) ** 2).mean(axis=axis) #export class SparseCategoricalAccuracy(Loss): def __init__(self, reduction: str = "mean"): """ Compute the sparse mean squared error. Sparse means that the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of elements in the output, `'sum'`: the output will be summed. Default: 'mean'. """ super().__init__(reduction=reduction) def loss(self, y_pred: ITensor, y_true: ITensor, axis: int=-1) -> ITensor: """ Compute the sparse categorical accuracy. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param axis: (Optional) The axis along which to compute the sparse categorical accuracy. """ pred_class = y_pred.argmax(axis=axis) true_class = y_true.cast("int64") correct_predictions = pred_class == true_class return correct_predictions.cast("float32").mean(axis=axis) #export class NaNMaskedLoss(Loss): def __init__(self, loss): """ Compute a sparse cross entropy. This means that the preds are logits and the targets are not one hot encoded. :param loss: The loss that should be wrapped and only applied on non nan values. """ super().__init__(reduction="none") self.wrapped_loss = loss self.zero = Tensor(data=np.array(0), trainable=False) def loss(self, y_pred: ITensor, y_true: ITensor) -> ITensor: """ Compute the loss given in the constructor only on values where the GT is not NaN. :param y_pred: The predictions of the network. Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. :param y_true: The desired outputs of the network (labels). Either a NamedTuple pointing at ITensors or a Dict or Tuple of ITensors. """ binary_mask = (~y_true.is_nan()) mask = binary_mask.cast("float32") masked_y_true = (y_true * mask)[binary_mask] if y_pred.shape[-1] != binary_mask.shape[-1] and binary_mask.shape[-1] == 1: new_shape = binary_mask.shape[:-1] binary_mask = binary_mask.reshape(new_shape) masked_y_pred = (y_pred * mask)[binary_mask] if masked_y_pred.shape[0] > 0: loss = self.wrapped_loss(masked_y_pred, masked_y_true) else: loss = self.zero return loss ```
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # Inference Bert Model for High Performance with ONNX Runtime on AzureML # This tutorial includes how to pretrain and finetune Bert models using AzureML, convert it to ONNX, and then deploy the ONNX model with ONNX Runtime through Azure ML. In the following sections, we are going to use the Bert model trained with Stanford Question Answering Dataset (SQuAD) dataset as an example. Bert SQuAD model is used in question answering scenarios, where the answer to every question is a segment of text, or span, from the corresponding reading passage, or the question might be unanswerable. ## Roadmap 0. **Prerequisites** to set up your Azure ML work environments. 1. **Pre-train, finetune and export Bert model** from other framework using Azure ML. 2. **Deploy Bert model using ONNX Runtime and AzureML** ## Step 0 - Prerequisites If you are using an [Azure Machine Learning Notebook VM](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-run-cloud-notebook), you are all set. Otherwise, refer to the [configuration Notebook](https://github.com/Azure/MachineLearningNotebooks/blob/56e0ebc5acb9614fac51d8b98ede5acee8003820/configuration.ipynb) first if you haven't already to establish your connection to the AzureML Workspace. Prerequisites are: * Azure subscription * Azure Machine Learning Workspace * Azure Machine Learning SDK Also to make the best use of your time, make sure you have done the following: * Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning * [Azure Portal](https://portal.azure.com) allows you to track the status of your deployments. ## Step 1 - Pretrain, Finetune and Export Bert Model (PyTorch) If you'd like to pre-train and finetune a Bert model from scratch, follow the instructions in [ Pretraining of the BERT model](https://github.com/microsoft/AzureML-BERT/blob/master/pretrain/PyTorch/notebooks/BERT_Pretrain.ipynb) to pretrain a Bert model in PyTorch using AzureML. Once you have the pretrained model, refer to [AzureML Bert Eval Squad](https://github.com/microsoft/AzureML-BERT/blob/master/finetune/PyTorch/notebooks/BERT_Eval_SQUAD.ipynb) or [AzureML Bert Eval GLUE](https://github.com/microsoft/AzureML-BERT/blob/master/finetune/PyTorch/notebooks/BERT_Eval_GLUE.ipynb) to finetune your model with your desired dataset. Follow the tutorials all the way through **Create a PyTorch estimator for fine-tuning**. Before creating a Pytorch estimator, we need to prepare an entry file that trains and exports the PyTorch model together. Make sure the entry file has the following code to create an ONNX file: ``` output_model_path = "bert_azureml_large_uncased.onnx" # set the model to inference mode # It is important to call torch_model.eval() or torch_model.train(False) before exporting the model, # to turn the model to inference mode. This is required since operators like dropout or batchnorm # behave differently in inference and training mode. model.eval() # Generate dummy inputs to the model. Adjust if neccessary inputs = { 'input_ids': torch.randint(32, [2, 32], dtype=torch.long).to(device), # list of numerical ids for the tokenised text 'attention_mask': torch.ones([2, 32], dtype=torch.long).to(device), # dummy list of ones 'token_type_ids': torch.ones([2, 32], dtype=torch.long).to(device), # dummy list of ones } symbolic_names = {0: 'batch_size', 1: 'max_seq_len'} torch.onnx.export(model, # model being run (inputs['input_ids'], inputs['attention_mask'], inputs['token_type_ids']), # model input (or a tuple for multiple inputs) output_model_path, # where to save the model (can be a file or file-like object) opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input_ids', 'input_mask', 'segment_ids'], # the model's input names output_names=['start', "end"], # the model's output names dynamic_axes={'input_ids': symbolic_names, 'input_mask' : symbolic_names, 'segment_ids' : symbolic_names, 'start' : symbolic_names, 'end': symbolic_names}) # variable length axes ``` In this directory, a `run_squad_azureml.py` containing the above code is available for use. Copy the training script `run_squad_azureml.py` to your `project_root` (defined at an earlier step in [AzureML Bert Eval Squad](https://github.com/microsoft/AzureML-BERT/blob/master/finetune/PyTorch/notebooks/BERT_Eval_SQUAD.ipynb)) ``` shutil.copy('run_squad_azureml.py', project_root) ``` Now you may continue to follow the **Create a PyTorch estimator for fine-tuning** section in [AzureML Bert Eval Squad](https://github.com/microsoft/AzureML-BERT/blob/master/finetune/PyTorch/notebooks/BERT_Eval_SQUAD.ipynb). In creating the estimator, change `entry_script` parameter to point to the `run_squad_azureml.py` we just copied as noted in the following code. ``` estimator = PyTorch(source_directory=project_roots, script_params={'--output-dir': './outputs'}, compute_target=gpu_compute_target, use_docker=True custom_docker_image=image_name script_params = {...} entry_script='run_squad_azureml.py', # change here node_count=1, process_count_per_node=4, distributed_backend='mpi', use_gpu=True) ``` Follow the rest of the [AzureML Bert Eval Squad](https://github.com/microsoft/AzureML-BERT/blob/master/finetune/PyTorch/notebooks/BERT_Eval_SQUAD.ipynb) to run and export your model. ## Step 2 - Deploy Bert model with ONNX Runtime through AzureML In Step 1 and 2, we have prepared an optimized ONNX Bert model and now we can deploy this model as a web service using Azure Machine Learning services and the ONNX Runtime. We're now going to deploy our ONNX model on Azure ML using the following steps. 1. **Register our model** in our Azure Machine Learning workspace 2. **Write a scoring file** to evaluate our model with ONNX Runtime 3. **Write environment file** for our Docker container image. 4. **Deploy to the cloud** using an Azure Container Instances VM and use it to make predictions using ONNX Runtime Python APIs 5. **Classify sample text input** so we can explore inference with our deployed service. ![End-to-end pipeline with ONNX Runtime](https://raw.githubusercontent.com/vinitra/models/gtc-demo/gtc-demo/E2EPicture.png) ## Step 2.0 - Check your AzureML environment ``` # Check core SDK version number import azureml.core from PIL import Image, ImageDraw, ImageFont import json import numpy as np import matplotlib.pyplot as plt %matplotlib inline print("SDK version:", azureml.core.VERSION) ``` ### Load your Azure ML workspace We begin by instantiating a workspace object from the existing workspace created earlier in the configuration notebook. ``` from azureml.core import Workspace ws = Workspace.from_config() print(ws.name, ws.location, ws.resource_group, sep = '\n') ``` ## Step 2.1 - Register your model with Azure ML Now we upload the model and register it in the workspace. In the following tutorial. we use the bert SQuAD model outputted from Step 1 as an example. You can also register the model from your run to your workspace. The model_path parameter takes in the relative path on the remote VM to the model file in your outputs directory. You can then deploy this registered model as a web service through the AML SDK. ``` model = run.register_model(model_path = "./bert_azureml_large_uncased.onnx", # Name of the registered model in your workspace. model_name = "bert-squad-large-uncased", # Local ONNX model to upload and register as a model model_framework=Model.Framework.ONNX , # Framework used to create the model. model_framework_version='1.6', # Version of ONNX used to create the model. tags = {"onnx": "demo"}, description = "Bert-large-uncased squad model exported from PyTorch", workspace = ws) ``` Alternatively, if you're working on a local model and want to deploy it to AzureML, upload your model to the same directory as this notebook and register it with `Model.register()` ``` from azureml.core.model import Model model = Model.register(model_path = "./bert_azureml_large_uncased.onnx", # Name of the registered model in your workspace. model_name = "bert-squad-large-uncased", # Local ONNX model to upload and register as a model model_framework=Model.Framework.ONNX , # Framework used to create the model. model_framework_version='1.6', # Version of ONNX used to create the model. tags = {"onnx": "demo"}, description = "Bert-large-uncased squad model exported from PyTorch", workspace = ws) ``` #### Displaying your registered models You can optionally list out all the models that you have registered in this workspace. ``` models = ws.models for name, m in models.items(): print("Name:", name,"\tVersion:", m.version, "\tDescription:", m.description, m.tags) # # If you'd like to delete the models from workspace # model_to_delete = Model(ws, name) # model_to_delete.delete() ``` ## Step 2.2 - Write scoring file We are now going to deploy our ONNX model on Azure ML using the ONNX Runtime. We begin by writing a score.py file that will be invoked by the web service call. The `init()` function is called once when the container is started so we load the model using the ONNX Runtime into a global session object. Then the `run()` function is called when we run the model using the Azure ML web service. Add neccessary `preprocess()` and `postprocess()` steps. The following score.py file uses `bert-squad` as an example and assumes the inputs will be in the following format. ``` inputs_json = { "version": "1.4", "data": [ { "paragraphs": [ { "context": "In its early years, the new convention center failed to meet attendance and revenue expectations.[12] By 2002, many Silicon Valley businesses were choosing the much larger Moscone Center in San Francisco over the San Jose Convention Center due to the latter's limited space. A ballot measure to finance an expansion via a hotel tax failed to reach the required two-thirds majority to pass. In June 2005, Team San Jose built the South Hall, a $6.77 million, blue and white tent, adding 80,000 square feet (7,400 m2) of exhibit space", "qas": [ { "question": "where is the businesses choosing to go?", "id": "1" }, { "question": "how may votes did the ballot measure need?", "id": "2" }, { "question": "When did businesses choose Moscone Center?", "id": "3" } ] } ], "title": "Conference Center" } ] } %%writefile score.py import os import collections import json import time from azureml.core.model import Model import numpy as np # we're going to use numpy to process input and output data import onnxruntime # to inference ONNX models, we use the ONNX Runtime import wget from pytorch_pretrained_bert.tokenization import whitespace_tokenize, BasicTokenizer, BertTokenizer def init(): global session, tokenizer # use AZUREML_MODEL_DIR to get your deployed model(s). If multiple models are deployed, # model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), '$MODEL_NAME/$VERSION/$MODEL_FILE_NAME') model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'bert_azureml_large_uncased.onnx') sess_options = onnxruntime.SessionOptions() # Set graph optimization level to ORT_ENABLE_EXTENDED to enable bert optimization session = onnxruntime.InferenceSession(model_path, sess_options) tokenizer = BertTokenizer.from_pretrained("bert-large-uncased", do_lower_case=True) # download run_squad.py and tokenization.py from # https://github.com/onnx/models/tree/master/text/machine_comprehension/bert-squad to # help with preprocessing and post-processing. if not os.path.exists('./run_onnx_squad.py'): url = "https://raw.githubusercontent.com/onnx/models/master/text/machine_comprehension/bert-squad/dependencies/run_onnx_squad.py" wget.download(url, './run_onnx_squad.py') if not os.path.exists('./tokenization.py'): url = "https://raw.githubusercontent.com/onnx/models/master/text/machine_comprehension/bert-squad/dependencies/tokenization.py" wget.download(url, './tokenization.py') def preprocess(input_data_json): global all_examples, extra_data # Model configs. Adjust as needed. max_seq_length = 128 doc_stride = 128 max_query_length = 64 # Write the input json to file to be used by read_squad_examples() input_data_file = "input.json" with open(input_data_file, 'w') as outfile: json.dump(json.loads(input_data_json), outfile) from run_onnx_squad import read_squad_examples, convert_examples_to_features # Use read_squad_examples method from run_onnx_squad to read the input file all_examples = read_squad_examples(input_file=input_data_file) # Use convert_examples_to_features method from run_onnx_squad to get parameters from the input input_ids, input_mask, segment_ids, extra_data = convert_examples_to_features(all_examples, tokenizer, max_seq_length, doc_stride, max_query_length) return input_ids, input_mask, segment_ids def postprocess(all_results): # postprocess results from run_onnx_squad import write_predictions n_best_size = 20 max_answer_length = 30 output_dir = 'predictions' os.makedirs(output_dir, exist_ok=True) output_prediction_file = os.path.join(output_dir, "predictions.json") output_nbest_file = os.path.join(output_dir, "nbest_predictions.json") # Write the predictions (answers to the questions) in a file. write_predictions(all_examples, extra_data, all_results, n_best_size, max_answer_length, True, output_prediction_file, output_nbest_file) # Retrieve best results from file. result = {} with open(output_prediction_file, "r") as f: result = json.load(f) return result def run(input_data_json): try: # load in our data input_ids, input_mask, segment_ids = preprocess(input_data_json) RawResult = collections.namedtuple("RawResult", ["unique_id", "start_logits", "end_logits"]) n = len(input_ids) bs = 1 all_results = [] start = time.time() for idx in range(0, n): item = all_examples[idx] # this is using batch_size=1 # feed the input data as int64 data = { "segment_ids": segment_ids[idx:idx+bs], "input_ids": input_ids[idx:idx+bs], "input_mask": input_mask[idx:idx+bs] } result = session.run(["start", "end"], data) in_batch = result[0].shape[0] start_logits = [float(x) for x in result[1][0].flat] end_logits = [float(x) for x in result[0][0].flat] for i in range(0, in_batch): unique_id = len(all_results) all_results.append(RawResult(unique_id=unique_id, start_logits=start_logits, end_logits=end_logits)) end = time.time() print("total time: {}sec, {}sec per item".format(end - start, (end - start) / len(all_results))) return {"result": postprocess(all_results), "total_time": end - start, "time_per_item": (end - start) / len(all_results)} except Exception as e: result = str(e) return {"error": result} ``` ## Step 2.3 - Write Environment File We create a YAML file that specifies which dependencies we would like to see in our container. ``` from azureml.core.conda_dependencies import CondaDependencies myenv = CondaDependencies.create(pip_packages=["numpy","onnxruntime","azureml-core", "azureml-defaults", "tensorflow", "wget", "pytorch_pretrained_bert"]) with open("myenv.yml","w") as f: f.write(myenv.serialize_to_string()) ``` We're all set! Let's get our model chugging. ## Step 2.4 - Deploy Model as Webservice on Azure Container Instance ``` from azureml.core.webservice import AciWebservice from azureml.core.model import InferenceConfig from azureml.core.environment import Environment myenv = Environment.from_conda_specification(name="myenv", file_path="myenv.yml") inference_config = InferenceConfig(entry_script="score.py", environment=myenv) aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, memory_gb = 4, tags = {'demo': 'onnx'}, description = 'web service for Bert-squad-large-uncased ONNX model') ``` The following cell will likely take a few minutes to run as well. ``` from azureml.core.webservice import Webservice from random import randint aci_service_name = 'onnx-bert-squad-large-uncased-'+str(randint(0,100)) print("Service", aci_service_name) aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig) aci_service.wait_for_deployment(True) print(aci_service.state) ``` In case the deployment fails, you can check the logs. Make sure to delete your aci_service before trying again. ``` if aci_service.state != 'Healthy': # run this command for debugging. print(aci_service.get_logs()) aci_service.delete() ``` ## Success! If you've made it this far, you've deployed a working web service that does image classification using an ONNX model. You can get the URL for the webservice with the code below. ``` print(aci_service.scoring_uri) ``` ## Step 2.5 - Inference Bert Model using our WebService **Input**: Context paragraph and questions as formatted in `inputs.json` **Task**: For each question about the context paragraph, the model predicts a start and an end token from the paragraph that most likely answers the questions. **Output**: The best answer for each question. ``` # Use the inputs from step 2.2 print("========= INPUT DATA =========") print(json.dumps(inputs_json, indent=2)) azure_result = aci_service.run(json.dumps(inputs_json)) print("\n") print("========= RESULT =========") print(json.dumps(azure_result, indent=2)) res = azure_result['result'] inference_time = np.round(azure_result['total_time'] * 1000, 2) time_per_item = np.round(azure_result['time_per_item'] * 1000, 2) print('========================================') print('Final predictions are: ') for key in res: print("Question: ", inputs_json['data'][0]['paragraphs'][0]['qas'][int(key) - 1]['question']) print("Best Answer: ", res[key]) print() print('========================================') print('Inference time: ' + str(inference_time) + " ms") print('Average inference time for each question: ' + str(time_per_item) + " ms") print('========================================') ``` When you are eventually done using the web service, remember to delete it. ``` aci_service.delete() ```
github_jupyter
``` import numpy as np import pandas as pd import re, nltk, spacy, gensim import en_core_web_sm from tqdm import tqdm # Sklearn from sklearn.decomposition import LatentDirichletAllocation, TruncatedSVD, NMF from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import GridSearchCV from pprint import pprint from sklearn.datasets import fetch_20newsgroups from sklearn.metrics import silhouette_score # Plotting tools import pyLDAvis import pyLDAvis.sklearn import matplotlib.pyplot as plt %matplotlib inline nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner']) newsgroups_data = fetch_20newsgroups() data = pd.DataFrame() data['content'] = newsgroups_data.data[:1000] # take only first 1000 texts data['label'] = newsgroups_data.target[:1000] newsgroups_data.target_names data.head(3) # Convert to list texts = data.content.values.tolist() # Remove Emails texts = [re.sub('\S*@\S*\s?', '', sent) for sent in texts] # Remove new line characters texts = [re.sub('\s+', ' ', sent) for sent in texts] # Remove distracting single quotes texts = [re.sub("\'", "", sent) for sent in texts] pprint(texts[:1]) def sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations data_words = list(sent_to_words(texts)) print(data_words[:1]) def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" texts_out = [] for sent in texts: doc = nlp(" ".join(sent)) texts_out.append(" ".join([token.lemma_ if token.lemma_ not in ['-PRON-'] else '' for token in doc if token.pos_ in allowed_postags])) return texts_out # Initialize spacy 'en' model, keeping only tagger component (for efficiency) # Run in terminal: python3 -m spacy download en # Do lemmatization keeping only Noun, Adj, Verb, Adverb data_lemmatized = lemmatization(data_words, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']) print(data_lemmatized[:2]) def print_top_words(model, feature_names, n_top_words, print_topics=True): all_top_words = [] for topic_idx, topic in enumerate(model.components_): message = "Topic #%d: " % topic_idx message += " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) if print_topics: print(message) all_top_words.append([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) return all_top_words def coherence_score(tf,vocabulary,all_top_words): totalcnt = len(all_top_words) tf = tf > 0 total = 0 count = 0 for i, allwords in enumerate(all_top_words): for word1 in allwords: for word2 in allwords: if word1 != word2: ind1 = vocabulary[word1] ind2 = vocabulary[word2] #print (ind1,ind2) total += np.log((np.matmul(np.array(tf[:,ind1]).ravel(),np.array(tf[:,ind2]).ravel()) + 1)/np.sum(tf[:,ind2])) count += 1 return total/count vectorizer = CountVectorizer(max_df=0.7, min_df=2, max_features=50000, stop_words='english') countvector = vectorizer.fit_transform(data_lemmatized) countvector = countvector.todense() vocabulary = dict(zip(vectorizer.get_feature_names(),np.arange(countvector.shape[1]))) print (countvector.shape) n_topics = 10 nmf = NMF(n_components=n_topics, random_state=123, alpha=.1, l1_ratio=.5).fit(countvector) topic_words = print_top_words(nmf, tfidf_vectorizer.get_feature_names(), n_top_words=5) print (coherence_score(countvector,vocabulary,topic_words)) top_topics = nmf.transform(countvector).argmax(axis=1) print (silhouette_score(countvector,top_topics)) lda = LatentDirichletAllocation(n_components=n_topics, max_iter=50, learning_method='online', learning_offset=50., random_state=0) lda.fit(countvector) topic_words = print_top_words(lda, tfidf_vectorizer.get_feature_names(), n_top_words=5) print (coherence_score(countvector,vocabulary,topic_words)) lda.perplexity(countvector) top_topics = lda.transform(countvector).argmax(axis=1) print (silhouette_score(countvector,top_topics)) nmf_coh_scores, nmf_sil_scores, lda_coh_scores, lda_sil_scores, lda_perplexity_scores = [], [], [], [], [] for numtopic in tqdm([10,20,50,75,100]): nmf = NMF(n_components=numtopic, random_state=123, alpha=.1, l1_ratio=.5).fit(countvector) topic_words = print_top_words(nmf, tfidf_vectorizer.get_feature_names(), n_top_words=5, print_topics=False) coh_nmf = coherence_score(countvector,vocabulary,topic_words) top_topics = nmf.transform(countvector).argmax(axis=1) sil_nmf = silhouette_score(countvector,top_topics) lda = LatentDirichletAllocation(n_components=numtopic, max_iter=50, learning_method='online', learning_offset=50., random_state=0) lda.fit(countvector) topic_words = print_top_words(lda, tfidf_vectorizer.get_feature_names(), n_top_words=5, print_topics=False) coh_lda = coherence_score(countvector,vocabulary,topic_words) top_topics = lda.transform(countvector).argmax(axis=1) sil_lda = silhouette_score(countvector,top_topics) nmf_coh_scores.append(coh_nmf) nmf_sil_scores.append(sil_nmf) lda_coh_scores.append(coh_lda) lda_sil_scores.append(sil_lda) lda_perplexity_scores.append(lda.perplexity(countvector)) plt.figure(figsize=(12, 8)) plt.plot([10,20,50,75,100], nmf_coh_scores, label='NMF') plt.plot([10,20,50,75,100], lda_coh_scores, label='LDA') plt.title("Coherence Scores") plt.xlabel("Num Topics") plt.ylabel("UMass Coh Scores") plt.legend(title='Model', loc='best') plt.show() plt.figure(figsize=(12, 8)) plt.plot([10,20,50,75,100], nmf_sil_scores, label='NMF') plt.plot([10,20,50,75,100], lda_sil_scores, label='LDA') plt.title("Silhouette Scores") plt.xlabel("Num Topics") plt.ylabel("Silhouette Score") plt.legend(title='Model', loc='best') plt.show() plt.figure(figsize=(12, 8)) plt.plot([10,20,50,75,100], lda_perplexity_scores) plt.title("Perplexity Scores") plt.xlabel("Num Topics") plt.ylabel("Perplexity Score") plt.show() nmf_sil_scores lda_sil_scores lda_perplexity_scores ```
github_jupyter
``` import numpy as np import cv2 # read image img = cv2.imread('sample.jpg', 0)# IMREAD_GRAYSCALE, IMREAD_COLOR %matplotlib inline from matplotlib import pyplot as plt plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ``` # 1. “亮点”缺陷检测 Detect part of defects by pre-process ``` equ = cv2.equalizeHist(img)# Histograms Equalization ret2,img_th2 = cv2.threshold(img,150,255,cv2.THRESH_BINARY) _, contours, _ = cv2.findContours(img_th2.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) im = cv2.imread('sample.jpg', cv2.IMREAD_COLOR)# IMREAD_GRAYSCALE, IMREAD_COLOR cv2.drawContours(im,contours,-1,(255,0,0),5) %matplotlib inline from matplotlib import pyplot as plt width = 15 height = 10 plt.figure(figsize=(width, height)) plt.subplot(2, 2, 1) plt.title('original') plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2, 2, 2) plt.title('hist equlize') plt.imshow(equ, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2, 2, 3) plt.title('img th2') plt.imshow(img_th2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2, 2, 4) plt.title('defect-1') plt.imshow(im, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ``` # 2. “阴影点”缺陷检测 Detect others by removing part of shadowimage ``` # read image img2 = cv2.imread('sample_2.jpg', 0)# IMREAD_GRAYSCALE, IMREAD_COLOR # average blur2 = cv2.blur(img2,(5,5)) %matplotlib inline from matplotlib import pyplot as plt width = 15 height = 10 plt.figure(figsize=(width, height)) plt.subplot(1, 2, 1) plt.title('original') plt.imshow(img2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(1, 2, 2) plt.title('average') plt.imshow(blur2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() equ2 = cv2.equalizeHist(blur2)# Histograms Equalization ret2,img2_th2 = cv2.threshold(equ2,100,255,cv2.THRESH_BINARY) plt.imshow(img2_th2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() # revert color img2_th2_rvt = cv2.bitwise_not(img2_th2) # erode kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(6, 6)) dilate2 = cv2.dilate(img2_th2_rvt, kernel) eroded2 = cv2.erode(dilate2,kernel) %matplotlib inline from matplotlib import pyplot as plt width = 15 height = 10 plt.figure(figsize=(width, height)) plt.subplot(1, 2, 1) plt.title('rvt') plt.imshow(img2_th2_rvt, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(1, 2, 2) plt.title('erode') plt.imshow(eroded2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() _, contours, _ = cv2.findContours(eroded2.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) selected_contours = [] for c in contours: area = cv2.contourArea(c) perimeter = cv2.arcLength(c, True)# 周长 if(area>620 and perimeter<1000 and area/perimeter>5): selected_contours.append(c) print('area={0}, perimeter={1}'.format(area, perimeter)) len(selected_contours) im2 = cv2.imread('sample_2.jpg', cv2.IMREAD_COLOR)# IMREAD_GRAYSCALE, IMREAD_COLOR cv2.drawContours(im2,selected_contours,-1,(255,0,0),5) width = 15 height = 10 plt.figure(figsize=(width, height)) plt.imshow(im2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() %matplotlib inline from matplotlib import pyplot as plt width = 15 height = 10 plt.figure(figsize=(width, height)) plt.subplot(2, 4, 1) plt.title('original') plt.imshow(img2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2, 4, 2) plt.title('average') plt.imshow(blur2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,3) plt.title('equ2') plt.imshow(equ2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,4) plt.title('th2') plt.imshow(img2_th2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,5) plt.title('revert') plt.imshow(img2_th2_rvt, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,6) plt.title('dilate') plt.imshow(dilate2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,7) plt.title('eroded') plt.imshow(eroded2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(2,4,8) plt.title('result') plt.imshow(im2, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ```
github_jupyter
# Object-based filtering of pixel classifications <img align="right" src="../figs/DE_Africa_Logo_Stacked_RGB_small.jpg"> ## Background Geographic Object-Based Image Analysis (GEOBIA), which aims to group pixels together into meaningful image-objects. There are two advantages to a GEOBIA worklow; one, we can reduce the 'salt and pepper' effect typical of classifying pixels; and two, we can increase the computational efficiency of our workflow by grouping pixels into fewer, larger, but meaningful objects. A review of the emerging trends in GEOBIA can be found in [Chen et al. (2017)](https://www.tandfonline.com/doi/abs/10.1080/15481603.2018.1426092). ## Description In this notebook, we take the pixel-based classifications generated in the `4_Predict.ipynb` notebook, and filter the classifications by image-objects. To do this, we first need to conduct image segmentation using the function `rsgislib.segmentation.runShepherdSegmentation`. This image sgementation algorithm is fast and scalable. The image segmentation is conducted on the `NDVI_S1` and `NDVI_S2` layers (NDVI season 1, NDVI season 2). To filter the pixel observations, we assign to each segment the majority (mode) pixel classification. 1. Load the NDVI_S1 and NDVI_S2 layers 2. Convert the NDVI layers to a .kea file format (a requirement for RSGSISLIB) 3. Run the image segmentation 4. Calculate the mode statistic for each segment 5. Write the new object-based classification to disk as COG *** ## Getting started To run this analysis, run all the cells in the notebook, starting with the "Load packages" cell. ### Load Packages ``` import os import sys import gdal import shutil import xarray as xr import numpy as np import geopandas as gpd import subprocess as sp from datacube.utils.cog import write_cog from rsgislib.segmentation import segutils from scipy.ndimage.measurements import _stats sys.path.append('../../Scripts') from deafrica_classificationtools import HiddenPrints ``` # Analysis Parameters ``` test_shapefile = 'data/imagesegtiles.shp' results = 'results/classifications/predicted/20210401/' model_type='gm_mads_two_seasons_20210401' min_seg_size=50 #in number of pixels ``` ### Open testing tile shapefile ``` gdf = gpd.read_file(test_shapefile) ``` ## Image segmentation ``` %%time for g_id in gdf['title'].values: print('working on grid: ' + g_id) #store temp files somewhere directory=results+'tmp_'+g_id if not os.path.exists(directory): os.mkdir(directory) tmp='tmp_'+g_id+'/' #inputs to image seg tiff_to_segment = results+'ndvi/Eastern_tile_'+g_id+'_NDVI.tif' kea_file = results+'ndvi/Eastern_tile_'+g_id+'_NDVI.kea' segmented_kea_file = results+'ndvi/Eastern_tile_'+g_id+'_segmented.kea' #convert tiff to kea gdal.Translate(destName=kea_file, srcDS=tiff_to_segment, format='KEA', outputSRS='EPSG:6933') #run image seg print(' image segmentation...') with HiddenPrints(): segutils.runShepherdSegmentation(inputImg=kea_file, outputClumps=segmented_kea_file, tmpath=results+tmp, numClusters=60, minPxls=min_seg_size) #open segments, and predictions segments=xr.open_rasterio(segmented_kea_file).squeeze().values t = results+ 'tiles/Eastern_tile_'+g_id+'_prediction_pixel_'+model_type+'.tif' pred = xr.open_rasterio(t).squeeze().drop_vars('band') #calculate mode print(' calculating mode...') count, _sum =_stats(pred, labels=segments, index=segments) mode = _sum > (count/2) mode = xr.DataArray(mode, coords=pred.coords, dims=pred.dims, attrs=pred.attrs).astype(np.int16) #write to disk print(' writing to disk...') write_cog(mode, results+ 'segmented/Eastern_tile_'+g_id+'_prediction_filtered_'+model_type+'.tif', overwrite=True) #remove the tmp folder shutil.rmtree(results+tmp) os.remove(kea_file) os.remove(segmented_kea_file) os.remove(tiff_to_segment) mode.plot(size=12); pred.plot(size=12) ``` ## Next steps To continue working through the notebooks in this `Eastern Africa Cropland Mask` workflow, go to the next notebook `6_Accuracy_assessment.ipynb`. 1. [Extracting_training_data](1_Extracting_training_data.ipynb) 2. [Inspect_training_data](2_Inspect_training_data.ipynb) 3. [Train_fit_evaluate_classifier](3_Train_fit_evaluate_classifier.ipynb) 4. [Predict](4_Predict.ipynb) 5. **Object-based_filtering (this notebook)** 6. [Accuracy_assessment](6_Accuracy_assessment.ipynb) *** ## Additional information **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks). **Last modified:** Dec 2020
github_jupyter
<a href="https://colab.research.google.com/github/AI4Finance-LLC/FinRL/blob/master/FinRL_ensemble_stock_trading_ICAIF_2020.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Deep Reinforcement Learning for Stock Trading from Scratch: Multiple Stock Trading Using Ensemble Strategy Tutorials to use OpenAI DRL to trade multiple stocks using ensemble strategy in one Jupyter Notebook | Presented at ICAIF 2020 * This notebook is the reimplementation of our paper: Deep Reinforcement Learning for Automated Stock Trading: An Ensemble Strategy, using FinRL. * Check out medium blog for detailed explanations: https://medium.com/@ai4finance/deep-reinforcement-learning-for-automated-stock-trading-f1dad0126a02 * Please report any issues to our Github: https://github.com/AI4Finance-LLC/FinRL-Library/issues * **Pytorch Version** # Content * [1. Problem Definition](#0) * [2. Getting Started - Load Python packages](#1) * [2.1. Install Packages](#1.1) * [2.2. Check Additional Packages](#1.2) * [2.3. Import Packages](#1.3) * [2.4. Create Folders](#1.4) * [3. Download Data](#2) * [4. Preprocess Data](#3) * [4.1. Technical Indicators](#3.1) * [4.2. Perform Feature Engineering](#3.2) * [5.Build Environment](#4) * [5.1. Training & Trade Data Split](#4.1) * [5.2. User-defined Environment](#4.2) * [5.3. Initialize Environment](#4.3) * [6.Implement DRL Algorithms](#5) * [7.Backtesting Performance](#6) * [7.1. BackTestStats](#6.1) * [7.2. BackTestPlot](#6.2) * [7.3. Baseline Stats](#6.3) * [7.3. Compare to Stock Market Index](#6.4) <a id='0'></a> # Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem. The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are: * Action: The action space describes the allowed actions that the agent interacts with the environment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 represent selling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We use an action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively * Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfolio values at state s′ and s, respectively * State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, so our trading agent observes many different features to better learn in an interactive environment. * Environment: Dow 30 consituents The data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. <a id='1'></a> # Part 2. Getting Started- Load Python Packages <a id='1.1'></a> ## 2.1. Install all the packages through FinRL library ``` # ## install finrl library #!pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git ``` <a id='1.2'></a> ## 2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API * pandas * numpy * matplotlib * stockstats * OpenAI gym * stable-baselines * tensorflow * pyfolio <a id='1.3'></a> ## 2.3. Import Packages ``` import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt # matplotlib.use('Agg') from datetime import datetime, timedelta %matplotlib inline from finrl.apps import config from finrl.neo_finrl.preprocessor.yahoodownloader import YahooDownloader from finrl.neo_finrl.preprocessor.preprocessors import FeatureEngineer, data_split from finrl.neo_finrl.env_stock_trading.env_stocktrading import StockTradingEnv from finrl.drl_agents.stablebaselines3.models import DRLAgent,DRLEnsembleAgent from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline from pprint import pprint import sys sys.path.append("../FinRL-Library") import itertools ``` <a id='1.4'></a> ## 2.4. Create Folders ``` import os if not os.path.exists("./" + config.DATA_SAVE_DIR): os.makedirs("./" + config.DATA_SAVE_DIR) if not os.path.exists("./" + config.TRAINED_MODEL_DIR): os.makedirs("./" + config.TRAINED_MODEL_DIR) if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR): os.makedirs("./" + config.TENSORBOARD_LOG_DIR) if not os.path.exists("./" + config.RESULTS_DIR): os.makedirs("./" + config.RESULTS_DIR) import yfinance as yf data_prefix = [f"{config.DOW_30_TICKER}", f"{config.nas_choosen}", f"{config.sp_choosen}"] path_mark = ["dow", "nas", "sp"] choose_number = 0 #注意更改ticker_list config.START_DATE config.END_DATE print(data_prefix[choose_number]) time_current = datetime.now() + timedelta(hours=8) time_current = time_current.strftime("%Y-%m-%d_%H:%M") print(f"time_current ====={time_current}") ``` <a id='2'></a> # Part 3. Download Data Yahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free. * FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API * Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). ----- class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API ``` #ticker_list = [] #ticker_list = [ticks[i] for i in index] #getattr(ticker_list, data_prefix[choose_number]) # 缓存数据,如果日期或者股票列表发生变化,需要删除该缓存文件重新下载 SAVE_PATH = f"./datasets/{path_mark[choose_number]}.csv" if os.path.exists(SAVE_PATH): df = pd.read_csv(SAVE_PATH) else: #注意更改ticker_list df = YahooDownloader( config.START_DATE, #'2000-01-01', config.END_DATE, # 2021-01-01,预计将改日期改为'2021-07-03'(今日日期) ticker_list=config.DOW_30_TICKER#config.DOW_30_TICKER, config.nas_choosen, config.sp_choosen ).fetch_data() df.to_csv(SAVE_PATH) df.head() df.tail() df.shape df.sort_values(['date','tic']).head() ``` # Part 4: Preprocess Data Data preprocessing is a crucial step for training a high quality machine learning model. We need to check for missing data and do feature engineering in order to convert the data into a model-ready state. * Add technical indicators. In practical trading, various information needs to be taken into account, for example the historical stock prices, current holding shares, technical indicators, etc. In this article, we demonstrate two trend-following technical indicators: MACD and RSI. * Add turbulence index. Risk-aversion reflects whether an investor will choose to preserve the capital. It also influences one's trading strategy when facing different market volatility level. To control the risk in a worst-case scenario, such as financial crisis of 2007–2008, FinRL employs the financial turbulence index that measures extreme asset price fluctuation. ``` tech_indicators = ['macd', 'rsi_30', 'cci_30', 'dx_30'] fe = FeatureEngineer( use_technical_indicator=True, tech_indicator_list = tech_indicators, use_turbulence=True, user_defined_feature = False) csv_name_func_processed = lambda time: f"./datasets/ensemble_{path_mark[choose_number]}_{time}_processed.csv" SAVE_PATH = csv_name_func_processed(time_current) if os.path.exists(SAVE_PATH): processed = pd.read_csv(SAVE_PATH) else: processed = fe.preprocess_data(df) processed.to_csv(SAVE_PATH) list_ticker = processed["tic"].unique().tolist() list_date = list(pd.date_range(processed['date'].min(),processed['date'].max()).astype(str)) combination = list(itertools.product(list_date,list_ticker)) processed_full = pd.DataFrame(combination,columns=["date","tic"]).merge(processed,on=["date","tic"],how="left") processed_full = processed_full[processed_full['date'].isin(processed['date'])] processed_full = processed_full.sort_values(['date','tic']) processed_full = processed_full.fillna(0) processed_full.sample(5) ``` <a id='4'></a> # Part 5. Design Environment Considering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds. Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation. The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. ``` #train = data_split(processed_full, '2009-01-01','2019-01-01') #trade = data_split(processed_full, '2019-01-01','2021-01-01') #print(len(train)) #print(len(trade)) stock_dimension = len(processed_full.tic.unique()) state_space = 1 + 2*stock_dimension + len(tech_indicators)*stock_dimension print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}") env_kwargs = { "hmax": 100, "initial_amount": 1000000, "buy_cost_pct": 0.001, "sell_cost_pct": 0.001, "state_space": state_space, "stock_dim": stock_dimension, "tech_indicator_list": tech_indicators, "action_space": stock_dimension, "reward_scaling": 1e-4, "print_verbosity":5 } ``` <a id='5'></a> # Part 6: Implement DRL Algorithms * The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups. * FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG, Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users to design their own DRL algorithms by adapting these DRL algorithms. * In this notebook, we are training and validating 3 agents (A2C, PPO, DDPG) using Rolling-window Ensemble Method ([reference code](https://github.com/AI4Finance-LLC/Deep-Reinforcement-Learning-for-Automated-Stock-Trading-Ensemble-Strategy-ICAIF-2020/blob/80415db8fa7b2179df6bd7e81ce4fe8dbf913806/model/models.py#L92)) ``` rebalance_window = 63 # rebalance_window is the number of days to retrain the model validation_window = 63 # validation_window is the number of days to do validation and trading (e.g. if validation_window=63, then both validation and trading period will be 63 days) """ train_start = '2009-01-01' train_end = "2016-10-03" val_test_start = "2016-10-03" val_test_end = "2021-09-18" """ train_start = "2009-01-01" train_end = "2015-12-31" val_test_start = "2015-12-31" val_test_end = "2021-05-03" ensemble_agent = DRLEnsembleAgent(df=processed_full, train_period=(train_start,train_end), val_test_period=(val_test_start,val_test_end), rebalance_window=rebalance_window, validation_window=validation_window, **env_kwargs) A2C_model_kwargs = { 'n_steps': 5, 'ent_coef': 0.01, 'learning_rate': 0.0005 } PPO_model_kwargs = { "ent_coef":0.01, "n_steps": 2048, "learning_rate": 0.00025, "batch_size": 128 } DDPG_model_kwargs = { "action_noise":"ornstein_uhlenbeck", "buffer_size": 50_000, "learning_rate": 0.000005, "batch_size": 128 } timesteps_dict = {'a2c' : 1_000, 'ppo' : 1_000, 'ddpg' : 1_000 } df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict) df_summary ``` <a id='6'></a> # Part 7: Backtest Our Strategy Backtesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. ``` unique_trade_date = processed_full[(processed_full.date > val_test_start)&(processed_full.date <= val_test_end)].date.unique() import functools def compare(A, B): # 名字可以随便取,不一定得是“compare" return -1 if int(A.split("_")[-1][:-4])<int(B.split("_")[-1][:-4]) else 1 from typing import List with open("paths.txt") as f: paths: List[str] = f.readlines() paths = [path.strip().split(" ")[-1] for path in paths] paths.sort(key=functools.cmp_to_key(compare)) #paths.sort() #print(paths) df_account_value=pd.DataFrame() for i in range(len(df_summary)): iter = df_summary.iloc[i]["Iter"] al = df_summary.iloc[i]["Model Used"] path = f"results/account_value_validation_{al}_{iter}.csv" #print(path, os.path.exists(path)) df_tmp = pd.read_csv(path) df_account_value = df_account_value.append(df_tmp,ignore_index=True) df_account_value df_account_value.tail() df_account_value.to_csv("results/account_value_all.csv", index=False) df_account_value.head() %matplotlib inline df_account_value.account_value.plot() ``` <a id='6.1'></a> ## 7.1 BackTestStats pass in df_account_value, this information is stored in env class ``` print("==============Get Backtest Results===========") now = datetime.now().strftime('%Y%m%d-%Hh%M') perf_stats_all = backtest_stats(account_value=df_account_value) perf_stats_all = pd.DataFrame(perf_stats_all) #baseline stats print("==============Get Baseline Stats===========") baseline_df = get_baseline( ticker="^GSPC", start = df_account_value.loc[0,'date'], end = df_account_value.loc[len(df_account_value)-1,'date']) stats = backtest_stats(baseline_df, value_col_name = 'close') ``` <a id='6.2'></a> ## 7.2 BackTestPlot ``` print("==============Compare to DJIA===========") import pandas as pd %matplotlib inline # S&P 500: ^GSPC # Dow Jones Index: ^DJI # NASDAQ 100: ^NDX #df_account_value = pd.read_csv("/mnt/wanyao/guiyi/hhf/RL-FIN/datasets/ensemble_2021-09-06_19:36_account_value.csv") backtest_plot(df_account_value, baseline_ticker = '^DJI', baseline_start = df_account_value.loc[0,'date'], baseline_end = df_account_value.loc[len(df_account_value)-1,'date']) ```
github_jupyter
# Text Classification using LSTM This Code Template is for Text Classification using Long short-term memory in python <img src="https://cdn.blobcity.com/assets/gpu_required.png" height="25" style="margin-bottom:-15px" /> ### Required Packages ``` !pip install tensorflow !pip install nltk import pandas as pd import tensorflow as tf from tensorflow.keras.layers import Embedding from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.preprocessing.text import one_hot from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import Dense import nltk import re from nltk.corpus import stopwords import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix pip install tensorflow==2.1.0 ``` ### Initialization Filepath of CSV file ``` df=pd.read_csv('/content/train.csv') ``` ### Data Fetching Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. ``` df.head() ###Drop Nan Values df=df.dropna() ``` Target variable for prediction. ``` target='' ``` Text column containing all the text data ``` text="" tf.__version__ ### Vocabulary size voc_size=5000 nltk.download('stopwords') ``` ### Data Preprocessing Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. ``` ### Dataset Preprocessing from nltk.stem.porter import PorterStemmer ps = PorterStemmer() corpus = [] for i in range(0, len(df)): review = re.sub('[^a-zA-Z]', ' ', df[text][i]) review = review.lower() review = review.split() review = [ps.stem(word) for word in review if not word in stopwords.words('english')] review = ' '.join(review) corpus.append(review) corpus[1:10] onehot_repr=[one_hot(words,voc_size)for words in corpus] onehot_repr ``` ### Embedding Representation ``` sent_length=20 embedded_docs=pad_sequences(onehot_repr,padding='pre',maxlen=sent_length) print(embedded_docs) embedded_docs[0] ``` ### Model #LSTM The LSTM model will learn a function that maps a sequence of past observations as input to an output observation. As such, the sequence of observations must be transformed into multiple examples from which the LSTM can learn. Refer [API](https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21) for the parameters ``` ## Creating model embedding_vector_features=40 model=Sequential() model.add(Embedding(voc_size,embedding_vector_features,input_length=sent_length)) model.add(LSTM(100)) model.add(Dense(1,activation='sigmoid')) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) print(model.summary()) len(embedded_docs),y.shape X=np.array(embedded_docs) Y=df[target] X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=42) ``` ### Model Training ``` ### Finally Training model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=10,batch_size=64) ``` ### Performance Metrics And Accuracy ``` y_pred=model.predict_classes(X_test) confusion_matrix(y_test,y_pred) ``` ## Model Accuracy ``` accuracy_score(y_test,y_pred) ``` #### Creator: Ageer Harikrishna , Github: [Profile](https://github.com/ageerHarikrishna)
github_jupyter
# Deep learning models for age prediction on EEG data This notebook uses deep learning methods to predict the age of infants using EEG data. The EEG data is preprocessed as shown in the notebook 'Deep learning EEG_dataset preprocessing raw'. ``` import sys, os, fnmatch, csv import numpy as np import pandas as pd import matplotlib.pyplot as plt sys.path.insert(0, os.path.dirname(os.getcwd())) from config import PATH_DATA_PROCESSED_DL_REDUCED, PATH_MODELS ``` ## Load preprocessed data (reduced) The data can be found in 'PATH_DATA_PROCESSED_DL_REDUCED'. This is a single folder with all the data and metadata. The EEG data is in the .zarr files and the metadata is in .csv files. The .zarr files are divided in chunks of 1-second epochs (average of 10 original EEG epochs) from the same subject and the metadata contains the information like the subject's identification code and age. The notebook "Deep learning EEG_DL dataset_reduction.ipynb" takes care of reducing the original processed data set to the reduced size. Generator loads all the data into memory. The generators generate averaged epochs on the fly. The data is split in train/validation/test and no subject can be found in more than one of these splits. Originally, we used the original EEG epochs and averaged 30 of them into a new EEG epoch in the generator object. This had two disadvantages: (1) many files had to be openened and closed during the training process, and (2) the data set was too large to fit into memory. Therefore, we decided to randomly create chunks of 10 EEG epochs and average those for each subject/age group. This reduced the data set from ±145GB to ±14.5 GB. We now use these already averaged EEG epochs as "original" epcohs, and average those another 3-5 times to reduce noise. We have also experimented with averaging all EEG epochs of a subject at a specific age into a single EEG epoch, but performance was lower, most likely because this reduced the size of the data set a lot. ``` %%time # Load all the metadata from sklearn.model_selection import train_test_split # Step 1: Get all the files in the output folder file_names = os.listdir(PATH_DATA_PROCESSED_DL_REDUCED) # Step 2: Get the full paths of the files (without extensions) files = [os.path.splitext(os.path.join(PATH_DATA_PROCESSED_DL_REDUCED, file_name))[0] for file_name in fnmatch.filter(file_names, "*.zarr")] # Step 3: Load all the metadata frames = [] for idx, feature_file in enumerate(files): df_metadata = pd.read_csv(feature_file + ".csv") frames.append(df_metadata) df_metadata = pd.concat(frames) # Step 4: Add missing age information based on the age group the subject is in df_metadata['age_months'].fillna(df_metadata['age_group'], inplace=True) df_metadata['age_days'].fillna(df_metadata['age_group']*30, inplace=True) df_metadata['age_years'].fillna(df_metadata['age_group']/12, inplace=True) # Step 5: List all the unique subject IDs subject_ids = sorted(list(set(df_metadata["code"].tolist()))) from sklearn.model_selection import train_test_split IDs_train, IDs_temp = train_test_split(subject_ids, test_size=0.3, random_state=42) IDs_test, IDs_val = train_test_split(IDs_temp, test_size=0.5, random_state=42) df_metadata from dataset_generator_reduced import DataGeneratorReduced # # Import libraries # from tensorflow.keras.utils import Sequence # import numpy as np # import zarr # import os # class DataGeneratorReduced(Sequence): # """Generates data for loading (preprocessed) EEG timeseries data. # Create batches for training or prediction from given folders and filenames. # """ # def __init__(self, # list_IDs, # BASE_PATH, # metadata, # gaussian_noise=0.0, # n_average = 3, # batch_size=10, # iter_per_epoch = 1, # n_timepoints = 501, # n_channels=30, # shuffle=True, # warnings=False): # """Initialization # Args: # -------- # list_IDs: # list of all filename/label ids to use in the generator # metadata: # DataFrame containing all the metadata. # n_average: int # Number of EEG/time series epochs to average. # batch_size: # batch size at each iteration # iter_per_epoch: int # Number of iterations over all data points within one epoch. # n_timepoints: int # Timepoint dimension of data. # n_channels: # number of input channels # shuffle: # True to shuffle label indexes after every epoch # """ # self.list_IDs = list_IDs # self.BASE_PATH = BASE_PATH # self.metadata = metadata # self.metadata_temp = None # self.gaussian_noise = gaussian_noise # self.n_average = n_average # self.batch_size = batch_size # self.iter_per_epoch = iter_per_epoch # self.n_timepoints = n_timepoints # self.n_channels = n_channels # self.shuffle = shuffle # self.warnings = warnings # self.on_epoch_end() # # Store all data in here # self.X_data_all = [] # self.y_data_all = [] # self.load_all_data() # def __len__(self): # """Denotes the number of batches per epoch # return: number of batches per epoch # """ # return int(np.floor(len(self.metadata_temp) / self.batch_size)) # def __getitem__(self, index): # """Generate one batch of data # Args: # -------- # index: int # index of the batch # return: X and y when fitting. X only when predicting # """ # # Generate indexes of the batch # indexes = self.indexes[index * self.batch_size:((index + 1) * self.batch_size)] # # Generate data # X, y = self.generate_data(indexes) # return X, y # def load_all_data(self): # """ Loads all data into memory. """ # for i, metadata_file in self.metadata_temp.iterrows(): # filename = os.path.join(self.BASE_PATH, metadata_file['cnt_file'] + '.zarr') # X_data = np.zeros((0, self.n_channels, self.n_timepoints)) # data_signal = self.load_signal(filename) # if (len(data_signal) == 0) and self.warnings: # print(f"EMPTY SIGNAL, filename: {filename}") # X_data = np.concatenate((X_data, data_signal), axis=0) # self.X_data_all.append(X_data) # self.y_data_all.append(metadata_file['age_months']) # def on_epoch_end(self): # """Updates indexes after each epoch.""" # # Create new metadata DataFrame with only the current subject IDs # if self.metadata_temp is None: # self.metadata_temp = self.metadata[self.metadata['code'].isin(self.list_IDs)].reset_index(drop=True) # idx_base = np.arange(len(self.metadata_temp)) # idx_epoch = np.tile(idx_base, self.iter_per_epoch) # self.indexes = idx_epoch # if self.shuffle == True: # np.random.shuffle(self.indexes) # def generate_data(self, indexes): # """Generates data containing batch_size averaged time series. # Args: # ------- # list_IDs_temp: list # list of label ids to load # return: batch of averaged time series # """ # X_data = np.zeros((0, self.n_channels, self.n_timepoints)) # y_data = [] # for index in indexes: # X = self.create_averaged_epoch(self.X_data_all[index]) # X_data = np.concatenate((X_data, X), axis=0) # y_data.append(self.y_data_all[index]) # return np.swapaxes(X_data,1,2), np.array(y_data).reshape((-1,1)) # def create_averaged_epoch(self, # data_signal): # """ # Function to create averages of self.n_average epochs. # Will create one averaged epoch per found unique label from self.n_average random epochs. # Args: # -------- # data_signal: numpy array # Data from one person as numpy array # """ # # Create new data collection: # X_data = np.zeros((0, self.n_channels, self.n_timepoints)) # num_epochs = len(data_signal) # if num_epochs >= self.n_average: # select = np.random.choice(num_epochs, self.n_average, replace=False) # signal_averaged = np.mean(data_signal[select,:,:], axis=0) # else: # if self.warnings: # print("Found only", num_epochs, " epochs and will take those!") # signal_averaged = np.mean(data_signal[:,:,:], axis=0) # X_data = np.concatenate([X_data, np.expand_dims(signal_averaged, axis=0)], axis=0) # if self.gaussian_noise != 0.0: # X_data += np.random.normal(0, self.gaussian_noise, X_data.shape) # return X_data # def load_signal(self, # filename): # """Load EEG signal from one person. # Args: # ------- # filename: str # filename... # return: loaded array # """ # return zarr.open(os.path.join(filename), mode='r') %%time # IDs_train = [152, 18, 11, 435, 617] # IDs_val = [180, 105, 19, 332] train_generator_noise = DataGeneratorReduced(list_IDs = IDs_train, BASE_PATH = PATH_DATA_PROCESSED_DL_REDUCED, metadata = df_metadata, n_average = 3, batch_size = 10, gaussian_noise=0.01, iter_per_epoch = 3, n_timepoints = 501, n_channels=30, shuffle=True) val_generator = DataGeneratorReduced(list_IDs = IDs_val, BASE_PATH = PATH_DATA_PROCESSED_DL_REDUCED, metadata = df_metadata, n_average = 3, batch_size = 10, n_timepoints = 501, iter_per_epoch = 3, n_channels=30, shuffle=True) ``` # Helper functions ``` import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, Input, Sequential from tensorflow.keras.layers import Bidirectional, LSTM, Dropout, BatchNormalization, Dense, Conv1D, LeakyReLU, AveragePooling1D, Flatten, Reshape, MaxPooling1D from tensorflow.keras.optimizers import Adam, Adadelta, SGD from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau from tensorflow.keras.metrics import RootMeanSquaredError, MeanAbsoluteError import time n_timesteps = 501 n_features = 30 n_outputs = 1 input_shape = (n_timesteps, n_features) ``` # Testing of different architectures Below we will test multiple different architectures, most of them as discussed in "Deep learning for time series classification: a review", by Ismail Fawaz et al (2019). Most of them are inspired again on other papers. Refer to the Ismail Fawaz paper for the original papers. 1. Fully-connected NN 2. CNN 3. ResNet 4. Encoder 5. Time-CNN Other architectures to test: 6. BLSTM-LSTM 7. InceptionTime # 1. Fully connected NN ``` def fully_connected_model(): """ Returns the fully connected model from Ismail Fawaz et al. (2019). """ input_layer = keras.layers.Input(input_shape) input_layer_flattened = keras.layers.Flatten()(input_layer) layer_1 = keras.layers.Dropout(0.1)(input_layer_flattened) layer_1 = keras.layers.Dense(500, activation='relu')(layer_1) layer_2 = keras.layers.Dropout(0.2)(layer_1) layer_2 = keras.layers.Dense(500, activation='relu')(layer_2) layer_3 = keras.layers.Dropout(0.2)(layer_2) layer_3 = keras.layers.Dense(500, activation='relu')(layer_3) output_layer = keras.layers.Dropout(0.3)(layer_3) output_layer = keras.layers.Dense(1)(output_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = fully_connected_model() optimizer = Adadelta(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # 01 seems to be incorrect (makes too many predictions, changed model) # Fully_connected_regressor_01: MSE, Adadelta, N_average=30, 5000 epochs, ES=1000, RLR=200, gaussian=0.01 # Fully_connected_regressor_02: MSE, Adadelta, N_average=30, 5000 epochs, ES=1000, RLR=200, gaussian=0.01 output_filename = 'Fully_connected_regressor_03' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=1000, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=200, min_lr=0.0001, verbose=1) %%time epochs = 5000 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer, earlystopper, reduce_lr]) ``` # 2. CNN ``` def cnn_model(): """ Returns the CNN (FCN) model from Ismail Fawaz et al. (2019). """ input_layer = keras.layers.Input(input_shape) conv1 = keras.layers.Conv1D(filters=128, kernel_size=8, padding='same')(input_layer) conv1 = keras.layers.BatchNormalization()(conv1) conv1 = keras.layers.Activation(activation='relu')(conv1) conv2 = keras.layers.Conv1D(filters=256, kernel_size=5, padding='same')(conv1) conv2 = keras.layers.BatchNormalization()(conv2) conv2 = keras.layers.Activation('relu')(conv2) conv3 = keras.layers.Conv1D(128, kernel_size=3, padding='same')(conv2) conv3 = keras.layers.BatchNormalization()(conv3) conv3 = keras.layers.Activation('relu')(conv3) gap_layer = keras.layers.GlobalAveragePooling1D()(conv3) output_layer = keras.layers.Dense(1)(gap_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = cnn_model() optimizer = Adam(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # CNN_regressor_01: MSE, Adam, N_average=30, 2000 epochs, ES=250, RLR=50, gaussian=0.01 output_filename = 'CNN_regressor_03' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=250, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=50, min_lr=0.0001, verbose=1) %%time epochs = 2000 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer, earlystopper, reduce_lr]) ``` # 3. ResNet ``` def resnet_model(): """ Returns the ResNet model from Ismail Fawaz et al. (2019). """ n_feature_maps = 64 input_layer = keras.layers.Input(input_shape) # BLOCK 1 conv_x = keras.layers.Conv1D(filters=n_feature_maps, kernel_size=8, padding='same')(input_layer) conv_x = keras.layers.BatchNormalization()(conv_x) conv_x = keras.layers.Activation('relu')(conv_x) conv_y = keras.layers.Conv1D(filters=n_feature_maps, kernel_size=5, padding='same')(conv_x) conv_y = keras.layers.BatchNormalization()(conv_y) conv_y = keras.layers.Activation('relu')(conv_y) conv_z = keras.layers.Conv1D(filters=n_feature_maps, kernel_size=3, padding='same')(conv_y) conv_z = keras.layers.BatchNormalization()(conv_z) # expand channels for the sum shortcut_y = keras.layers.Conv1D(filters=n_feature_maps, kernel_size=1, padding='same')(input_layer) shortcut_y = keras.layers.BatchNormalization()(shortcut_y) output_block_1 = keras.layers.add([shortcut_y, conv_z]) output_block_1 = keras.layers.Activation('relu')(output_block_1) # BLOCK 2 conv_x = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=8, padding='same')(output_block_1) conv_x = keras.layers.BatchNormalization()(conv_x) conv_x = keras.layers.Activation('relu')(conv_x) conv_y = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=5, padding='same')(conv_x) conv_y = keras.layers.BatchNormalization()(conv_y) conv_y = keras.layers.Activation('relu')(conv_y) conv_z = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=3, padding='same')(conv_y) conv_z = keras.layers.BatchNormalization()(conv_z) # expand channels for the sum shortcut_y = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=1, padding='same')(output_block_1) shortcut_y = keras.layers.BatchNormalization()(shortcut_y) output_block_2 = keras.layers.add([shortcut_y, conv_z]) output_block_2 = keras.layers.Activation('relu')(output_block_2) # BLOCK 3 conv_x = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=8, padding='same')(output_block_2) conv_x = keras.layers.BatchNormalization()(conv_x) conv_x = keras.layers.Activation('relu')(conv_x) conv_y = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=5, padding='same')(conv_x) conv_y = keras.layers.BatchNormalization()(conv_y) conv_y = keras.layers.Activation('relu')(conv_y) conv_z = keras.layers.Conv1D(filters=n_feature_maps * 2, kernel_size=3, padding='same')(conv_y) conv_z = keras.layers.BatchNormalization()(conv_z) # no need to expand channels because they are equal shortcut_y = keras.layers.BatchNormalization()(output_block_2) output_block_3 = keras.layers.add([shortcut_y, conv_z]) output_block_3 = keras.layers.Activation('relu')(output_block_3) # FINAL gap_layer = keras.layers.GlobalAveragePooling1D()(output_block_3) output_layer = keras.layers.Dense(1)(gap_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = resnet_model() optimizer = Adam(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # ResNet_regressor_01: MSE, Adam, N_average=30, 1500 epochs, ES=250, RLR=50, gaussian=0.01 output_filename = 'ResNet_regressor_02' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=250, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=50, min_lr=0.0001, verbose=1) %%time epochs = 1500 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer, earlystopper, reduce_lr]) ``` # 4. Encoder ``` import tensorflow_addons as tfa def encoder_model(): """ Returns the Encoder model from Ismail Fawaz et al. (2019). """ input_layer = keras.layers.Input(input_shape) # conv block -1 conv1 = keras.layers.Conv1D(filters=128,kernel_size=5,strides=1,padding='same')(input_layer) conv1 = tfa.layers.InstanceNormalization()(conv1) conv1 = keras.layers.PReLU(shared_axes=[1])(conv1) conv1 = keras.layers.Dropout(rate=0.2)(conv1) conv1 = keras.layers.MaxPooling1D(pool_size=2)(conv1) # conv block -2 conv2 = keras.layers.Conv1D(filters=256,kernel_size=11,strides=1,padding='same')(conv1) conv2 = tfa.layers.InstanceNormalization()(conv2) conv2 = keras.layers.PReLU(shared_axes=[1])(conv2) conv2 = keras.layers.Dropout(rate=0.2)(conv2) conv2 = keras.layers.MaxPooling1D(pool_size=2)(conv2) # conv block -3 conv3 = keras.layers.Conv1D(filters=512,kernel_size=21,strides=1,padding='same')(conv2) conv3 = tfa.layers.InstanceNormalization()(conv3) conv3 = keras.layers.PReLU(shared_axes=[1])(conv3) conv3 = keras.layers.Dropout(rate=0.2)(conv3) # split for attention attention_data = keras.layers.Lambda(lambda x: x[:,:,:256])(conv3) attention_softmax = keras.layers.Lambda(lambda x: x[:,:,256:])(conv3) # attention mechanism attention_softmax = keras.layers.Softmax()(attention_softmax) multiply_layer = keras.layers.Multiply()([attention_softmax,attention_data]) # last layer dense_layer = keras.layers.Dense(units=256,activation='sigmoid')(multiply_layer) dense_layer = tfa.layers.InstanceNormalization()(dense_layer) # output layer flatten_layer = keras.layers.Flatten()(dense_layer) output_layer = keras.layers.Dense(1)(flatten_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = encoder_model() optimizer = Adam(learning_rate=0.00001) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # Encoder_regressor_01: MSE, Adam, N_average=30, 1500 epochs, ES=250, RLR=50, gaussian=0.01 (LR = 0.0001, no reduction) output_filename = 'Encoder_regressor_02' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) %%time epochs = 100 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer]) ``` # 5. Time-CNN ``` # https://github.com/hfawaz/dl-4-tsc/blob/master/classifiers/cnn.py def timecnn_model(): """ Returns the Time-CNN model from Ismail Fawaz et al. (2019). """ padding = 'valid' input_layer = keras.layers.Input(input_shape) conv1 = keras.layers.Conv1D(filters=6,kernel_size=7,padding=padding,activation='sigmoid')(input_layer) conv1 = keras.layers.AveragePooling1D(pool_size=3)(conv1) conv2 = keras.layers.Conv1D(filters=12,kernel_size=7,padding=padding,activation='sigmoid')(conv1) conv2 = keras.layers.AveragePooling1D(pool_size=3)(conv2) flatten_layer = keras.layers.Flatten()(conv2) output_layer = keras.layers.Dense(units=1)(flatten_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = cnn_model() optimizer = Adam(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # TimeCNN_regressor_01: MSE, Adam, N_average=30, 2000 epochs, ES=250, RLR=50, gaussian=0.01 output_filename = 'TimeCNN_regressor_02' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=250, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=50, min_lr=0.0001, verbose=1) %%time epochs = 2000 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer, earlystopper, reduce_lr]) ``` # 6. BLSTM-LSTM ``` def blstm_lstm_model(): """ Returns the BLSTM-LSTM model from Kaushik et al. (2019). """ # MARK: This model compresses too much in the last phase, check if possible to improve. model = keras.Sequential() # BLSTM layer model.add(Bidirectional(LSTM(256, return_sequences=True), input_shape=input_shape)) model.add(Dropout(.2)) model.add(BatchNormalization()) # LSTM layer model.add(LSTM(128, return_sequences=True)) model.add(BatchNormalization()) # LSTM layer model.add(LSTM(64, return_sequences=False)) model.add(BatchNormalization()) # Fully connected layer model.add(Dense(32)) model.add(Dense(n_outputs)) return model model = blstm_lstm_model() optimizer = Adam(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # BLSTM_regressor_01: MSE, Adam, N_average=30, 1500 epochs, ES=250, RLR=50, gaussian=0.01 output_filename = 'BLSTM_regressor_01' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=250, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=50, min_lr=0.0001, verbose=1) model.summary() %%time epochs = 1500 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks=[checkpointer, earlystopper, reduce_lr]) ``` # 7. InceptionTime ``` class Regressor_Inception: def __init__(self, output_directory, input_shape, verbose=False, build=True, batch_size=64, nb_filters=32, use_residual=True, use_bottleneck=True, depth=6, kernel_size=41, nb_epochs=1500): self.output_directory = output_directory self.nb_filters = nb_filters self.use_residual = use_residual self.use_bottleneck = use_bottleneck self.depth = depth self.kernel_size = kernel_size - 1 self.callbacks = None self.batch_size = batch_size self.bottleneck_size = 32 self.nb_epochs = nb_epochs if build == True: self.model = self.build_model(input_shape) if (verbose == True): self.model.summary() self.verbose = verbose self.model.save_weights(self.output_directory + 'inception_model_init.hdf5') def _inception_module(self, input_tensor, stride=1, activation='linear'): if self.use_bottleneck and int(input_tensor.shape[-1]) > 1: input_inception = tf.keras.layers.Conv1D(filters=self.bottleneck_size, kernel_size=1, padding='same', activation=activation, use_bias=False)(input_tensor) else: input_inception = input_tensor # kernel_size_s = [3, 5, 8, 11, 17] kernel_size_s = [self.kernel_size // (2 ** i) for i in range(3)] conv_list = [] for i in range(len(kernel_size_s)): conv_list.append(tf.keras.layers.Conv1D(filters=self.nb_filters, kernel_size=kernel_size_s[i], strides=stride, padding='same', activation=activation, use_bias=False)( input_inception)) max_pool_1 = tf.keras.layers.MaxPool1D(pool_size=3, strides=stride, padding='same')(input_tensor) conv_6 = tf.keras.layers.Conv1D(filters=self.nb_filters, kernel_size=1, padding='same', activation=activation, use_bias=False)(max_pool_1) conv_list.append(conv_6) x = tf.keras.layers.Concatenate(axis=2)(conv_list) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(activation='relu')(x) return x def _shortcut_layer(self, input_tensor, out_tensor): shortcut_y = tf.keras.layers.Conv1D(filters=int(out_tensor.shape[-1]), kernel_size=1, padding='same', use_bias=False)(input_tensor) shortcut_y = tf.keras.layers.BatchNormalization()(shortcut_y) x = tf.keras.layers.Add()([shortcut_y, out_tensor]) x = tf.keras.layers.Activation('relu')(x) return x def build_model(self, input_shape): input_layer = tf.keras.layers.Input(input_shape) x = input_layer input_res = input_layer for d in range(self.depth): x = self._inception_module(x) if self.use_residual and d % 3 == 2: x = self._shortcut_layer(input_res, x) input_res = x pooling_layer = tf.keras.layers.AveragePooling1D(pool_size=50)(x) flat_layer = tf.keras.layers.Flatten()(pooling_layer) dense_layer = tf.keras.layers.Dense(128, activation='relu')(flat_layer) output_layer = tf.keras.layers.Dense(1)(dense_layer) model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer) return model model = Regressor_Inception(PATH_MODELS, input_shape, verbose=True).model optimizer = Adam(learning_rate=0.01) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=[RootMeanSquaredError(), MeanAbsoluteError()]) # 'Inception_regressor_01' (n_average = 40, gaussian_noise = 0.01, MAE) # 'Inception_regressor_02' (n_average = 1, gaussian_noise = 0.01, MAE) # 'Inception_regressor_03' (n_average = 40, gaussian_noise = 0.01, MSE) # 'Inception_regressor_04' (n_average = 1, gaussian_noise = 0.01, MSE) # 'Inception_regressor_05' (n_average = 100, gaussian_noise = 0.01, MAE) output_filename = 'Inception_regressor_05' output_file = os.path.join(PATH_MODELS, output_filename) checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True) earlystopper = EarlyStopping(monitor='val_loss', patience=100, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=20, min_lr=0.0001, verbose=1) %%time epochs = 1500 # fit network history = model.fit(x=train_generator_noise, validation_data=val_generator, epochs=epochs, callbacks = [checkpointer, earlystopper, reduce_lr]) ``` # Compare models ### Helper functions for comparison ``` # 'Inception_regressor_01' (n_average = 40, gaussian_noise = 0.01, MAE) model_path = os.path.join(PATH_MODELS, 'Inception_regressor_01.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # 'Inception_regressor_02' (n_average = 1, gaussian_noise = 0.01, MAE) model_path = os.path.join(PATH_MODELS, 'Inception_regressor_02.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # 'Inception_regressor_03' (n_average = 40, gaussian_noise = 0.01, MSE) model_path = os.path.join(PATH_MODELS, 'Inception_regressor_03.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # 'Inception_regressor_04' (n_average = 1, gaussian_noise = 0.01, MSE) model_path = os.path.join(PATH_MODELS, 'Inception_regressor_04.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # 'Inception_regressor_05' (n_average = 100, gaussian_noise = 0.01, MAE) model_path = os.path.join(PATH_MODELS, 'Inception_regressor_05.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # Fully_connected_regressor_02: MSE, Adadelta, N_average=30, 5000 epochs, ES=1000, RLR=200, gaussian=0.01 model_path = os.path.join(PATH_MODELS, 'Fully_connected_regressor_02.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # CNN_regressor_01: MSE, Adam, N_average=30, 2000 epochs, ES=250, RLR=50, gaussian=0.01 model_path = os.path.join(PATH_MODELS, 'CNN_regressor_01.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # ResNet_regressor_01: MSE, Adam, N_average=30, 1500 epochs, ES=250, RLR=50, gaussian=0.01 model_path = os.path.join(PATH_MODELS, 'ResNet_regressor_01.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # Encoder_regressor_01: MSE, Adam, N_average=30, 1500 epochs, ES=250, RLR=50, gaussian=0.01 (LR = 0.0001, no reduction) model_path = os.path.join(PATH_MODELS, 'Encoder_regressor_01.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) # TimeCNN_regressor_01: MSE, Adam, N_average=30, 2000 epochs, ES=250, RLR=50, gaussian=0.01 model_path = os.path.join(PATH_MODELS, 'TimeCNN_regressor_01.hdf5') loaded_model = tf.keras.models.load_model(model_path) evaluate_model(loaded_model) ```
github_jupyter
# Descriptive statistics ``` import numpy as np import seaborn as sns import scipy.stats as st import matplotlib.pyplot as plt import matplotlib.mlab as mlab import pandas as pd import statsmodels.api as sm import statistics import os from scipy.stats import norm ``` ## Probability data, binomial distribution We already got to know data that follow a binomial distribution, but we actually had not looked at the distribution. We will do this now. 10% of the 100 cells we count have deformed nuclei. To illustrate the distribution we will count repeatedly.... ``` n = 100 # number of trials p = 0.1 # probability of each trial s = np.random.binomial(n, p, 1000) #simulation repeating the experiment 1000 times print(s) ``` As you can see, the result of the distribution is in absolute counts, not proportions - they can easyly be converted by deviding with n, but they dont have to... ``` props = s/n print(props) ``` Now we plot the distribution. The easiest first look is a histogram. ``` plt.hist(props, bins = 5) plt.xlabel("proportion") plt.ylabel("frequency") plt.show() ``` The resolution is a bit inappropriate, given that we deal with integers. To increase the bin number would be a good idea. Maybe we should also plot a confidence interval. ``` CI= sm.stats.proportion_confint(n*p, n, alpha=0.05) print(CI) plt.axvspan(CI[0],CI[1], alpha=0.2, color='yellow') plt.hist(props, bins = 50) plt.xlabel("proportion") plt.ylabel("frequency") plt.axvline(p, color="black") ``` In a binomial distribution, the distribution is given by the proportion and the sample size. Therefore we could calculate a confidence interval from one measurement. #### How can we now describe the distribution? Summary statistics: ``` print("the minimum is:", min(props)) print("the maximum is:", max(props)) print(statistics.mean(props)) ``` Is the mean a good way to look at our distribution? ``` n = 50 # number of trials p = 0.02 # probability of each trial s = np.random.binomial(n, p, 1000) #simulation repeating the experiment 1000 times props = s/n CI= sm.stats.proportion_confint(n*p, n, alpha=0.05) print(CI) plt.axvspan(CI[0],CI[1], alpha=0.2, color='yellow') plt.hist(props, bins = 20) plt.xlabel("proportion") plt.ylabel("frequency") plt.axvline(p, color="black") plt.axvline(statistics.mean(props), color="red") print(statistics.mean(props)) ``` ## Count data/ the Poisson distribution The Poisson distribution is built on count data, e.g. the numbers of raisins in a Dresdner Christstollen, the number of geese at any given day between Blaues Wunder and Waldschlösschenbrücke, or radioactive decay. So lets use a Geiger counter and count the numbers of decay per min. ``` freq =1.6 s = np.random.poisson(freq, 1000) plt.hist(s, bins = 20) plt.xlabel("counts per minute") plt.ylabel("frequency") plt.axvline(freq, color="black") ``` ### Confidence intervals for a Poisson distribution Similar to the binomial distribution, the distribution is defined by sample size and the mean. Also for Poisson, one can calculate an also asymmetrical confidence interval: ``` freq =1.6 s = np.random.poisson(freq, 1000) CI = st.poisson.interval(0.95,freq) plt.axvspan(CI[0],CI[1], alpha=0.2, color='yellow') plt.hist(s, bins = 20) plt.xlabel("counts per minute") plt.ylabel("frequency") plt.axvline(freq, color="black") ``` For a poisson distribution, poisson error can be reduced, when increasing the counting population, in our case lets count for 10 min instead of 1 min, and see what happens. ``` CI = np.true_divide(st.poisson.interval(0.95,freq*10),10) print(CI) s = np.true_divide(np.random.poisson(freq*10, 1000),10) plt.axvspan(CI[0],CI[1], alpha=0.2, color='yellow') plt.hist(s, bins = 70) plt.xlabel("counts per minute") plt.ylabel("frequency") plt.axvline(freq, color="black") ``` What is the difference between Poisson and Binomial? Aren't they both kind of looking at count data? Yes, BUT: Binomial counts events versus another event, e.g. for the cells there are two options, normal versus deformed. A binomial distribution is about comparing the two options. Poisson counts with an open end, e.g. number of mutations. ## Continuous data Let's import the count data you have generated with Robert. When you download it from Google sheets (https://docs.google.com/spreadsheets/d/1Ek-23Soro5XZ3y1kJHpvaTaa1f4n2C7G3WX0qddD-78/edit#gid=0), it comes with spaces. Try to avoid spaces and special characters in file names, they tend to make trouble. I renamed it to 'BBBC001.csv'. ``` dat = pd.read_csv(os.path.join('data','BBBC001.csv'), header=1, sep=';') print(dat) ``` For now we will focus on the manual counts, visualise it and perform summary statistics. ``` man_count = dat.iloc[:,1].values plt.hist(man_count,bins=100) ``` There are different alternatives of displaying such data, some of which independent of distribution. You will find documentation in the graph galery: https://www.python-graph-gallery.com/ ``` sns.kdeplot(man_count) ``` A density plot is sometimes helpful to see the distribution, but be aware of the smoothing and that you loose the information on sample size. ``` sns.stripplot(y=man_count) sns.swarmplot(y=man_count) sns.violinplot(y=man_count) ``` this plot is useful, but the density function can sometimes be misleading and lead to artefacts dependent on the sample size. Unless explicitely stated, sample sizes are usually normalised and therefore hidden! ``` sns.boxplot(y=man_count) ``` Be aware that boxplots hide the underlying distribution and the sample size. So the "safest" plot, when in doubt, is to combine boxplot and jitter: ``` ax = sns.swarmplot(y=man_count, color="black") ax = sns.boxplot(y=man_count,color="lightgrey") ``` The boxplot is very useful, because it directly provides non-parametric summary statistics: Min, Max, Median, Quartiles and therefore the inter-quartile range (IQR). The whiskers are usually the highest point that is within 1.5x the quartile plus the IQR. Everything beyond that is considered an outlier. Whiskers are however not always used in this way! The mean and standard diviation are not visible in a boxplot, because it is only meaningful in distributions that center around the mean. It is however a part of summary statistics: ``` dat["BBBC001 manual count"].describe() ``` ## Normal distribution We assume that our distribution is "normal". First we fit a normal distribution to our data. ``` (mu, sigma) = norm.fit(man_count) n, bins, patches = plt.hist(man_count, 100,density=1) # add a 'best fit' line y = norm.pdf(bins, mu, sigma) l = plt.plot(bins, y, 'r--', linewidth=2) #plot plt.xlabel('manual counts counts') plt.ylabel('binned counts') plt.title(r'$\mathrm{Histogram\ of\ manual\ counts:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma)) plt.show() ``` Is it really normally distributed? What we see here is already one of the most problematic properties of a normal distribution: The susceptibility to outliers. In normal distributions the confidence interval is determined by the standard diviation. A confidence level of 95% equals 1.96 x sigma. ``` #plot (mu, sigma) = norm.fit(man_count) n, bins, patches = plt.hist(man_count, 100,density=1) # add a 'best fit' line y = norm.pdf(bins, mu, sigma) l = plt.plot(bins, y, 'r--', linewidth=2) plt.xlabel('manual counts counts') plt.ylabel('binned counts') plt.title(r'$\mathrm{Histogram\ of\ manual\ counts:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma)) plt.axvspan((mu-1.96*sigma),(mu+1.96*sigma), alpha=0.2, color='yellow') plt.axvline(mu, color="black") plt.show() ``` This shows even nicer that our outlier messes up the distribution :-) How can we solve this in practise? 1. Ignore the problem and continue with the knowledge that we are overestimating the width of the distribution and underestimating the mean. 2. Censor the outlier. 3. Decide that we cannot assume normality and move to either a different distribution or non-parametric statistics. ## Other distributions Of course there are many more distributions, e.g. Lognormal is a distribution that becomes normal, when log transformed. It is important for the "geometric mean". Bimodal distributions may arise from imaging data with background signal, or DNA methylation data. Negative binomial distributions are very important in genomics, especially RNA-Seq analysis. ## Exercise 1. We had imported the total table with also the automated counts. Visualise the distribution of the data next to each other 2. Generate the summary statistics and compare the different distributions 3. Two weeks ago you learned how to analyze a folder of images and measured the average size of beads: https://nbviewer.jupyter.org/github/BiAPoL/Bio-image_Analysis_with_Python/blob/main/image_processing/12_process_folders.ipynb Go back to the bead-analysis two weeks ago and measure the intensity of the individual beads (do not average over the image). Plot the beads' intensities as different plots. Which one do you find most approproiate for these data?
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') import torch # If there's a GPU available... if torch.cuda.is_available(): # Tell PyTorch to use the GPU. device = torch.device("cuda") print('There are %d GPU(s) available.' % torch.cuda.device_count()) print('We will use the GPU:', torch.cuda.get_device_name(0)) # If not... else: print('No GPU available, using the CPU instead.') device = torch.device("cpu") !ls drive/My\ Drive/Colab\ Notebooks/bert BERT_PATH = "drive/My Drive/Colab Notebooks/bert" COLUMN_NAME = "raw_tweet_features_text_tokens" PATH = BERT_PATH+"/tweet_features_text_tokens_padded.csv.gz" N_ROWS = 1000 CHUNKSIZE = 10 PAD = int(0) MAX_LENGTH = 179 VOCAB = 'bert-base-multilingual-cased' !pip install transformers import pandas as pd import numpy as np from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained(VOCAB) vocab_size = len(tokenizer.vocab.keys()) vocab_size tokenizer.vocab['[PAD]'] ``` ## Load tweets from csv file as lists of int tokens ``` # Declaring two lambdas in order to cast a string to a numpy array of integers f_to_int = lambda x: int(x) f_int = lambda x: list(map(f_to_int, x.replace('[', '').replace(']', '').replace(' ', '').split(','))) def read_tweets_list(path): list_of_tweets = [] for chunk in pd.read_csv(path, chunksize=CHUNKSIZE, names=[COLUMN_NAME], #dtype={COLUMN_NAME: pd.Int32Dtype()}, nrows=N_ROWS, header=None, index_col=0, compression='gzip'): #print(chunk) tweets = chunk[COLUMN_NAME] for t in tweets: t_list = f_int(t) list_of_tweets.append(t_list) return list_of_tweets tokenized_tweets = read_tweets_list(PATH) n_tweets = len(tokenized_tweets) n_tweets ``` ## Check that at least one tweet having the last token different from PAD exists ``` for tweet in tokenized_tweets: if tweet[-1] != PAD: print('Ok') ``` ## Decode all the tweets in the list ``` decoded_tweets = [] for t in tokenized_tweets: decoded_tweets.append(tokenizer.decode(t)) len(decoded_tweets) ``` ## Find two tweets containing the words "obama" and "president" ``` i = 0 for t in decoded_tweets: if "president" in t or "obama" in t: print(i) i += 1 ``` ## Create the model from a pre-trained one ``` from transformers import BertModel, AdamW, BertConfig # Load BERT model, the pretrained BERT model with a single # linear classification layer on top. model = BertModel.from_pretrained( VOCAB, # Use the 12-layer BERT model, with an uncased vocab. ) # Tell pytorch to run this model on the GPU. model.cuda() # Get all of the model's parameters as a list of tuples. params = list(model.named_parameters()) print('The BERT model has {:} different named parameters.\n'.format(len(params))) print('==== Embedding Layer ====\n') for p in params[0:5]: print("{:<55} {:>12}".format(p[0], str(tuple(p[1].size())))) print('\n==== First Transformer ====\n') for p in params[5:21]: print("{:<55} {:>12}".format(p[0], str(tuple(p[1].size())))) print('\n==== Output Layer ====\n') for p in params[-2:]: print("{:<55} {:>12}".format(p[0], str(tuple(p[1].size())))) ``` ## Create inputs tensor ``` decoded_tweets[754] # it contains the word "president" decoded_tweets[813] # it contains the word "obama" model.eval() tweet1 = tokenized_tweets[754] tweet2 = tokenized_tweets[813] inputs ``` ## Create attention mask ``` masks = [] masks.append([int(token_id > 0) for token_id in tweet1]) # mask PAD tokens (PAD == 0) masks.append([int(token_id > 0) for token_id in tweet2]) masks = torch.tensor(masks) masks.shape masks ``` ## Move tensors to GPU ``` inputs = inputs.to(device) masks = masks.to(device) ``` ## Get model outputs ``` outputs = model(input_ids=inputs, attention_mask=masks) outputs[0][0].size() outputs[0][1].size() outputs[1][0].size() outputs[1][1].size() ``` #### The output is a tuple with 2 elements: * a list containing lists of lists: for each input token we obtain a vector with 768 elements ---> for each input we have a list of MAX_LENGTH lists (one for each token), each containing 768 values (refer to this link http://jalammar.github.io/a-visual-guide-to-using-bert-for-the-first-time/, in the "Flowing through DistillBERT" section) * the second element is a list containing an embedding vector for each input ``` outputs ``` ## Compute similarity between the two embedding vectors ``` emb1 = outputs[1][0] emb2 = outputs[1][1] torch.dot(emb1, emb2) # dot product cosine = torch.nn.CosineSimilarity(dim=0) cosine(emb1, emb2) # cosine similarity ``` ## Similarity between other two tweets ``` decoded_tweets[2] decoded_tweets[200] tweet1 = tokenized_tweets[2] tweet2 = tokenized_tweets[200] inputs = torch.tensor([tweet1, tweet2]) masks = [] masks.append([int(token_id > 0) for token_id in tweet1]) # mask PAD tokens (PAD == 0) masks.append([int(token_id > 0) for token_id in tweet2]) masks = torch.tensor(masks) inputs = inputs.to(device) masks = masks.to(device) outputs = model(input_ids=inputs, attention_mask=masks) emb1 = outputs[1][0] emb2 = outputs[1][1] torch.dot(emb1, emb2) # dot product cosine = torch.nn.CosineSimilarity(dim=0) cosine(emb1, emb2) # cosine similarity ```
github_jupyter
# Qiskit: Open-Source Quantum Development, an introduction --- ### Workshop contents 1. Intro IBM Quantum Lab and Qiskit modules 2. Circuits, backends, visualization 3. Quantum info, circuit lib, algorithms 4. Circuit compilation, pulse, opflow ## 1. Intro IBM Quantum Lab and Qiskit modules ### https://quantum-computing.ibm.com/lab ### https://qiskit.org/documentation/ ### https://github.com/qiskit ## 2. Circuits, backends and visualization ``` from qiskit import IBMQ # Loading your IBM Quantum account(s) #provider = IBMQ.load_account() #provider = IBMQ.enable_account(<token>) IBMQ.providers() ``` ### Your first quantum circuit Let's begin exploring the different tools in Qiskit Terra. For that, we will now create a Quantum Circuit. ``` from qiskit import QuantumCircuit # Create circuit # <INSERT CODE> # print circuit # <INSERT CODE> ``` Now let's run the circuit in the Aer simulator and plot the results in a histogram. ``` from qiskit import Aer # run circuit on Aer simulator # <INSERT CODE> from qiskit.visualization import plot_histogram # and display it on a histogram # <INSERT CODE> ``` ### Qiskit Visualization tools ``` from qiskit.visualization import plot_state_city from qiskit.visualization import plot_state_paulivec, plot_state_hinton circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0, 1) backend = Aer.get_backend('statevector_simulator') # the device to run on result = backend.run(circuit).result() psi = result.get_statevector(circuit) # plot state city # <INSERT CODE> # plot state hinton # <INSERT CODE> # plot state paulivec # <INSERT CODE> ``` #### Circuit Visualization ``` from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # Build a quantum circuit circuit = QuantumCircuit(3, 3) circuit.x(1) circuit.h(range(3)) circuit.cx(0, 1) circuit.measure(range(3), range(3)); # print circuit # <INSERT CODE> # print circuit using draw method # <INSERT CODE> ``` There are different drawing formats. The parameter output (str) selects the output method to use for drawing the circuit. Valid choices are ``text, mpl, latex, latex_source``. See [qiskit.circuit.QuantumCircuit.draw](https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.draw.html?highlight=draw) ``` # print circuit using different drawer (mlp for example) # <INSERT CODE> ``` ##### Disable Plot Barriers and Reversing Bit Order ``` # Draw a new circuit with barriers and more registers q_a = QuantumRegister(3, name='qa') q_b = QuantumRegister(5, name='qb') c_a = ClassicalRegister(3) c_b = ClassicalRegister(5) circuit = QuantumCircuit(q_a, q_b, c_a, c_b) circuit.x(q_a[1]) circuit.x(q_b[1]) circuit.x(q_b[2]) circuit.x(q_b[4]) circuit.barrier() circuit.h(q_a) circuit.barrier(q_a) circuit.h(q_b) circuit.cswap(q_b[0], q_b[1], q_b[2]) circuit.cswap(q_b[2], q_b[3], q_b[4]) circuit.cswap(q_b[3], q_b[4], q_b[0]) circuit.barrier(q_b) circuit.measure(q_a, c_a) circuit.measure(q_b, c_b); # Draw the circuit # <INSERT CODE> # Draw the circuit with reversed bit order # <INSERT CODE> # Draw the circuit without barriers # <INSERT CODE> ``` ##### MPL specific costumizations ``` # Change the background color in mpl # <INSERT CODE> # Scale the mpl output to 1/2 the normal size # <INSERT CODE> ``` ### Simulators ``` import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory (measurement outcomes for each individual shot) result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) print(memory) ``` ##### Simulation methods ``` # Increase shots to reduce sampling variance shots = 10000 # Stabilizer simulation method sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) # Statevector simulation method sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Density Matrix simulation method sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) # Matrix Product State simulation method sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps = job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) ``` ##### Simulation precision ``` # Configure a single-precision statevector simulator backend simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) print(counts) ``` ##### Device backend noise model simulations ``` from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.test.mock import FakeVigo device_backend = FakeVigo() # Construct quantum circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) # Create ideal simulator and run # <INSERT CODE> # Create simulator from backend # <INSERT CODE> # Transpile the circuit for the noisy basis gates and get results # <INSERT CODE> ``` #### Usefull operations with circuits ``` qc = QuantumCircuit(12) for idx in range(5): qc.h(idx) qc.cx(idx, idx+5) qc.cx(1, 7) qc.x(8) qc.cx(1, 9) qc.x(7) qc.cx(1, 11) qc.swap(6, 11) qc.swap(6, 9) qc.swap(6, 10) qc.x(6) qc.draw() # width of circuit # <INSERT CODE> # number of qubits # <INSERT CODE> # count of operations # <INSERT CODE> # size of circuit # <INSERT CODE> # depth of circuit # <INSERT CODE> ``` #### Final statevector ``` # Saving the final statevector # Construct quantum circuit without measure from qiskit.visualization import array_to_latex circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) # save statevector, run circuit and get results # <INSERT CODE> # Saving the circuit unitary # Construct quantum circuit without measure circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) # save unitary, run circuit and get results # <INSERT CODE> ``` Saving multiple statevectors ``` # Saving multiple states # Construct quantum circuit without measure steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() data = result.data(0) data ``` Saving custom statevector ``` # Generate a random statevector num_qubits = 2 psi = qi.random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) ``` ### Parametric circuits ``` # Parameterized Quantum Circuits from qiskit.circuit import Parameter # create parameter and use it in circuit # <INSERT CODE> res = sim.run(circuit, parameter_binds=[{theta: [np.pi/2, np.pi, 0]}]).result() # Different bindings res.get_counts() from qiskit.circuit import Parameter theta = Parameter('θ') n = 5 qc = QuantumCircuit(5, 1) qc.h(0) for i in range(n-1): qc.cx(i, i+1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(n-1)): qc.cx(i, i+1) qc.h(0) qc.measure(0, 0) qc.draw('mpl') #We can inspect the circuit’s parameters # <INSERT CODE> import numpy as np theta_range = np.linspace(0, 2 * np.pi, 128) circuits = [qc.bind_parameters({theta: theta_val}) for theta_val in theta_range] circuits[-1].draw() backend = Aer.get_backend('aer_simulator') job = backend.run(transpile(circuits, backend)) counts = job.result().get_counts() import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0') ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1') ax.set_xticks([i * np.pi / 2 for i in range(5)]) ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14) ax.set_xlabel('θ', fontsize=14) ax.set_ylabel('Counts', fontsize=14) ax.legend(fontsize=14) # Random Circuit from qiskit.circuit.random import random_circuit # create random circuit # <INSERT CODE> # add unitary matrix to circuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] # <INSERT CODE> # Classical logic from qiskit.circuit import classical_function, Int1 @classical_function def oracle(x: Int1, y: Int1, z: Int1) -> Int1: return not x and (y or z) circuit = QuantumCircuit(4) circuit.append(oracle, [0, 1, 2, 3]) circuit.draw() # circuit.decompose().draw() #synthesis # Classical logic from qiskit.circuit import classical_function, Int1 @classical_function def oracle(x: Int1) -> Int1: return not x circuit = QuantumCircuit(2) circuit.append(oracle, [0, 1]) circuit.draw() circuit.decompose().draw() ``` https://qiskit.org/documentation/tutorials/circuits_advanced/02_operators_overview.html ## 3. Quantum info, circuit lib and algorithms ### Circuit lib ``` from qiskit.circuit.library import InnerProduct, QuantumVolume, clifford_6_2, C3XGate # inner product circuit # <INSERT CODE> # clifford # <INSERT CODE> ``` ### Quantum info ``` from qiskit.quantum_info.operators import Operator # Create an operator # <INSERT CODE> # add operator to circuit # <INSERT CODE> # Pauli from qiskit.quantum_info.operators import Pauli # use Pauli operator # <INSERT CODE> # Pauli with phase from qiskit.quantum_info.operators import Pauli circuit = QuantumCircuit(4) iIXYZ = Pauli('iIXYZ') # ['', '-i', '-', 'i'] circuit.append(iIXYZ, [0, 1, 2, 3]) circuit.draw() # create clifford from qiskit.quantum_info import random_clifford # random clifford # <INSERT CODE> # stabilizer and destabilizer # <INSERT CODE> ``` ### Algorithms #### VQE ``` from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.circuit.library import TwoLocal num_qubits = 2 ansatz = TwoLocal(num_qubits, 'ry', 'cz') opt = SLSQP(maxiter=1000) vqe = VQE(ansatz, optimizer=opt) from qiskit.opflow import X, Z, I H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) from qiskit.utils import algorithm_globals seed = 50 algorithm_globals.random_seed = seed qi = QuantumInstance(Aer.get_backend('statevector_simulator'), seed_transpiler=seed, seed_simulator=seed) ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz') slsqp = SLSQP(maxiter=1000) vqe = VQE(ansatz, optimizer=slsqp, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) ``` #### Grover's algorithm ``` from qiskit.algorithms import Grover from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm problem.grover_operator.draw(output='mpl') from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import Grover aer_simulator = Aer.get_backend('aer_simulator') grover = Grover(quantum_instance=aer_simulator) result = grover.amplify(problem) print('Result type:', type(result)) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) ``` ## 4. Transpiling, pulse and opflow ### Compiling circuits ``` [(b.name(), b.configuration().n_qubits) for b in provider.backends()] from qiskit.tools.jupyter import * %qiskit_backend_overview from qiskit.providers.ibmq import least_busy # get least busy backend # <INSERT CODE> # bell state circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() circuit.draw() # run it in simulator sim = Aer.get_backend('aer_simulator') result = sim.run(circuit).result() counts = result.get_counts() plot_histogram(counts) # run on least busy backend # <INSERT CODE> # get results # <INSERT CODE> circuit.draw('mpl') from qiskit import transpile # transpile with specified backend # <INSERT CODE> # rerun job # <INSERT CODE> # job status # <INSERT CODE> # get results # <INSERT CODE> from qiskit.visualization import plot_circuit_layout, plot_gate_map display(transpiled_circuit.draw(idle_wires=False)) display(plot_gate_map(backend)) plot_circuit_layout(transpiled_circuit, backend) # a slightly more interesting example: circuit = QuantumCircuit(3) circuit.h([0,1,2]) circuit.ccx(0, 1, 2) circuit.h([0,1,2]) circuit.ccx(2, 0, 1) circuit.h([0,1,2]) circuit.measure_all() circuit.draw() transpiled = transpile(circuit, backend) transpiled.draw(idle_wires=False, fold=-1) # Initial layout # transpiling with initial layout # <INSERT CODE> transpiled.draw(idle_wires=False, fold=-1) level0 = transpile(circuit, backend, optimization_level=0) level1 = transpile(circuit, backend, optimization_level=1) level2 = transpile(circuit, backend, optimization_level=2) level3 = transpile(circuit, backend, optimization_level=3) for level in [level0, level1, level2, level3]: print(level.count_ops()['cx'], level.depth()) # transpiling is a stochastic process transpiled = transpile(circuit, backend, optimization_level=2, seed_transpiler=42) transpiled.depth() transpiled = transpile(circuit, backend, optimization_level=2, seed_transpiler=1) transpiled.depth() # Playing with other transpiler options (without a backend) transpiled = transpile(circuit) transpiled.draw(fold=-1) # Set a basis gates backend.configuration().basis_gates # specify basis gates # <INSERT CODE> # Set a coupling map backend.configuration().coupling_map from qiskit.transpiler import CouplingMap # specify coupling map # <INSERT CODE> # Set an initial layout in a coupling map transpiled = transpile(circuit, coupling_map=CouplingMap([(0,1),(1,2)]), initial_layout=[1, 0, 2]) transpiled.draw(fold=-1) # Set an initial_layout in the coupling map with basis gates transpiled = transpile(circuit, coupling_map=CouplingMap([(0,1),(1,2)]), initial_layout=[1, 0, 2], basis_gates=['x', 'cx', 'h', 'p'] ) transpiled.draw(fold=-1) transpiled.count_ops()['cx'] # Plus optimization level transpiled = transpile(circuit, coupling_map=CouplingMap([(0,1),(1,2)]), initial_layout=[1, 0, 2], basis_gates=['x', 'cx', 'h', 'p'], optimization_level=3 ) transpiled.draw(fold=-1) transpiled.count_ops()['cx'] # Last parameter, approximation degree transpiled = transpile(circuit, coupling_map=CouplingMap([(0,1),(1,2)]), initial_layout=[1, 0, 2], basis_gates=['x', 'cx', 'h', 'p'], approximation_degree=0.99, optimization_level=3 ) transpiled.draw(fold=-1) transpiled.depth() transpiled = transpile(circuit, coupling_map=CouplingMap([(0,1),(1,2)]), initial_layout=[1, 0, 2], basis_gates=['x', 'cx', 'h', 'p'], approximation_degree=0.01, optimization_level=3 ) transpiled.draw(fold=-1) transpiled.depth() ``` #### Qiskit is hardware agnostic! ``` # !pip install qiskit-ionq # from qiskit_ionq import IonQProvider # provider = IonQProvider(<your token>) # circuit = QuantumCircuit(2) # circuit.h(0) # circuit.cx(0, 1) # circuit.measure_all() # circuit.draw() # backend = provider.get_backend("ionq_qpu") # job = backend.run(circuit) # plot_histogram(job.get_counts()) ``` ### Pulse ``` from qiskit import pulse # create dummy pusle program # <INSERT CODE> from qiskit.pulse import DriveChannel channel = DriveChannel(0) from qiskit.test.mock import FakeValencia # build backend aware pulse schedule # <INSERT CODE> ``` #### Delay instruction ``` # delay instruction # <INSERT CODE> ``` #### Play instruction #### Parametric pulses ``` from qiskit.pulse import library # build parametric pulse # <INSERT CODE> # play parametric pulse # <INSERT CODE> # set frequency # <INSERT CODE> # shift phase # <INSERT CODE> from qiskit.pulse import Acquire, AcquireChannel, MemorySlot # aqure instruction # <INSERT CODE> # example with left align schedule # <INSERT CODE> from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() ``` ### Opflow ``` from qiskit.opflow import I, X, Y, Z print(I, X, Y, Z) # These operators may also carry a coefficient. # <INSERT CODE> # These coefficients allow the operators to be used as terms in a sum. # <INSERT CODE> # Tensor products are denoted with a caret, like this. # <INSERT CODE> # Composition is denoted by the @ symbol. # <INSERT CODE> ``` ### State functions and measurements ``` from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn) # zero, one # <INSERT CODE> # plus, minus # <INSERT CODE> # evaulation # <INSERT CODE> # adjoint # <INSERT CODE> # other way of writing adjoint # <INSERT CODE> ``` #### Algebraic operations ``` import math v_zero_one = (Zero + One) / math.sqrt(2) print(v_zero_one) print(StateFn({'0':1})) print(StateFn({'0':1}) == Zero) print(StateFn([0,1,1,0])) from qiskit.circuit.library import RealAmplitudes print(StateFn(RealAmplitudes(2))) from qiskit.opflow import Zero, One, H, CX, I # bell state # <INSERT CODE> # implement arbitrary circuits # <INSERT CODE> ```
github_jupyter
# Pivotal method vs Percentile Method In this notebook we will explore the difference between the **pivotal** and **percentile** bootstrapping methods. tldr - * The **percentile method** generates a bunch of re-samples and esimates confidence intervals based on the percentile values of those re-samples. * The **pivotal method** is similar to percentile but does a correction for the fact that your input sample may not be a good representation of your population. Bootstrapped uses this as the default. We will show that the pviotal method has generally better power. This does come at a cost - the pivotal method can warp the confidence interval to give non-sencical interval values. See [Link1](https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdf), [Link2](http://www.stat.cmu.edu/~cshalizi/402/lectures/08-bootstrap/lecture-08.pdf) for explanations of both methods. ``` import matplotlib.pyplot as plt import pandas as pd import numpy as np import numpy.random as npr import bootstrapped.bootstrap as bs import bootstrapped.stats_functions as bs_stats import bootstrapped.power as bs_power ``` ### Setup The bootstrap is based on a sample of your larger population. A sample is only as good as how representitave it is. If you happen to be unlucky in your sample then you are going to make some very bad inferences! We pick the exponential distribution because it should differentiate the difference between the two methods somewhat. We will also look at an extreme case. ``` population = np.random.exponential(scale=1000, size=500000) # Plot the population count, bins, ignored = plt.hist(population, 30, normed=True) plt.title('Distribution of the population') plt.show() population = pd.Series(population) # Do a bunch of simpulations and track the percent of the time the error bars overlap the true mean def bootstrap_vs_pop_mean(population, num_samples, is_pivotal, num_loops=3000): population_mean = population.mean() pop_results = [] for _ in range(num_loops): samples = population.sample(num_samples) result = bs.bootstrap(samples.values, stat_func=bs_stats.mean, is_pivotal=is_pivotal) # we want to 0 center this for our power plotting below # we want our error bars to overlap zero result = result - population_mean pop_results.append(result) return pop_results def bounds_squared_distance(results): '''The squared distance from zero for both the lower and the upper bound This is a rough measure of how 'good' the confidence intervals are in terms of near misses vs extreme misses. It is minimized when (1) the confidence interval is symmetric over zero and (2) when it is narrow. ''' return np.sum([r.upper_bound**2 for r in results]) + np.sum([r.lower_bound**2 for r in results]) def squared_dist_ratio(x, y): 'Compare bounds_squared_distance for two sets of bootstrap results' return bounds_squared_distance(x) / bounds_squared_distance(y) ``` ### Pivotal vs Percentile for very small input sample size - 10 elements ``` pivotal_tiny_sample_count = bootstrap_vs_pop_mean(population, num_samples=10, is_pivotal=True) percentile_tiny_sample_count = bootstrap_vs_pop_mean(population, num_samples=10, is_pivotal=False) squared_dist_ratio(pivotal_tiny_sample_count, percentile_tiny_sample_count) # more insignificant results is better print(bs_power.power_stats(pivotal_tiny_sample_count)) bs_power.plot_power(pivotal_tiny_sample_count[::20]) # more insignificant results is better print(bs_power.power_stats(percentile_tiny_sample_count)) bs_power.plot_power(percentile_tiny_sample_count[::20]) ``` ### Pivotal vs Percentile for small input sample size - 100 elements ``` pivotal_small_sample_count = bootstrap_vs_pop_mean(population, num_samples=100, is_pivotal=True) percentile_small_sample_count = bootstrap_vs_pop_mean(population, num_samples=100, is_pivotal=False) squared_dist_ratio(pivotal_small_sample_count, percentile_small_sample_count) print(bs_power.power_stats(pivotal_small_sample_count)) bs_power.plot_power(pivotal_small_sample_count[::20]) print(bs_power.power_stats(percentile_small_sample_count)) bs_power.plot_power(percentile_small_sample_count[::20]) ``` ### Pivotal vs Percentile for medium input sample size - 1000 elements ``` pivotal_med_sample_count = bootstrap_vs_pop_mean(population, num_samples=1000, is_pivotal=True) percentile_med_sample_count = bootstrap_vs_pop_mean(population, num_samples=1000, is_pivotal=False) squared_dist_ratio(pivotal_med_sample_count, percentile_med_sample_count) print(bs_power.power_stats(pivotal_med_sample_count)) bs_power.plot_power(pivotal_med_sample_count[::20]) print(bs_power.power_stats(percentile_med_sample_count)) bs_power.plot_power(percentile_med_sample_count[::20]) ``` ### Pivotal vs Percentile for somewhat large input sample size - 10k elements ### Bad Populaiton ``` bad_population = pd.Series([1]*10000 + [100000]) # Plot the population count, bins, ignored = plt.hist(bad_population, 30, normed=True) plt.title('Distribution of the population') plt.show() samples = bad_population.sample(10000) print('Mean:\t\t{}'.format(bad_population.mean())) print('Pivotal CI:\t{}'.format(bs.bootstrap(samples.values, stat_func=bs_stats.mean, is_pivotal=True))) print('Percentile CI:\t{}'.format(bs.bootstrap(samples.values, stat_func=bs_stats.mean, is_pivotal=False))) ``` **Analysis:** The correction from the pivotal method causes a negative lower bound for the estimate in this instance. Generalization: the pivotal correction may not always produce realisitc intervals. In this situation we know that the mean cant be less than one. Still, we have seen from above that the piovtal method seems to be more reliable - this is why it is the default.
github_jupyter
Cesar Andrés Galindo Villalobos / Juan Sebastian Correa Paez **MOVIMIENTO DE UN CUERPO HACÍA UN PLANETA** Un cuerpo de masa m2, parte desde una posición (a,b), con una velocidad horizontal Vx y una velocidad vertical Vy hacía un planeta de masa 1, radio R y con un centro de gravedad ubicado en el punto (h,k) del sistema de coordenadas rectangulares y a una distancia r. Establecer un modelo fisico matemático para definir si el cuerpo choca o no con el planeta. **Elementos trigonométricos** - Ángulo de desviación (alpha) sen(alpha)=R/r entonces alpha=arcsen(R/r) **(1)** donde R es constante, r es el vector posición inicial. Si r -> alpha, entonces alpha = 0 - Ángulo de inclinación de vector de la fuerza de gravitación universal tan(tetha)=(b-k)/(a-h) -> tetha=arctan((b-k)/(a-h)) **(2)** - Ángulo direccional del vector de la velocidad tan(betha)=Vy/Vx -> betha=arctan(Vy/Vx) **(3)** - Relación entre ángulos tetha=alpha + betha -> alpha = tetha - alpha alpha = arcsen(R/r) =arctan((b-k)/(a-h))=arctan(Vy/Vx) **(4)** **Situaciones físicas** Si alpha<=arcsen(R/r), el cuerpo hará contacto con el planeta Si alpha>arcsen(R/r), el cuerpo no hará contacto con el planeta **Modelo fisico matemático que relaciona el ánguo de desviación con las variables físicas: fuerza gravitacional, posición.** - Vector posición en función de masas y fuerza gravitacional F=(Gm1m2)/r^2 -> r^2=(G*m1*m2)/F -> r=((Gm1m2)/F)^(1/2) **(5)** - Reemplazar r en ecuación (1) alpha=arcsen(R/((Gm1m2)/F)^(1/2)) = arcsen=(R(F/(Gm1m2))^(1/2)) Si F -> 0, entonces alpha -> 0 - Modelo Físico matemático alpha=arcsen(R*(F/(G*m1*m2))^(1/2)) = arctan((b-k)/(a-h))- arctan(Vy/Vx) **FORMA DE SOLUCIÓN NO.1 SEGÚN ÁNGULO DE DESVIACIÓN** ``` import math f = open ('tarea4-01.txt','r') mensaje = f.read() print("Los datos son:", mensaje) G=float(6.67*(10**-11)) dato=str(mensaje).split(",") h=float(dato[0]) a=float(dato[1]) k=float(dato[2]) b=float(dato[3]) m1=float(dato[4]) m2=float(dato[5]) Vx=float(dato[6]) r=float(dato[7]) R=float(dato[8]) Vy=float(dato[9]) F=(G*m1*m2)/(r**2) alpharad=math.asin((R*math.sqrt(F))/(math.sqrt(G*m1*m2))) alpha=math.degrees(alpharad) print("El ángulo de desviación es", alpha) condicion=math.asin(R/r) print("La condición es:",condicion) if alpha <= condicion: print("Como el ángulo de desviación no es mayor a la condición, el cuerpo hará contacto con el planeta") else: print("Como el ángulo de desviación es mayor a la condición, el cuerpo no hará contacto con el planeta") f.close() ``` **FORMA DE SOLUCIÓN NO.2 SEGÚN ÁNGULO DE DESVIACIÓN** ``` import math f = open ('tarea4-01.txt','r') mensaje = f.read() print("Los datos son:", mensaje) G=float(6.67*(10**-11)) dato=str(mensaje).split(",") h=float(dato[0]) a=float(dato[1]) k=float(dato[2]) b=float(dato[3]) m1=float(dato[4]) m2=float(dato[5]) Vx=float(dato[6]) r=float(dato[7]) R=float(dato[8]) Vy=float(dato[9]) alpha=math.atan((b-k)/(a-h))-math.atan(Vy/Vx) alpha=math.degrees(alpharad) print("El ángulo de desviación es", alpha) condicion=math.asin(R/r) print("La condición es:",condicion) if alpha <= condicion: print("Como el ángulo de desviación no es mayor a la condición, el cuerpo hará contacto con el planeta") else: print("Como el ángulo de desviación es mayor a la condición, el cuerpo no hará contacto con el planeta") f.close() ```
github_jupyter
``` import sys sys.path.append('/Users/mic.fell/Documents/venvs/jupyter/lib/python3.6/site-packages') import pandas as pd import html from functools import reduce import re import numpy as np from nltk import word_tokenize import spacy import pronouncing from textblob import TextBlob from sklearn.preprocessing import StandardScaler from keras.models import load_model import _pickle from sklearn import preprocessing nlp = spacy.load('en_core_web_lg') mpd_with_lyrics = pd.read_csv('/Users/mic.fell/Documents/Jupyter Orbit/resources/recsys_challenge_2018/mpd_wasabi_aligned_langdetect.csv', sep='\t', encoding='utf8') mpd_with_lyrics = mpd_with_lyrics.drop(['Unnamed: 0'], axis=1) mpd_with_lyrics.head() features = read_file('/Users/mic.fell/Documents/Jupyter Orbit/resources/recsys_challenge_2018/mpd_ids_english_features.pickle') features.head() # use only english lyrics mpd_with_lyrics = mpd_with_lyrics[mpd_with_lyrics['langdetect'] == 'en'] print('aligned indices :', len(mpd_with_lyrics)) print('unique Spotify URIs:', len(set(mpd_with_lyrics['spotify_track_uri']))) print('unique lyrics :', len(set(mpd_with_lyrics['lyrics']))) def read_file(name): with open(name, 'rb') as f: content = _pickle.load(f) return content def write_file(content, name): with open(name, 'wb') as f: _pickle.dump(content, f) def robust_min_max_scaler(matrix): matrix_robust = preprocessing.RobustScaler().fit_transform(matrix) matrix_mmax = preprocessing.MinMaxScaler().fit_transform(matrix_robust) return matrix_mmax # parse lyrics to segment-line-structure, assuming lines are separated by line_border_indicator and # segments are separated by multiple consecutive line_border_indicator occurences # assuming line_border_indicator is <br> (standard in lyrics.wikia.com) def tree_structure(text): #normalize segment border encoding segment_border_encoder = '<segmentborder>' line_border_encoder = '<lineborder>' tree_string = re.sub('(( )*<br>( )*){2,}', segment_border_encoder, text) tree_string = re.sub('( )*<br>( )*', line_border_encoder, tree_string) #parse tree_string segment_structure = tree_string.split(segment_border_encoder) tree_structure = list(map(lambda segment: segment.split(line_border_encoder), segment_structure)) return tree_structure #flattened tree structure, does not differentiate between segment and line border def line_structure(lyric_tree): return reduce(lambda x, segment: x + segment, lyric_tree, []) # flattened line_structure def token_structure(lyric_tree, tokenizer=word_tokenize): return reduce(lambda x, line: extend_with_return(x, tokenizer(line)), line_structure(lyric_tree), []) def extend_with_return(some_list, other_list): some_list.extend(other_list) return some_list # normalizations we want to apply to all lyrics go here def normalize_lyric(lyric): lyric = html.unescape(lyric) lyric = lyric.lower() return lyric # Reduce a list of numbers to single number / feature (cf. np.average, np.std, ...) def list_span(some_list): min_list = min(some_list) return max(some_list) / min_list if min_list > 0 else 1e-10 ###################################### ########Stylometric features########## ###################################### def type_token_ratio(lyric_tokens): return len(set(lyric_tokens)) / len(lyric_tokens) def line_lengths_in_chars(lyric_lines): return list(map(len, lyric_lines)) def line_lengths_in_tokens(lyric_lines): return list(map(lambda line: len(word_tokenize(line)), lyric_lines)) def pos_tag_distribution(lyric_lines): # Look at https://spacy.io/api/annotation for a better description of each tag tags = ['ADJ', 'ADP', 'ADV', 'AUX', 'CONJ', 'CCONJ', 'DET', 'INTJ', 'NOUN', 'NUM', 'PART', 'PRON', 'PROPN', 'PUNCT', 'SCONJ', 'SYM', 'VERB', 'X', 'SPACE'] freq = dict() for tag in tags: freq[tag] = 0 for line in lyric_lines: doc = nlp(line) for word in doc: if word.pos_ in tags: freq[word.pos_] += 1 wc = sum(line_lengths_in_tokens(lyric_lines)) for key in freq: freq[key] /= wc return freq def get_rhymes(lyric_lines): count = 0 lyric_length = len(lyric_lines) for i in range(lyric_length-1): words = lyric_lines[i].split() if len(words) < 1: continue rhymes = pronouncing.rhymes(words[-1]) next_line_words = lyric_lines[i+1].split() if next_line_words is not None and len(next_line_words) > 0 and next_line_words[-1] in rhymes: count += 1 return count / lyric_length if lyric_length > 0 else 0 def get_echoisms(lyric_lines): vowels = ['a', 'e', 'i', 'o', 'u'] # Do echoism count on a word level echoism_count = 0 for line in lyric_lines: doc = nlp(line) for i in range(len(doc) - 1): echoism_count += doc[i].text.lower() == doc[i+1].text.lower() # Count echoisms inside words e.g. yeeeeeeah for tk in doc: for i in range(len(tk.text) - 1): if tk.text[i] == tk.text[i+1] and tk.text in vowels: echoism_count += 1 break return echoism_count / sum(line_lengths_in_tokens(lyric_lines)) def is_title_in_lyrics(title, lyric_lines): for line in lyric_lines: if title in line: return True return False def count_duplicate_lines(lyric_lines): wc = sum(line_lengths_in_tokens(lyric_lines)) wc = wc if wc > 0 else 1 return sum([lyric_lines.count(x) for x in list(set(lyric_lines)) if lyric_lines.count(x) > 1]) / wc ################################## ########Segment features########## ################################## #The indices of lines that end a segment def segment_borders(lyric_tree): segment_lengths = reduce(lambda x, block: x + [len(block)], lyric_tree, []) segment_indices = [] running_sum = -1 for i in range(len(segment_lengths)): running_sum += segment_lengths[i] segment_indices.append(running_sum) return segment_indices[:-1] # lengths of the segments def segment_lengths(lyric_tree): return reduce(lambda x, block: x + [len(block)], lyric_tree, []) ################################## ########Orientation feature####### ################################## def get_verb_tense_frequencies(lyric_lines): freq = dict() freq['present'] = 0 freq['future'] = 0 freq['past'] = 0 verbs_no = 0 for line in lyric_lines: doc = nlp(line) for i in range(len(doc)): token = doc[i] if token.pos_ == 'VERB' and token.tag_ != 'MD': verbs_no += 1 if 'present' in spacy.explain(token.tag_): freq['present'] += 1 elif 'past' in spacy.explain(token.tag_): freq['past'] += 1 elif token.pos_ == 'VERB' and token.tag_ == 'MD' and token.text.lower() == 'will': if i < len(doc) - 1: i += 1 next_token = doc[i] if next_token is not None and next_token.text == 'VB': verbs_no += 1 freq['future'] += 1 if verbs_no > 0: for key, value in freq.items(): freq[key] = value/verbs_no return freq def get_polarity_and_subjectivity(lyric_lines): text = '\n'.join(lyric_lines) opinion = TextBlob(text) sentiment = opinion.sentiment return (sentiment.polarity, sentiment.subjectivity) ################################## ########Emotion features########## ################################## #import emoclassify as clf # #def get_emotion_vector(lyric, title, modelpath='emodetect.h5'): # return clf.classify(0, '', title, lyric_content = html.unescape(lyric).replace('<br>', '\n')) def representations_from(lyric): """Compute different representations of lyric: tree (with paragraphs), lines, tokens""" lyric_tree = tree_structure(lyric) lyric_lines = line_structure(lyric_tree) lyric_tokens = token_structure(lyric_tree) return lyric_tree, lyric_lines, lyric_tokens def feat_vect_from(feature_list): """Assuming a list of features of the lyric""" feat_vect = [] feat_vect.append(np.median(feature_list)) feat_vect.append(np.std(feature_list)) feat_vect.append(list_span(feature_list)) return feat_vect def extend_feat_vect(feat_vect, feature_list): feat_vect.extend(feat_vect_from(feature_list)) return feat_vect def feature_vector_from(lyric, title): lyric_tree, lyric_lines, lyric_tokens = representations_from(lyric) # lump everything in a single feature vector feat_vect = [] # segmentation features feat_vect = extend_feat_vect(feat_vect, segment_lengths(lyric_tree)) # stylometric features feat_vect.append(type_token_ratio(lyric_tokens)) ln_lengths_chars = line_lengths_in_chars(lyric_lines) # line count feat_vect.append(len(ln_lengths_chars)) feat_vect = extend_feat_vect(feat_vect, ln_lengths_chars) feat_vect = extend_feat_vect(feat_vect, line_lengths_in_tokens(lyric_lines)) feat_vect.append(get_rhymes(lyric_lines)) # orientation features feat_vect.extend(get_polarity_and_subjectivity(lyric_lines)) # emotion features #emo = get_emotion_vector(lyric, title) #feat_vect.extend(get_emotion_vector(lyric, title)) #features using expensive nlp(.) calls #feat_vect.extend(pos_tag_distribution(lyric_lines).values()) #feat_vect.extend(get_verb_tense_frequencies(lyric_lines).values()) #feat_vect.append(get_echoisms(lyric_lines)) return feat_vect def feature_vectors_from(many_lyrics: list, many_titles: list) -> np.ndarray: many_count = len(many_lyrics) first_feat_vect = feature_vector_from(many_lyrics.iloc[0], many_titles.iloc[0]) feat_vects = np.empty((many_count, len(first_feat_vect)), dtype=object) feat_vects[0] = first_feat_vect for i in range(1, many_count): feat_vects[i] = feature_vector_from(many_lyrics.iloc[i], many_titles.iloc[i]) if i % 100 == 0: print('Progress:', i, 'of', many_count, '(' + str(round(i/many_count*100, 1)) + '%)') return feat_vects # Define subset to compute features on mpd_with_lyrics_subset = mpd_with_lyrics.iloc[:10] all_uris = mpd_with_lyrics_subset['spotify_track_uri'] all_lyrics = mpd_with_lyrics_subset['lyrics'] all_titles = mpd_with_lyrics_subset['title'] assert len(all_uris) == len(all_lyrics) == len(all_titles) matrix = feature_vectors_from(all_lyrics, all_titles) print(matrix.shape) #Put back into dataframe fvec = {} for row in range(matrix.shape[0]): fvec[all_uris.iloc[row]] = matrix[row, :] xf = pd.DataFrame(list(fvec.items()), columns=['spotify_track_uri', 'feature_vector']) xf.head() write_file(content=xf, fl='/Users/mic.fell/Documents/Jupyter Orbit/resources/recsys_challenge_2018/mpd_ids_english_features.csv') xx = read_file('/Users/mic.fell/Documents/Jupyter Orbit/resources/recsys_challenge_2018/mpd_ids_english_features.pickle') xx xx.iloc[567].feature_vector.shape from time import time mpd_limited = mpd_with_lyrics_subset all_lyrics, all_titles = (mpd_limited['lyrics'], mpd_limited['title']) t = time() matrix = feature_vectors_from(all_lyrics, all_titles) print('Lyrics count :', len(all_lyrics)) time_taken = time()-t print('Time taken [s] :', round(time_taken, 2)) print('Time / lyric [s] :', round(time_taken / len(all_lyrics), 3)) print('Time / 416k [h/m] :', round(time_taken / len(all_lyrics) * 416000 / 60 / 60, 1), '/', round(time_taken / len(all_lyrics) * 416000 / 60, 1)) t = time() scaled_matrix = apply_to_columns(min_max_scaler, matrix) print('Scaling', matrix.shape, ':', round(time() - t, 3)) ```
github_jupyter
``` import os import sys from os.path import dirname proj_path = dirname(os.getcwd()) sys.path.append(proj_path) from typing import Mapping import torch import torch.distributions as D import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import tqdm from absl import app from absl import flags from absl import logging from oatomobile.baselines.torch.dim.model import ImitativeModel from oatomobile.datasets.carla import CARLADataset from oatomobile.torch import types from oatomobile.torch.loggers import TensorBoardLogger from oatomobile.torch.savers import Checkpointer import numpy as np import ray.train as train from ray.train import Trainer, TorchConfig from ray.train.callbacks import JsonLoggerCallback, TBXLoggerCallback from torch.nn.parallel import DistributedDataParallel from torch.utils.data import DistributedSampler import ray ray_address = "127.0.0.1" num_workers = 4 smoke_test = True dataset_dir = "nonlocalexamples" output_dir = "models" batch_size = 512 num_epochs = 3 save_model_frequency = 4 learning_rate = 1e-3 num_timesteps_to_keep = 4 weight_decay = 0.0 clip_gradients = False def train_func(confg): batch_size = config.get("batch_size", 32) hidden_size = config.get("hidden_size", 1) lr = config.get("lr", 1e-2) epochs = config.get("epochs", 3) weight_decay = config.get("weight_decay", 0) # # Creates the necessary output directory. # os.makedirs(output_dir, exist_ok=True) # log_dir = os.path.join(output_dir, "logs") # os.makedirs(log_dir, exist_ok=True) # ckpt_dir = os.path.join(output_dir, "ckpts") # os.makedirs(ckpt_dir, exist_ok=True) # Initializes the model and its optimizer. output_shape = [num_timesteps_to_keep, 2] model = ImitativeModel(output_shape=output_shape).to(device) model = DistributedDataParallel(model) optimizer = optim.Adam( model.parameters(), lr=lr, weight_decay=weight_decay, ) # writer = TensorBoardLogger(log_dir=log_dir) # checkpointer = Checkpointer(model=model, ckpt_dir=ckpt_dir) def transform(batch: Mapping[str, types.Array]) -> Mapping[str, torch.Tensor]: """Preprocesses a batch for the model. Args: batch: (keyword arguments) The raw batch variables. Returns: The processed batch. """ # Sends tensors to `device`. batch = {key: tensor.to(device) for (key, tensor) in batch.items()} # Preprocesses batch for the model. batch = model.transform(batch) return batch # Setups the dataset and the dataloader. modalities = ( "lidar", "is_at_traffic_light", "traffic_light_state", "player_future", "velocity", ) dataset_train = CARLADataset.as_torch( dataset_dir=os.path.join(dataset_dir, "train"), modalities=modalities, ) dataloader_train = torch.utils.data.DataLoader( dataset_train, batch_size=batch_size, shuffle=True, num_workers=5, ) dataset_val = CARLADataset.as_torch( dataset_dir=os.path.join(dataset_dir, "val"), modalities=modalities, ) dataloader_val = torch.utils.data.DataLoader( dataset_val, batch_size=batch_size * 5, shuffle=True, num_workers=5, ) # Theoretical limit of NLL. nll_limit = -torch.sum( # pylint: disable=no-member D.MultivariateNormal( loc=torch.zeros(output_shape[-2] * output_shape[-1]), # pylint: disable=no-member scale_tril=torch.eye(output_shape[-2] * output_shape[-1]) * # pylint: disable=no-member noise_level, # pylint: disable=no-member ).log_prob(torch.zeros(output_shape[-2] * output_shape[-1]))) # pylint: disable=no-member def train_step( model: ImitativeModel, optimizer: optim.Optimizer, batch: Mapping[str, torch.Tensor], clip: bool = False, ) -> torch.Tensor: """Performs a single gradient-descent optimisation step.""" # Resets optimizer's gradients. optimizer.zero_grad() # Perturb target. y = torch.normal( # pylint: disable=no-member mean=batch["player_future"][..., :2], std=torch.ones_like(batch["player_future"][..., :2]) * noise_level, # pylint: disable=no-member ) # Forward pass from the model. z, _ = model._params( velocity=batch["velocity"], visual_features=batch["visual_features"], is_at_traffic_light=batch["is_at_traffic_light"], traffic_light_state=batch["traffic_light_state"], ) _, log_prob, logabsdet = model._decoder._inverse(y=y, z=z) # Calculates loss (NLL). loss = -torch.mean(log_prob - logabsdet, dim=0) # pylint: disable=no-member # Backward pass. loss.backward() # Clips gradients norm. if clip: torch.nn.utils.clip_grad_norm(model.parameters(), 1.0) # Performs a gradient descent step. optimizer.step() return loss def train_epoch( model: ImitativeModel, optimizer: optim.Optimizer, dataloader: torch.utils.data.DataLoader, ) -> torch.Tensor: """Performs an epoch of gradient descent optimization on `dataloader`.""" model.train() loss = 0.0 with tqdm.tqdm(dataloader) as pbar: for batch in pbar: # Prepares the batch. batch = transform(batch) # Performs a gradien-descent step. loss += train_step(model, optimizer, batch, clip=clip_gradients) return loss / len(dataloader) def evaluate_step( model: ImitativeModel, batch: Mapping[str, torch.Tensor], ) -> torch.Tensor: """Evaluates `model` on a `batch`.""" # Forward pass from the model. z, _ = model._params( velocity=batch["velocity"], visual_features=batch["visual_features"], is_at_traffic_light=batch["is_at_traffic_light"], traffic_light_state=batch["traffic_light_state"], ) _, log_prob, logabsdet = model._decoder._inverse( y=batch["player_future"][..., :2], z=z, ) # Calculates loss (NLL). loss = -torch.mean(log_prob - logabsdet, dim=0) # pylint: disable=no-member return loss def evaluate_epoch( model: ImitativeModel, dataloader: torch.utils.data.DataLoader, ) -> torch.Tensor: """Performs an evaluation of the `model` on the `dataloader.""" model.eval() loss = 0.0 with tqdm.tqdm(dataloader) as pbar: for batch in pbar: # Prepares the batch. batch = transform(batch) # Accumulates loss in dataset. with torch.no_grad(): loss += evaluate_step(model, batch) return loss / len(dataloader) results = [] for _ in range(epochs): # Trains model on whole training dataset, and writes on `TensorBoard`. loss_train = train_epoch(model, optimizer, dataloader_train) # write(model, dataloader_train, writer, "train", loss_train, epoch) # Evaluates model on whole validation dataset, and writes on `TensorBoard`. loss_val = evaluate_epoch(model, dataloader_val) # write(model, dataloader_val, writer, "val", loss_val, epoch) # # Checkpoints model weights. # if epoch % save_model_frequency == 0: # checkpointer.save(epoch) # train_epoch(train_loader, model, loss_fn, optimizer) # result = validate_epoch(validation_loader, model, loss_fn) train.report(**result) results.append(result) return results def train_carla(): trainer = Trainer(TorchConfig(backend="gloo"), num_workers=num_workers) config = {"lr": learning_rate, "hidden_size": 1, "batch_size": batch_size, "epochs": num_epochs} trainer.start() results = trainer.run( train_func, config, callbacks=[JsonLoggerCallback(), TBXLoggerCallback()]) trainer.shutdown() print(results) return results if __name__ == "__main__": # Start Ray Cluster if smoke_test: ray.init(num_cpus=2) else: ray.init(address=address) # Train carla train_carla() ```
github_jupyter
# Image Classification Neo Compilation Example - Local Mode This notebook shows an intermediate step in the process of developing an Edge image classification algorithm. ## Notebook Setup ``` %matplotlib inline import time import os #os.environ["CUDA_VISIBLE_DEVICES"]="0" import tensorflow as tf import numpy as np import cv2 from tensorflow.python.client import device_lib tf.__version__ ``` ## Helper Functions and scripts ``` def get_img(img_path): img = cv2.imread(img_path) img = cv2.resize(img.astype(float), (224, 224)) #resize imgMean = np.array([104, 117, 124], np.float) img -= imgMean #subtract image mean return img def get_label_encode(class_id): enc = np.zeros((257),dtype=int) enc[class_id] = 1 return enc def freeze_graph(model_dir, output_node_names): """Extract the sub graph defined by the output nodes and convert all its variables into constant Args: model_dir: the root folder containing the checkpoint state file output_node_names: a string, containing all the output node's names, comma separated """ if not tf.gfile.Exists(model_dir): raise AssertionError( "Export directory doesn't exists. Please specify an export " "directory: %s" % model_dir) if not output_node_names: print("You need to supply the name of a node to --output_node_names.") return -1 # We retrieve our checkpoint fullpath checkpoint = tf.train.get_checkpoint_state(model_dir) input_checkpoint = checkpoint.model_checkpoint_path # We precise the file fullname of our freezed graph absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1]) output_graph = absolute_model_dir + "/frozen_model.pb" # We clear devices to allow TensorFlow to control on which device it will load operations clear_devices = True # We start a session using a temporary fresh Graph with tf.Session(graph=tf.Graph()) as sess: # We import the meta graph in the current default Graph saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices) # We restore the weights saver.restore(sess, input_checkpoint) # We use a built-in TF helper to export variables to constants output_graph_def = tf.graph_util.convert_variables_to_constants( sess, # The session is used to retrieve the weights tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes output_node_names.split(",") # The output node names are used to select the usefull nodes ) # Finally we serialize and dump the output graph to the filesystem with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the final graph." % len(output_graph_def.node)) return output_graph_def class VGG(object): """alexNet model""" def __init__(self, n_classes, batch_size=None): self.NUM_CLASSES = n_classes self.BATCH_SIZE = batch_size self.x = tf.placeholder(tf.float32, [None, 224, 224, 3]) self.y = tf.placeholder(tf.float32, [None, self.NUM_CLASSES]) self.buildCNN() def buildCNN(self): """build model""" input_layer = self.x conv1_1 = tf.layers.conv2d( input_layer, filters=64, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv1_1' ) conv1_2 = tf.layers.conv2d( conv1_1, filters=64, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv1_2' ) pool1 = tf.layers.max_pooling2d(conv1_2, pool_size=(2, 2), strides=(2, 2), padding='SAME', name='pool1') # conv2 conv2_1 = tf.layers.conv2d( pool1, filters=128, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv2_1' ) conv2_2 = tf.layers.conv2d( conv2_1, filters=128, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv2_2' ) pool2 = tf.layers.max_pooling2d(conv2_2, pool_size=(2, 2), strides=(2, 2), padding='SAME', name='pool2') # conv3 conv3_1 = tf.layers.conv2d( pool2, filters=256, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv3_1' ) conv3_2 = tf.layers.conv2d( conv3_1, filters=256, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv3_2' ) conv3_3 = tf.layers.conv2d( conv3_2, filters=256, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv3_3' ) pool3 = tf.layers.max_pooling2d(conv3_3, pool_size=(2, 2), strides=(2, 2), padding='SAME', name='pool3') # conv4 conv4_1 = tf.layers.conv2d( pool3, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv4_1' ) conv4_2 = tf.layers.conv2d( conv4_1, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv4_2' ) conv4_3 = tf.layers.conv2d( conv4_2, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv4_3' ) pool4 = tf.layers.max_pooling2d(conv4_3, pool_size=(2, 2), strides=(2, 2), padding='SAME', name='pool4') # conv5 conv5_1 = tf.layers.conv2d( pool4, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv5_1' ) conv5_2 = tf.layers.conv2d( conv5_1, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv5_2' ) conv5_3 = tf.layers.conv2d( conv5_2, filters=512, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, padding='SAME', name='conv5_3' ) pool5 = tf.layers.max_pooling2d(conv5_3, pool_size=(2, 2), strides=(2, 2), padding='SAME', name='pool5') #print('POOL5', pool5.shape) #CULPADO flatten = tf.layers.flatten(pool5, name='flatten') flatten = tf.reshape(pool5, [-1, 7*7*512]) fc1_relu = tf.layers.dense(flatten, units=4096, activation=tf.nn.relu, name='fc1_relu') fc2_relu = tf.layers.dense(fc1_relu, units=4096, activation=tf.nn.relu, name='fc2_relu') self.logits = tf.layers.dense(fc2_relu, units=self.NUM_CLASSES, name='fc3_relu') #fc3 = tf.nn.softmax(logits) print(self.logits.shape) # Return the complete AlexNet model return self.logits net = VGG(257) net.x, net.y, net.logits ``` ## Dataset The example is no longer on this URL. Now it has to be downloaded from Google Drive: https://drive.google.com/uc?id=1r6o0pSROcV1_VwT4oSjA2FBUSCWGuxLK ``` !conda install -c conda-forge -y gdown !mkdir -p ../data/Caltech256 import gdown url = "https://drive.google.com/uc?id=1r6o0pSROcV1_VwT4oSjA2FBUSCWGuxLK" destination = "../data/Caltech256/256_ObjectCategories.tar" gdown.download(url, destination, quiet=False) #!curl http://www.vision.caltech.edu/Image_Datasets/Caltech256/256_ObjectCategories.tar -o ../data/Caltech256/256_ObjectCategories.tar %%sh pushd ../data/Caltech256/ tar -xvf 256_ObjectCategories.tar popd import glob import random from sklearn.model_selection import train_test_split counter = 0 classes = {} all_image_paths = list(glob.glob('../data/Caltech256/256_ObjectCategories/*/*.jpg')) x = [] y = [] for i in all_image_paths: _,cat,fname = i.split('/')[3:] if classes.get(cat) is None: classes[cat] = counter counter += 1 x.append(i) y.append(classes.get(cat)) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42) ``` ## Training ``` # (6) Define model's cost and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=net.logits, labels=net.y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # (7) Defining evaluation metrics correct_prediction = tf.equal(tf.argmax(net.logits, 1), tf.argmax(net.y, 1)) accuracy_pct = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) * 100 # (8) initialize initializer_op = tf.global_variables_initializer() epochs = 1 batch_size = 128 test_batch_size = 256 # (9) Run with tf.Session() as session: session.run(initializer_op) print("Training for", epochs, "epochs.") # looping over epochs: for epoch in range(epochs): # To monitor performance during training avg_cost = 0.0 avg_acc_pct = 0.0 # loop over all batches of the epoch- 1088 records # batch_size = 128 is already defined n_batches = int(len(x_train) / batch_size) counter = 1 for i in range(n_batches): # Get the random int for batch #random_indices = np.random.randint(len(x_train), size=batch_size) # 1088 is the no of training set records pivot = i * batch_size feed = { net.x: [get_img(i) for i in x_train[pivot:pivot+batch_size]], net.y: [get_label_encode(i) for i in y_train[pivot:pivot+batch_size]] } # feed batch data to run optimization and fetching cost and accuracy: _, batch_cost, batch_acc = session.run([optimizer, cost, accuracy_pct], feed_dict=feed) # Print batch cost to see the code is working (optional) # print('Batch no. {}: batch_cost: {}, batch_acc: {}'.format(counter, batch_cost, batch_acc)) # Get the average cost and accuracy for all batches: avg_cost += batch_cost / n_batches avg_acc_pct += batch_acc / n_batches counter += 1 if counter % 50 == 0: print("Batch {}/{}: batch_cost={:.3f}, batch_acc={:.3f},avg_cost={:.3f},avg_acc={:.3f}".format( i,n_batches, batch_cost, batch_acc, avg_cost, avg_acc_pct )) # Get cost and accuracy after one iteration test_cost = cost.eval({net.x: [get_img(i) for i in x_test[:test_batch_size]], net.y: [get_label_encode(i) for i in y_test[:test_batch_size]]}) test_acc_pct = accuracy_pct.eval({net.x: [get_img(i) for i in x_test[:test_batch_size]], net.y: [get_label_encode(i) for i in y_test[:test_batch_size]]}) # output logs at end of each epoch of training: print("Epoch {}: Training Cost = {:.3f}, Training Acc = {:.2f} -- Test Cost = {:.3f}, Test Acc = {:.2f}"\ .format(epoch + 1, avg_cost, avg_acc_pct, test_cost, test_acc_pct)) # Getting Final Test Evaluation print('\n') print("Training Completed. Final Evaluation on Test Data Set.\n") test_cost = cost.eval({net.x: [get_img(i) for i in x_test[:test_batch_size]], net.y: [get_label_encode(i) for i in y_test[:test_batch_size]]}) test_accy_pct = accuracy_pct.eval({net.x: [get_img(i) for i in x_test[:test_batch_size]], net.y: [get_label_encode(i) for i in y_test[:test_batch_size]]}) print("Test Cost:", '{:.3f}'.format(test_cost)) print("Test Accuracy: ", '{:.2f}'.format(test_accy_pct), "%", sep='') print('\n') # Getting accuracy on Validation set val_cost = cost.eval({net.x: [get_img(i) for i in x_test[test_batch_size:test_batch_size*2]], net.y: [get_label_encode(i) for i in y_test[test_batch_size:test_batch_size*2]]}) val_acc_pct = accuracy_pct.eval({net.x: [get_img(i) for i in x_test[test_batch_size:test_batch_size*2]], net.y: [get_label_encode(i) for i in y_test[test_batch_size:test_batch_size*2]]}) print("Evaluation on Validation Data Set.\n") print("Evaluation Cost:", '{:.3f}'.format(val_cost)) print("Evaluation Accuracy: ", '{:.2f}'.format(val_acc_pct), "%", sep='') ``` ## Saving/exporting the model ``` !rm -rf vgg16/ exporter = tf.saved_model.builder.SavedModelBuilder('vgg16/model') saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) img = get_img('TestImage.jpg') batch = np.array([img for i in range(batch_size)]).reshape((batch_size,224,224,3)) print(batch.shape) x = net.x y = net.logits start_time = time.time() out = sess.run(y, feed_dict = {x: batch}) print("Elapsed time: {}".format(time.time() - start_time)) exporter.add_meta_graph_and_variables( sess, tags=[tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: tf.saved_model.signature_def_utils.predict_signature_def( inputs={"inputs": net.x}, outputs={"outputs": net.logits } ) }, strip_default_attrs=True) #exporter.save() saver.save(sess, 'vgg16/model/model') _ = freeze_graph('vgg16/model', 'fc3_relu/BiasAdd') !cd vgg16 && rm -f model.tar.gz && cd model && tar -czvf ../model.tar.gz frozen_model.pb import time import sagemaker import os import json import boto3 # Retrieve the default bucket sagemaker_session = sagemaker.Session() default_bucket = sagemaker_session.default_bucket() type(sagemaker_session) role=sagemaker.session.get_execution_role() job_prefix='VGG16' path='neo/%s' % job_prefix sm = boto3.client('sagemaker') !aws s3 cp vgg16/model.tar.gz s3://$default_bucket/$path/model.tar.gz target_device='ml_m5' # 'lambda'|'ml_m4'|'ml_m5'|'ml_c4'|'ml_c5'|'ml_p2'|'ml_p3'|'ml_g4dn'|'ml_inf1'|'jetson_tx1'|'jetson_tx2'|'jetson_nano'|'jetson_xavier'| # 'rasp3b'|'imx8qm'|'deeplens'|'rk3399'|'rk3288'|'aisage'|'sbe_c'|'qcs605'|'qcs603'|'sitara_am57x'|'amba_cv22'|'x86_win32'|'x86_win64' job_name="%s-%d" % (job_prefix, int(time.time())) sm.create_compilation_job( CompilationJobName=job_name, RoleArn=role, InputConfig={ 'S3Uri': "s3://%s/%s/model.tar.gz" % (default_bucket, path), 'DataInputConfig': '{"data":[1,224,224,3]}', 'Framework': 'TENSORFLOW' }, OutputConfig={ 'S3OutputLocation': "s3://%s/%s/" % (default_bucket, path), 'TargetDevice': target_device }, StoppingCondition={ 'MaxRuntimeInSeconds': 300 } ) print(job_name) default_bucket ``` ## NEO ``` !echo s3://$default_bucket/neo/VGG16/model-$target_device\.tar.gz !aws s3 cp s3://$default_bucket/neo/VGG16/model-$target_device\.tar.gz . !tar -tzvf model-$target_device\.tar.gz !rm -rf neo_test && mkdir neo_test !tar -xzvf model-$target_device\.tar.gz -C neo_test !ldd neo_test/compiled.so %%time import os import numpy as np import cv2 import time from dlr import DLRModel model_path='neo_test' imgMean = np.array([104, 117, 124], np.float) img = cv2.imread("TestImage.jpg") img = cv2.resize(img.astype(float), (224, 224)) # resize img -= imgMean #subtract image mean img = img.reshape((1, 224, 224, 3)) device = 'cpu' # Go, Raspberry Pi, go! model = DLRModel(model_path, dev_type=device) print(model.get_input_names()) def predict(img): start = time.time() input_data = {'Placeholder': img} out = model.run(input_data) return (out, time.time()-start) startTime = time.time() out = [predict(img)[1] for i in (range(1))] print("Elapsed time: {}".format((time.time() - start_time))) #top1 = np.argmax(out[0]) #prob = np.max(out) #print("Class: %d, probability: %f" % (top1, prob)) %matplotlib inline import matplotlib.pyplot as plt fig = plt.figure(figsize=(20,10)) ax = plt.axes() ax.plot(out) ```
github_jupyter
# Basic Distributions ### A. Taylan Cemgil ### Boğaziçi University, Dept. of Computer Engineering ### Notebook Summary * We review the notation and parametrization of densities of some basic distributions that are often encountered * We show how random numbers are generated using python libraries * We show some basic visualization methods such as displaying histograms # Sampling From Basic Distributions Sampling from basic distribution is easy using the numpy library. Formally we will write $x \sim p(X|\theta)$ where $\theta$ is the _parameter vector_, $p(X| \theta)$ denotes the _density_ of the random variable $X$ and $x$ is a _realization_, a particular draw from the density $p$. The following distributions are building blocks from which more complicated processes may be constructed. It is important to have a basic understanding of these distributions. ### Continuous Univariate * Uniform $\mathcal{U}$ * Univariate Gaussian $\mathcal{N}$ * Gamma $\mathcal{G}$ * Inverse Gamma $\mathcal{IG}$ * Beta $\mathcal{B}$ ### Discrete * Poisson $\mathcal{P}$ * Bernoulli $\mathcal{BE}$ * Binomial $\mathcal{BI}$ * Categorical $\mathcal{M}$ * Multinomial $\mathcal{M}$ ### Continuous Multivariate (todo) * Multivariate Gaussian $\mathcal{N}$ * Dirichlet $\mathcal{D}$ ### Continuous Matrix-variate (todo) * Wishart $\mathcal{W}$ * Inverse Wishart $\mathcal{IW}$ * Matrix Gaussian $\mathcal{N}$ ## Sampling from the standard uniform $\mathcal{U}(0,1)$ For generating a single random number in the interval $[0, 1)$ we use the notation $$ x_1 \sim \mathcal{U}(x; 0,1) $$ In python, this is implemented as ``` import numpy as np x_1 = np.random.rand() print(x_1) ``` We can also generate an array of realizations $x_i$ for $i=1 \dots N$, $$ x_i \sim \mathcal{U}(x; 0,1) $$ ``` import numpy as np N = 5 x = np.random.rand(N) print(x) ``` For large $N$, it is more informative to display an histogram of generated data: ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Number of realizations N = 50000 x = np.random.rand(N) plt.hist(x, bins=20) plt.xlabel('x') plt.ylabel('Count') plt.show() ``` $\newcommand{\indi}[1]{\left[{#1}\right]}$ $\newcommand{\E}[1]{\left\langle{#1}\right\rangle}$ We know that the density of the uniform distribution $\mathcal{U}(0,1)$ is $$ \mathcal{U}(x; 0,1) = \left\{ \begin{array}{cc} 1 & 0 \leq x < 1 \\ 0 & \text{otherwise} \end{array} \right. $$ or using the indicator notation $$ \mathcal{U}(x; 0,1) = \left[ x \in [0,1) \right] $$ #### Indicator function To write and manipulate discrete probability distributions in algebraic expression, the *indicator* function is useful: $$ \left[x\right] = \left\{ \begin{array}{cc} 1 & x\;\;\text{is true} \\ 0 & x\;\;\text{is false} \end{array} \right.$$ This notation is also known as the Iverson's convention. #### Aside: How to plot the density and the histogram onto the same plot? In one dimension, the histogram is simply the count of the data points that fall to a given interval. Mathematically, we have $j = 1\dots J$ intervals where $B_j = [b_{j-1}, b_j]$ and $b_j$ are bin boundries such that $b_0 < b_1 < \dots < b_J$. $$ h(x) = \sum_{j=1}^J \sum_{i=1}^N \indi{x \in B_j} \indi{x_i \in B_j} $$ This expression, at the first sight looks somewhat more complicated than it really is. The indicator product just encodes the logical condition $x \in B_j$ __and__ $x_i \in B_j$. The sum over $j$ is just a convenient way of writing the result instead of specifying the histogram as a case by case basis for each bin. It is important to get used to such nested sums. When the density $p(x)$ is given, the probability that a single realization is in bin $B_j$ is given by $$ \Pr\left\{x \in B_j\right\} = \int_{B_j} dx p(x) = \int_{-\infty}^{\infty} dx \indi{x\in B_j} p(x) = \E{\indi{x\in B_j}} $$ In other words, the probability is just the expectation of the indicator. The histogram can be written as follows $$ h(x) = \sum_{j=1}^J \indi{x \in B_j} \sum_{i=1}^N \indi{x_i \in B_j} $$ We define the counts at each bin as $$ c_j \equiv \sum_{i=1}^N \indi{x_i \in B_j} $$ If all bins have the same width, i.e., $b_j - b_{j-1} = \Delta$ for $\forall j$, and if $\Delta$ is sufficiently small we have $$ \E{\indi{x\in B_j}} \approx p(b_{j-1}+\Delta/2) \Delta $$ i.e., the probability is roughly the interval width times the density evaluated at the middle point of the bin. The expected value of the counts is $$ \E{c_j} = \sum_{i=1}^N \E{\indi{x_i \in B_j}} \approx N \Delta p(b_{j-1}+\Delta/2) $$ Hence, the density should be roughly $$ p(b_{j-1}+\Delta/2) \approx \frac{\E{c_j} }{N \Delta} $$ The $N$ term is intuitive but the $\Delta$ term is easily forgotten. When plotting the histograms on top of the corresponding densities, we should scale the normalized histogram ${ c_j }/{N}$ by dividing by $\Delta$. ``` N = 1000 # Bin width Delta = 0.02 # Bin edges b = np.arange(0 ,1+Delta, Delta) # Evaluate the density g = np.ones(b.size) # Draw the samples u = np.random.rand(N) counts,edges = np.histogram(u, bins=b) plt.bar(b[:-1], counts/N/Delta, width=Delta) #plt.hold(True) plt.plot(b, g, linewidth=3, color='y') #plt.hold(False) plt.show() ``` The __plt.hist__ function (calling __np.histogram__) can do this calculation automatically if the option normed=True. However, when the grid is not uniform, it is better to write your own code to be sure what is going on. ``` N = 1000 Delta = 0.05 b = np.arange(0 ,1+Delta, Delta) g = np.ones(b.size) u = np.random.rand(N) #plt.hold(True) plt.plot(b, g, linewidth=3, color='y') plt.hist(u, bins=b, normed=True) #plt.hold(False) plt.show() ``` # Continuous Univariate Distributions * Uniform $\mathcal{U}$ * Univariate Gaussian $\mathcal{N}$ $${\cal N}(x;\mu, v) = \frac{1}{\sqrt{2\pi v}} \exp\left(-\frac12 \frac{(x - \mu)^2}{v}\right) $$ * Gamma $\mathcal{G}$ $${\cal G}(\lambda; a, b) = \frac{b^a \lambda^{a-1}}{\Gamma(a)} \exp( - b \lambda)$$ * Inverse Gamma $\mathcal{IG}$ $${\cal IG}(v; \alpha, \beta) = \frac{\beta^\alpha}{\Gamma(\alpha) v^{\alpha+1}} \exp(- \frac{\beta}{v}) $$ * Beta $\mathcal{B}$ $${\cal B}(r; \alpha, \beta) = \frac{\Gamma(\alpha + \beta)}{\Gamma(\alpha) \Gamma(\beta) } r^{\alpha-1} (1-r)^{\beta-1}$$ In derivations, the distributions are often needed as building blocks. The following code segment prints the latex strings to be copied and pasted. $\DeclareMathOperator{\trace}{Tr}$ ``` from IPython.display import display, Math, Latex, HTML import notes_utilities as nut print('Gaussian') L = nut.pdf2latex_gauss(x=r'Z_{i,j}', m=r'\mu_{i,j}',v=r'l_{i,j}') display(HTML(nut.eqs2html_table(L))) print('Gamma') L = nut.pdf2latex_gamma(x=r'u', a=r'a',b=r'b') display(HTML(nut.eqs2html_table(L))) print('Inverse Gamma') L = nut.pdf2latex_invgamma(x=r'z', a=r'a',b=r'b') display(HTML(nut.eqs2html_table(L))) print('Beta') L = nut.pdf2latex_beta(x=r'\pi', a=r'\alpha',b=r'\beta') display(HTML(nut.eqs2html_table(L))) ``` We will illustrate two alternative ways for sampling from continuous distributions. - The first method has minimal dependence on the numpy and scipy libraries. This is initially the preferred method. Only random variable generators and the $\log \Gamma(x)$ (__gammaln__) function is used and nothing more. - The second method uses scipy. This is a lot more practical but requires knowing more about the internals of the library. ### Aside: The Gamma function $\Gamma(x)$ The gamma function $\Gamma(x)$ is the (generalized) factorial. - Defined by $$\Gamma(x) = \int_0^{\infty} t^{x-1} e^{-t}\, dt$$ - For integer $x$, $\Gamma(x) = (x-1)!$. Remember that for positive integers $x$, the factorial function can be defined recursively $x! = (x-1)! x $ for $x\geq 1$. - For real $x>1$, the gamma function satisfies $$ \Gamma(x+1) = \Gamma(x) x $$ - Interestingly, we have $$\Gamma(1/2) = \sqrt{\pi}$$ - Hence $$\Gamma(3/2) = \Gamma(1/2 + 1) = \Gamma(1/2) (1/2) = \sqrt{\pi}/2$$ - It is available in many numerical computation packages, in python it is available as __scipy.special.gamma__. - To compute $\log \Gamma(x)$, you should always use the implementation as __scipy.special.gammaln__. The gamma function blows up super-exponentially so numerically you should never evaluate $\log \Gamma(x)$ as ```python import numpy as np import scipy.special as sps np.log(sps.gamma(x)) # Don't sps.gammaln(x) # Do ``` - A related function is the Beta function $$B(x,y) = \int_0^{1} t^{x-1} (1-t)^{y-1}\, dt$$ - We have $$B(x,y) = \frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$$ - Both $\Gamma(x)$ and $B(x)$ pop up as normalizing constant of the gamma and beta distributions. #### Derivatives of $\Gamma(x)$ - <span style="color:red"> </span> The derivatives of $\log \Gamma(x)$ pop up quite often when fitting densities. The first derivative has a specific name, often called the digamma function or the psi function. $$ \Psi(x) \equiv \frac{d}{d x} \log \Gamma(x) $$ - It is available as __scipy.special.digamma__ or __scipy.special.psi__ - Higher order derivatives of the $\log \Gamma(x)$ function (including digamma itself) are available as __scipy.special.polygamma__ ``` import numpy as np import scipy.special as sps import matplotlib.pyplot as plt x = np.arange(0.1,5,0.01) f = sps.gammaln(x) df = sps.psi(x) # First derivative of the digamma function ddf = sps.polygamma(1,x) # sps.psi(x) == sps.polygamma(0,x) plt.figure(figsize=(8,10)) plt.subplot(3,1,1) plt.plot(x, f, 'r') plt.grid(True) plt.xlabel('x') plt.ylabel('log Gamma(x)') plt.subplot(3,1,2) plt.grid(True) plt.plot(x, df, 'b') plt.xlabel('x') plt.ylabel('Psi(x)') plt.subplot(3,1,3) plt.plot(x, ddf, 'k') plt.grid(True) plt.xlabel('x') plt.ylabel('Psi\'(x)') plt.show() ``` #### Stirling's approximation An important approximation to the factorial is the famous Stirling's approximation \begin{align} n! \sim \sqrt{2 \pi n}\left(\frac{n}{e}\right)^n \end{align} \begin{align} \log \Gamma(x+1) \approx \frac{1}{2}\log(2 \pi) + x \log(x) - \frac{1}{2} \log(x) \end{align} ``` import matplotlib.pylab as plt import numpy as np from scipy.special import polygamma from scipy.special import gammaln as loggamma from scipy.special import psi x = np.arange(0.001,6,0.001) ylim = [-1,8] xlim = [-1,6] plt.plot(x, loggamma(x), 'b') stir = x*np.log(x)-x +0.5*np.log(2*np.pi*x) plt.plot(x+1, stir,'r') plt.hlines(0,0,8) plt.vlines([0,1,2],ylim[0],ylim[1],linestyles=':') plt.hlines(range(ylim[0],ylim[1]),xlim[0],xlim[1],linestyles=':',colors='g') plt.ylim(ylim) plt.xlim(xlim) plt.legend([r'\log\Gamma(x)',r'\log(x-1)'],loc=1) plt.xlabel('x') plt.show() ``` # Sampling from Continuous Univariate Distributions ## Sampling using numpy.random ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.special import gammaln def plot_histogram_and_density(N, c, edges, dx, g, title='Put a title'): ''' N : Number of Datapoints c : Counts, as obtained from np.histogram function edges : bin edges, as obtained from np.histogram dx : The bin width g : Density evaluated at the points given in edges title : for the plot ''' plt.bar(edges[:-1], c/N/dx, width=dx) # plt.hold(True) plt.plot(edges, g, linewidth=3, color='y') # plt.hold(False) plt.title(title) def log_gaussian_pdf(x, mu, V): return -0.5*np.log(2*np.pi*V) -0.5*(x-mu)**2/V def log_gamma_pdf(x, a, b): return (a-1)*np.log(x) - b*x - gammaln(a) + a*np.log(b) def log_invgamma_pdf(x, a, b): return -(a+1)*np.log(x) - b/x - gammaln(a) + a*np.log(b) def log_beta_pdf(x, a, b): return - gammaln(a) - gammaln(b) + gammaln(a+b) + np.log(x)*(a-1) + np.log(1-x)*(b-1) N = 1000 # Univariate Gaussian mu = 2 # mean V = 1.2 # Variance x_normal = np.random.normal(mu, np.sqrt(V), N) dx = 10*np.sqrt(V)/50 x = np.arange(mu-5*np.sqrt(V) ,mu+5*np.sqrt(V),dx) g = np.exp(log_gaussian_pdf(x, mu, V)) #g = scs.norm.pdf(x, loc=mu, scale=np.sqrt(V)) c,edges = np.histogram(x_normal, bins=x) plt.figure(num=None, figsize=(16, 5), dpi=80, facecolor='w', edgecolor='k') plt.subplot(2,2,1) plot_histogram_and_density(N, c, x, dx, g, 'Gaussian') ## Gamma # Shape a = 1.2 # inverse scale b = 30 # Generate unit scale first than scale with inverse scale parameter b x_gamma = np.random.gamma(a, 1, N)/b dx = np.max(x_gamma)/500 x = np.arange(dx, 250*dx, dx) g = np.exp(log_gamma_pdf(x, a, b)) c,edges = np.histogram(x_gamma, bins=x) plt.subplot(2,2,2) plot_histogram_and_density(N, c, x, dx, g, 'Gamma') ## Inverse Gamma a = 3.5 b = 0.2 x_invgamma = b/np.random.gamma(a, 1, N) dx = np.max(x_invgamma)/500 x = np.arange(dx, 150*dx, dx) g = np.exp(log_invgamma_pdf(x,a,b)) c,edges = np.histogram(x_invgamma, bins=x) plt.subplot(2,2,3) plot_histogram_and_density(N, c, x, dx, g, 'Inverse Gamma') ## Beta a = 0.5 b = 1 x_beta = np.random.beta(a, b, N) dx = 0.01 x = np.arange(dx, 1, dx) g = np.exp(log_beta_pdf(x, a, b)) c,edges = np.histogram(x_beta, bins=x) plt.subplot(2,2,4) plot_histogram_and_density(N, c, x, dx, g, 'Beta') plt.show() ``` ## Sampling using scipy.stats ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.stats as scs N = 2000 # Univariate Gaussian mu = 2 # mean V = 1.2 # Variance rv_normal = scs.norm(loc=mu, scale=np.sqrt(V)) x_normal = rv_normal.rvs(size=N) dx = 10*np.sqrt(V)/50 x = np.arange(mu-5*np.sqrt(V) ,mu+5*np.sqrt(V),dx) g = rv_normal.pdf(x) c,edges = np.histogram(x_normal, bins=x) plt.figure(num=None, figsize=(16, 5), dpi=80, facecolor='w', edgecolor='k') plt.subplot(2,2,1) plot_histogram_and_density(N, c, x, dx, g, 'Gaussian') ## Gamma a = 3.2 b = 30 # The following is equivalent to our parametrization of gamma, note the 1/b term rv_gamma = scs.gamma(a, scale=1/b) x_gamma = rv_gamma.rvs(N) dx = np.max(x_gamma)/500 x = np.arange(0, 250*dx, dx) g = rv_gamma.pdf(x) c,edges = np.histogram(x_gamma, bins=x) plt.subplot(2,2,2) plot_histogram_and_density(N, c, x, dx, g, 'Gamma') ## Inverse Gamma a = 3.5 b = 0.2 # Note the b term rv_invgamma = scs.invgamma(a, scale=b) x_invgamma = rv_invgamma.rvs(N) dx = np.max(x_invgamma)/500 x = np.arange(dx, 150*dx, dx) g = rv_invgamma.pdf(x) c,edges = np.histogram(x_invgamma, bins=x) plt.subplot(2,2,3) plot_histogram_and_density(N, c, x, dx, g, 'Inverse Gamma') ## Beta a = 0.7 b = 0.8 rv_beta = scs.beta(a, b) x_beta = rv_beta.rvs(N) dx = 0.02 x = np.arange(0, 1+dx, dx) g = rv_beta.pdf(x) c,edges = np.histogram(x_beta, bins=x) plt.subplot(2,2,4) plot_histogram_and_density(N, c, x, dx, g, 'Beta') plt.show() ``` # Sampling from Discrete Densities * Bernoulli $\mathcal{BE}$ $$ {\cal BE}(r; w) = w^r (1-w)^{1-r} \;\; \text{if} \; r \in \{0, 1\} $$ * Binomial $\mathcal{BI}$ $${\cal BI}(r; L, w) = \binom{L}{r, (L-r)} w^r (1-w)^{L-r} \;\; \text{if} \; r \in \{0, 1, \dots, L\} $$ Here, the binomial coefficient is defined as $$ \binom{L}{r, (L-r)} = \frac{N!}{r!(L-r)!} $$ Note that $$ {\cal BE}(r; w) = {\cal BI}(r; L=1, w) $$ * Poisson $\mathcal{PO}$, with intensity $\lambda$ $${\cal PO}(x;\lambda) = \frac{e^{-\lambda} \lambda^x}{x!} = \exp(x \log \lambda - \lambda - \log\Gamma(x+1)) $$ Given samples on nonnegative integers, we can obtain histograms easily using __np.bincount__. ```python c = np.bincount(samples) ``` The functionality is equivalent to the following sniplet, while implementation is possibly different and more efficient. ```python upper_bound = np.max() c = np.zeros(upper_bound+1) for i in samples: c[i] += 1 ``` ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np def plot_histogram_and_pmf(N, c, domain, dx, g, title='Put a title'): ''' N : Number of Datapoints c : Counts, as obtained from np.bincount function domain : integers for each c, same size as c dx : The bin width g : Density evaluated at the points given in edges title : for the plot ''' plt.bar(domain-dx/2, c/N, width=dx) # plt.hold(True) plt.plot(domain, g, 'ro:', linewidth=3, color='y') # plt.hold(False) plt.title(title) def log_poisson_pdf(x, lam): return -lam + x*np.log(lam) - gammaln(x+1) def log_bernoulli_pdf(r, pr): return r*np.log(pr) + (1-r)*np.log(1 - pr) def log_binomial_pdf(r, pr, L): return gammaln(L+1) - gammaln(r+1) - gammaln(L-r+1) + r*np.log(pr) + (L-r)*np.log(1 - pr) N = 100 pr = 0.8 # For plots bin_width = 0.3 # Bernoulli L = 1 x_bern = np.random.binomial(n=L, p=pr, size=N) c = np.bincount(x_bern, minlength=L+1) g = np.exp(log_bernoulli_pdf(np.arange(L+1), pr)) plt.figure(figsize=(20,4)) plt.subplot(1,3,1) plot_histogram_and_pmf(N, c, np.arange(L+1), bin_width, g, 'Bernoulli') plt.xticks([0,1]) # Binomial L = 10 pr = 0.7 x_binom = np.random.binomial(n=L, p=pr, size=N) c = np.bincount(x_binom, minlength=L+1) g = np.exp(log_binomial_pdf(np.arange(L+1), pr, L)) plt.subplot(1,3,2) plot_histogram_and_pmf(N, c, np.arange(L+1), bin_width, g, 'Binomial') plt.xticks(np.arange(L+1)) # Poisson intensity = 10.5 x_poiss = np.random.poisson(intensity, size =N ) c = np.bincount(x_poiss) x = np.arange(len(c)) g = np.exp(log_poisson_pdf(x, intensity)) plt.subplot(1,3,3) plot_histogram_and_pmf(N, c, x, bin_width, g, 'Poisson') ``` ## Bernoulli, Binomial, Categorical and Multinomial Distributions The Bernoulli and Binomial distributions are quite simple and well known distributions on small integers, so it may come as a surprise that they have another, less obvious but arguably more useful representation as discrete multivariate densities. This representation makes the link to categorical distributions where there are more than two possible outcomes. Finally, all Bernoulli, Binomial or Categorical distributions are special cases of Multinomial distribution. ### Bernoulli Recall the Bernoulli distribution $r \in \{0, 1\}$ $$ {\cal BE}(r; w) = w^r (1-w)^{1-r} $$ We will define $\pi_0 = 1-w$ and $\pi_1 = w$, such that $\pi_0 + \pi_1 = 1$. The parameter vector is $\pi = (\pi_0, \pi_1)$ We will also introduce a positional encoding such that \begin{eqnarray} r = 0 & \Rightarrow & s = (1, 0) \\ r = 1 & \Rightarrow & s = (0, 1) \end{eqnarray} In other words $s = (s_0, s_1)$ is a 2-dimensional vector where $$s_0, s_1 \in \{0,1\}\;\text{and}\; s_0 + s_1 = 1$$ We can now write the Bernoulli density $$ p(s | \pi) = \pi_0^{s_0} \pi_1^{s_1} $$ ### Binomial Similarly, recall the Binomial density where $r \in \{0, 1, \dots, L\}$ $${\cal BI}(r; L, w) = \binom{L}{r, (L-r)} w^r (1-w)^{L-r} $$ We will again define $\pi_0 = 1-w$ and $\pi_1 = w$, such that $\pi_0 + \pi_1 = 1$. The parameter vector is $\pi = (\pi_0, \pi_1)$ \begin{eqnarray} r = 0 & \Rightarrow & s = (L, 0) \\ r = 1 & \Rightarrow & s = (L-1, 1)\\ r = 2 & \Rightarrow & s = (L-2, 2)\\ \dots \\ r = L & \Rightarrow & s = (0, L) \end{eqnarray} where $s = (s_0, s_1)$ is a 2-dimensional vector where $$s_0, s_1 \in \{0,\dots,L\} \;\text{and}\; s_0 + s_1 = L$$ We can now write the Binomial density as $$ p(s | \pi) = \binom{L}{s_0, s_1} \pi_0^{s_0} \pi_1^{s_1} $$ ### Categorical (Multinouilli) One of the advantages of this new notation is that we can write the density even if the outcomes are not numerical. For example, the result of a single coin flip experiment when $r \in \{$ 'Tail', 'Head' $\}$ where the probability of 'Tail' is $w$ can be written as $$ p(r | w) = w^{\indi{r=\text{'Tail'}}} (1-w)^{\indi{r=\text{'Head'}}} $$ We define $s_0 = \indi{r=\text{'Head'}}$ and $s_1 = \indi{r=\text{'Tail'}}$, then the density can be written in the same form as $$ p(s | \pi) = \pi_0^{s_0} \pi_1^{s_1} $$ where $\pi_0 = 1-w$ and $\pi_1 = w$. More generally, when $r$ is from a set with $K$ elements, i.e., $r \in R = \{ v_0, v_1, \dots, v_{K-1} \}$ with probability of the event $r = v_k$ given as $\pi_k$, we define $s = (s_0, s_1, \dots, s_{K-1})$ for $k=0,\dots, K-1$ $$ s_k = \indi{r=v_k} $$ Note that by construction, we have $\sum_k s_k = 1$. The resulting density, known as the Categorical density, can be writen as $$ p(s|\pi) = \pi_0^{s_0} \pi_1^{s_1} \dots \pi_{K-1}^{s_{K-1}} $$ ### Multinomial When drawing from a categorical distribution, one chooses a single category from $K$ options with given probabilities. A standard model for this is placing a single ball into $K$ different bins. The vector $s = (s_0, s_1, \dots,s_k, \dots, s_{K-1})$ represents how many balls eack bin $k$ contains. Now, place $L$ balls instead of one into $K$ bins with placing each ball idependently into bin $k$ where $k \in\{0,\dots,K-1\}$ with the probability $\pi_k$. The multinomial is the joint distribution of $s$ where $s_k$ is the number of balls placed into bin $k$. The density will be denoted as $${\cal M}(s; L, \pi) = \binom{L}{s_0, s_1, \dots, s_{K-1}}\prod_{k=0}^{K-1} \pi_k^{s_k} $$ Here $\pi \equiv [\pi_0, \pi_2, \dots, \pi_{K-1} ]$ is the probability vector and $L$ is referred as the _index parameter_. Clearly, we have the normalization constraint $ \sum_k \pi_k = 1$ and realization of the counts $s$ satisfy $ \sum_k s_k = L $. Here, the _multinomial_ coefficient is defined as $$\binom{L}{s_0, s_1, \dots, s_{K-1}} = \frac{L!}{s_0! s_1! \dots s_{K-1}!}$$ Binomial, Bernoulli and Categorical distributions are all special cases of the Multinomial distribution, with a suitable representation. The picture is as follows: ~~~ |Balls/Bins | $2$ Bins | $K$ Bins | |-------- | -------- | ---------| | $1$ Ball | Bernoulli ${\cal BE}$ | Categorical ${\cal C}$ | |-------- | -------- | ---------| | $L$ Balls | Binomial ${\cal BI}$ | Multinomial ${\cal M}$ | ~~~ Murphy calls the categorical distribution ($1$ Ball, $K$ Bins) as the Multinoulli. This is non-standard but logical (and somewhat cute). It is common to consider Bernoulli and Binomial as scalar random variables. However, when we think of them as special case of a Multinomial it is better to think of them as bivariate, albeit degenerate, random variables, as illustrated in the following cell along with an alternative visualization. ``` # The probability parameter pr = 0.3 fig = plt.figure(figsize=(16,50), edgecolor=None) maxL = 12 plt.subplot(maxL-1,2,1) plt.grid(False) # Set up the scalar binomial density as a bivariate density for L in range(1,maxL): r = np.arange(L+1) p = np.exp(log_binomial_pdf(r, pr=pr, L=L)) A = np.zeros(shape=(13,13)) for s in range(L): s0 = s s1 = L-s A[s0, s1] = p[s] #plt.subplot(maxL-1,2,2*L-1) # plt.bar(r-0.25, p, width=0.5) # ax.set_xlim(-1,maxL) # ax.set_xticks(range(0,maxL)) if True: plt.subplot(maxL-1,2,2*L-1) plt.barh(bottom=r-0.25, width=p, height=0.5) ax2 = fig.gca() pos = ax2.get_position() pos2 = [pos.x0, pos.y0, 0.04, pos.height] ax2.set_position(pos2) ax2.set_ylim(-1,maxL) ax2.set_yticks(range(0,maxL)) ax2.set_xlim([0,1]) ax2.set_xticks([0,1]) plt.ylabel('s1') ax2.invert_xaxis() plt.subplot(maxL-1,2,2*L) plt.imshow(A, interpolation='nearest', origin='lower',cmap='gray_r',vmin=0,vmax=0.7) plt.xlabel('s0') ax1 = fig.gca() pos = ax1.get_position() pos2 = [pos.x0-0.45, pos.y0, pos.width, pos.height] ax1.set_position(pos2) ax1.set_ylim(-1,maxL) ax1.set_yticks(range(0,maxL)) ax1.set_xlim(-1,maxL) ax1.set_xticks(range(0,maxL)) plt.show() ``` The following cell illustrates sampling from the Multinomial density. ``` # Number of samples sz = 3 # Multinomial p = np.array([0.3, 0.1, 0.1, 0.5]) K = len(p) # number of Bins L = 20 # number of Balls print('Multinomial with number of bins K = {K} and Number of balls L = {L}'.format(K=K,L=L)) print(np.random.multinomial(L, p, size=sz)) # Categorical L = 1 # number of Balls print('Categorical with number of bins K = {K} and a single ball L=1'.format(K=K)) print(np.random.multinomial(L, p, size=sz)) # Binomial p = np.array([0.3, 0.7]) K = len(p) # number of Bins = 2 L = 20 # number of Balls print('Binomial with two bins K=2 and L={L} balls'.format(L=L)) print(np.random.multinomial(L, p, size=sz)) # Bernoulli L = 1 # number of Balls p = np.array([0.3, 0.7]) K = len(p) # number of Bins = 2 print('Bernoulli, two bins and a single ball') print(np.random.multinomial(L, p, size=sz)) ```
github_jupyter
``` import sys if not './' in sys.path: sys.path.append('./') import pandas as pd import numpy as np import io import os from datetime import datetime from sklearn import preprocessing from sklearn.model_selection import train_test_split from envs.stocks_env_multiaction import Stocks_env from datasets import nyse import tensorflow as tf from IPython.display import clear_output import matplotlib.pyplot as plt %matplotlib inline #data = nyse.load_data('../data/') data, _, _ = nyse.load_data_with_industry('../data/') fit_data = data.drop(["symbol"], axis=1) scaler = preprocessing.StandardScaler().fit(fit_data) # Hyper params: input_shape = np.shape(data)[1]-1 lr = 1e-3 seed = 42 epochs = 8 batch_size = 256 # log save_directory = 'results/logreg/' date = datetime.now().strftime("%Y_%m_%d-%H:%M:%S") identifier = "logreg-" + date train_summary_writer = tf.summary.create_file_writer('results/summaries/logreg/train/' + identifier) test_summary_writer = tf.summary.create_file_writer('results/summaries/logreg/test/' + identifier) train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32) train_accuracy = tf.keras.metrics.BinaryAccuracy('train_accuracy') test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32) test_accuracy = tf.keras.metrics.BinaryAccuracy('test_accuracy') # format data symbols = data['symbol'].unique().tolist() X = [] Y = [] for sym in symbols: sym_data = scaler.transform(data.loc[data.symbol==sym].drop(["symbol"], axis=1)) for i in range(len(sym_data)-1): X.append(sym_data[i]) Y.append(1 if (sym_data[i][1]<sym_data[i+1][1]) else 0) X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=seed) train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)) test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test)) train_dataset = train_dataset.shuffle(60000).batch(batch_size) test_dataset = test_dataset.batch(batch_size) # initialize the model model = tf.keras.Sequential(tf.keras.layers.Dense(1, input_shape=(input_shape,), activation='sigmoid')) optimizer = tf.keras.optimizers.Adam(lr) loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True) def train_step(model, optimizer, x_train, y_train): with tf.GradientTape() as tape: predictions = model(x_train, training=True) loss = loss_object(y_train, predictions) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) train_loss(loss) train_accuracy(y_train, predictions) def test_step(model, x_test, y_test): predictions = model(x_test) loss = loss_object(y_test, predictions) test_loss(loss) test_accuracy(y_test, predictions) test_total_profits = [] for epoch in range(epochs): for (x_train, y_train) in train_dataset: train_step(model, optimizer, x_train, y_train) with train_summary_writer.as_default(): tf.summary.scalar('loss', train_loss.result(), step=epoch) tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch) for (x_test, y_test) in test_dataset: test_step(model, x_test, y_test) with test_summary_writer.as_default(): tf.summary.scalar('loss', test_loss.result(), step=epoch) tf.summary.scalar('accuracy', test_accuracy.result(), step=epoch) template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}' print (template.format(epoch+1, train_loss.result(), train_accuracy.result()*100, test_loss.result(), test_accuracy.result()*100)) # Reset metrics every epoch train_loss.reset_states() test_loss.reset_states() train_accuracy.reset_states() test_accuracy.reset_states() columns = data.columns[1:].tolist() weights = model.layers[0].get_weights() a = [(weights[0][i][0], columns[i]) for i in range(len(columns))] a window_size = 1 run_lenght = 10 initial_money = 100 train_test_ratio = 0.2 env = Stocks_env(data, window_size, run_lenght, batch_size=batch_size, train_test_ratio = train_test_ratio, test_seed=seed, initial_money=initial_money) batch_size = len(env.get_test_symbols()) def test_env(record_days=False): state = env.reset(training=False, batch_size=batch_size, run_lenght=run_lenght, initial_money=initial_money) state = np.reshape(state, (batch_size, len(columns))) done = False operation_array = [] days_array = [] rewards_array = [] total_profit = np.zeros(batch_size) while not done: actions = [] for result in model(state): buy = 1 if result>0 else 0 sell = 1 if result<0 else 0 actions += [[buy, sell]] next_state, reward, done, operations, day, profit = env.step(actions) state = next_state if record_days: operation_array.append(np.array(operations)) days_array.append(np.array(day)) rewards_array.append(np.array(reward)) mean_test_reward(np.array(reward)) total_profit += profit total_profit = total_profit/initial_money return operation_array, days_array, rewards_array, total_profit save_directory = 'results/test-all/' date = datetime.now().strftime("%Y_%m_%d-%H:%M:%S") identifier = "logreg-" + date test_summary_writer = tf.summary.create_file_writer('results/summaries/test/' + identifier) mean_test_reward = tf.keras.metrics.Mean(name='mean_test_reward') repeat = 100 test_total_profits = [] for i in range(repeat): print(i) operation_array, days_array, rewards_array, test_total_profit = test_env(record_days=True) test_total_profits.append(test_total_profit) with test_summary_writer.as_default(): tf.summary.scalar('mean_test_reward', mean_test_reward.result(), step=i) # serialize weights to HDF5 if not os.path.exists(save_directory): os.makedirs(save_directory) if not os.path.exists(save_directory+'operations/'): os.makedirs(save_directory+'operations/') if not os.path.exists(save_directory+'endingdays/'): os.makedirs(save_directory+'endingdays/') if not os.path.exists(save_directory+'rewards/'): os.makedirs(save_directory+'rewards/') if not os.path.exists(save_directory+'profits/'): os.makedirs(save_directory+'profits/') pd.DataFrame(operation_array).to_csv(save_directory+"operations/{}-iteration{}.csv".format(identifier, i), header=env.get_current_symbols(), index=None) pd.DataFrame(days_array).to_csv(save_directory+"endingdays/{}-iteration{}.csv".format(identifier, i), header=env.get_current_symbols(), index=None) pd.DataFrame(rewards_array).to_csv(save_directory+"rewards/{}-iteration{}.csv".format(identifier, i), header=env.get_current_symbols(), index=None) pd.DataFrame(test_total_profits).to_csv(save_directory+"profits/{}.csv".format(identifier), index=None) mean_test_reward.reset_states() a = [(-0.15989657, 'open'), (-0.19772957, 'close'), (0.11944062, 'low'), (-0.07273539, 'high'), (-0.05442702, 'volume'), (0.08966919, 'Accounts Payable'), (0.021010576, 'Accounts Receivable'), (-0.027171114, "Add'l income/expense items"), (0.01937542, 'After Tax ROE'), (0.22196895, 'Capital Expenditures'), (0.02117831, 'Capital Surplus'), (-0.062394377, 'Cash Ratio'), (-0.1270617, 'Cash and Cash Equivalents'), (0.047790807, 'Changes in Inventories'), (0.07777014, 'Common Stocks'), (0.106798984, 'Cost of Revenue'), (-0.021594241, 'Current Ratio'), (-0.015595697, 'Deferred Asset Charges'), (-0.031983275, 'Deferred Liability Charges'), (0.1295437, 'Depreciation'), (-0.19305989, 'Earnings Before Interest and Tax'), (-0.10321899, 'Earnings Before Tax'), (0.0041140895, 'Effect of Exchange Rate'), (0.23839177, 'Equity Earnings/Loss Unconsolidated Subsidiary'), (-0.20699006, 'Fixed Assets'), (0.018536765, 'Goodwill'), (0.03508943, 'Gross Margin'), (0.10541249, 'Gross Profit'), (0.19734253, 'Income Tax'), (0.13355829, 'Intangible Assets'), (-0.17602208, 'Interest Expense'), (-0.0025003892, 'Inventory'), (-0.081173904, 'Investments'), (0.028858133, 'Liabilities'), (-0.015410017, 'Long-Term Debt'), (-0.059088428, 'Long-Term Investments'), (-0.060415223, 'Minority Interest'), (0.052735303, 'Misc. Stocks'), (-0.16270235, 'Net Borrowings'), (0.30459827, 'Net Cash Flow'), (-0.051255636, 'Net Cash Flow-Operating'), (-0.17853276, 'Net Cash Flows-Financing'), (-0.012475527, 'Net Cash Flows-Investing'), (-0.007237089, 'Net Income'), (0.030531632, 'Net Income Adjustments'), (-0.044338573, 'Net Income Applicable to Common Shareholders'), (-0.019390859, 'Net Income-Cont. Operations'), (-0.042641692, 'Net Receivables'), (-0.19151591, 'Non-Recurring Items'), (0.2126374, 'Operating Income'), (-0.115024894, 'Operating Margin'), (-0.12695658, 'Other Assets'), (-0.11095659, 'Other Current Assets'), (-0.21254101, 'Other Current Liabilities'), (0.08447041, 'Other Equity'), (0.017648121, 'Other Financing Activities'), (-0.08386561, 'Other Investing Activities'), (0.10737695, 'Other Liabilities'), (-0.09191378, 'Other Operating Activities'), (-0.057637196, 'Other Operating Items'), (-0.023080353, 'Pre-Tax Margin'), (-0.048542995, 'Pre-Tax ROE'), (0.13798867, 'Profit Margin'), (0.02022573, 'Quick Ratio'), (-0.05218117, 'Research and Development'), (-0.32454595, 'Retained Earnings'), (-0.01603744, 'Sale and Purchase of Stock'), (-0.07250982, 'Sales, General and Admin.'), (0.02872207, 'Short-Term Debt / Current Portion of Long-Term Debt'), (0.29647112, 'Short-Term Investments'), (-0.0073608444, 'Total Assets'), (-0.07006701, 'Total Current Assets'), (-0.014121261, 'Total Current Liabilities'), (0.011505632, 'Total Equity'), (0.16001107, 'Total Liabilities'), (0.010682229, 'Total Liabilities & Equity'), (0.0726818, 'Total Revenue'), (-0.07457304, 'Treasury Stock'), (0.21740438, 'Earnings Per Share'), (-0.2218255, 'Estimated Shares Outstanding')] def myFunc(x): return abs(x[0]) a.sort(key=myFunc) def myFunc(x): return abs(x[0]) a.sort(key=myFunc) positive_list = [x>0 for x,y in a[-15:]] x = [abs(x) for x,y in a[-15:]] y = [y for x,y in a[-15:]] plt.xlabel('Absolute coefficient') plt.title('Logistic reggression coefficients') plot = plt.barh(y,x, alpha=0.5) for i in range(len(positive_list)): if positive_list[i]: plot[i].set_color('g') else: plot[i].set_color('r') import matplotlib.patches as mpatches red_patch = mpatches.Patch(color='r', label='Negative') green_patch = mpatches.Patch(color='g', label='Positive') plt.legend(handles=[green_patch,red_patch], loc="lower right") plt.tight_layout() plt.savefig('lr_coefficients.png', dpi=1200) positive_list ```
github_jupyter
### Package Imports ``` #Package imports import pandas as pd import numpy as np import calendar import matplotlib.pyplot as plt import seaborn as sns import plotly import utils sns.set_style('darkgrid') from pandas_datareader import data #Package for pulling data from the web from datetime import date from fbprophet import Prophet ``` ### Pulling in Data ``` #Pulling in the tickers and economic predicators we're interested in #ONLN = Online Retail ETF, FTXD = Nasdaq Retail ETF, XLY = S&P Consumer Discretionary ETF, #IYW= iShares US Tech ETF, AMZN = Amazon, EBAY = Ebay, FB = Facebook #JETS = Global Airline ETF (Recovery trade), XOP = S&P O&G Exploration and Production ETF (Recovery Trade) #GOVT = US T-Bond ETF, CL=F = Crude, GC=F = Gold, SI=F = Silver, HG=F = Copper, ^VIX = CBOE Vix tickers = ['ETSY','SPY','ONLN','FTXD','XLY','IHE','AMZN','EBAY','FB','JETS','XOP','GOVT','CL=F','GC=F','SI=F','HG=F','^VIX'] #Getting the most up to date data we can today = date.today() #This function automatically updates with today's data #Pulling the timeseries data directly from yahoo finance into a dataframe etf_df= data.DataReader(tickers, start='2020-06-01', #start date end = today, #charting up to today's date data_source='yahoo')['Adj Close'] #obtaining price at close #Dropping missing vals etf_df = etf_df.dropna() #Checking the 5 most recent values etf_df.head(5) #Creating correlation matrix corr_mat = etf_df.corr() fig, ax = plt.subplots(figsize = (10,10)) sns.heatmap(corr_mat) #Quantifying the Correlation Matrix i = 12 columns = corr_mat.nlargest(i,'ETSY')['ETSY'].index corrmat = np.corrcoef(etf_df[columns].values.T) heatmap = sns.heatmap(corrmat, cbar=True, annot=True, xticklabels = columns.values, yticklabels = columns.values) ax.set_title('Correlation Matrix for ETSY') plt.show() ``` ### Forecasting Predicator Variables Individually ``` #Creating dfs to model with #SPY, XOP, ONLN #Regressor 1 (SPY) reg1_prophet = pd.DataFrame() reg1_prophet['ds'] = etf_df.index reg1_prophet['y'] = etf_df['SPY'].values #Regressor 2 (ONLN) reg2_prophet = pd.DataFrame() reg2_prophet['ds'] = etf_df.index reg2_prophet['y'] = etf_df['ONLN'].values #Regressor 3 (XOP) reg3_prophet = pd.DataFrame() reg3_prophet['ds'] = etf_df.index reg3_prophet['y'] = etf_df['XOP'].values ``` ### Fitting Models ``` #Pred 1 reg1_m = Prophet() reg1_m.fit(reg1_prophet) reg1_future = reg1_m.make_future_dataframe(freq='m', periods=3); #Pred 2 reg2_m = Prophet() reg2_m.fit(reg2_prophet) reg2_future = reg2_m.make_future_dataframe(freq='m', periods=3); #Pred 3 reg3_m = Prophet() reg3_m.fit(reg3_prophet) reg3_future = reg3_m.make_future_dataframe(freq='m', periods=3); ``` ### Creating Forecast for Next 6 Months of Predicator Variables ``` #Defining length of forecast future_pred_length = reg1_m.make_future_dataframe(freq='m',periods = 3) #Pred 1 reg1_forecast = reg1_m.predict(future_pred_length) reg1_pred = pd.DataFrame(reg1_forecast['trend'].values) #Pred 2 reg2_forecast = reg2_m.predict(future_pred_length) reg2_pred = pd.DataFrame(reg2_forecast['trend'].values) #Pred 3 reg3_forecast = reg3_m.predict(future_pred_length) reg3_pred = pd.DataFrame(reg3_forecast['trend'].values) #Combining predicators into one df frames = [future_pred_length,reg1_pred,reg2_pred,reg3_pred] predicator_forecast = pd.concat(frames,axis=1) predicator_forecast.columns = ['ds','Reg_1','Reg_2','Reg_3'] predicator_forecast.head() ``` ### Forecasting ETF Performance with Predicator Variables ``` #Creating dfs to train model with (FB Prophet format) etf_prophet = pd.DataFrame() etf_prophet['ds'] = etf_df.index etf_prophet['y'] = etf_df['ETSY'].values etf_prophet['Reg_1'] = etf_df['SPY'].values etf_prophet['Reg_2'] = etf_df['ONLN'].values etf_prophet['Reg_3'] = etf_df['XOP'].values #Checking Prophet df etf_prophet.head() #Defining model, adding additional regressors and fitting model m = Prophet() #m.add_regressor('Reg_1') m.add_regressor('Reg_2') m.add_regressor('Reg_3') m.fit(etf_prophet) #Forecasting the next 90 days etf_forecast = m.predict(predicator_forecast) etf_forecast.tail() #Visualizing forecast plt.figure(figsize = (20,10)) m.plot(etf_forecast, xlabel='Year',ylabel ='Price [USD]'); plt.title('3 Month ETSY Forecast [ETSY]') #Plotting forecast components plt.figure(figsize = (20,10)) m.plot_components(etf_forecast); ```
github_jupyter
``` import pandas as pd import numpy as np import seaborn as sb %matplotlib inline import matplotlib.pyplot as plt df = pd.read_csv('C:\\\\Users\kimte\\git\\data-analytics-and-science\\exercises\\exercise 1 - loan prediction problem\\data\\train.csv') df.shape type(df) df.info() df.head() ``` # Missing values identification ``` df.isnull().any() df[df.isnull().any(axis=1)] ``` # Target value identification and recoding ### target Loan_Status ``` df["Loan_Status"].isnull().value_counts() df["Loan_Status"].value_counts() df["Loan_Status_int"] = df["Loan_Status"].astype('category').cat.codes pd.crosstab(df["Loan_Status"],df["Loan_Status_int"]) ``` # Predictive variable identification Opties om data in dummys om te zetten: cat_vars=['job','marital','education','default','housing','loan','contact','month','day_of_week','poutcome'] for var in cat_vars: cat_list='var'+'_'+var cat_list = pd.get_dummies(data[var], prefix=var) data1=data.join(cat_list) data=data1 df["Gender"].astype('category').cat.codes pd.get_dummies(df["Gender"]) ## make list for predictive vars ``` x_selected = [] x_selected ``` ### Var Gender ``` df["Gender"].isnull().value_counts() pd.crosstab(df["Loan_Status"], df["Gender"].isnull())\ ,pd.crosstab(df["Loan_Status"], df["Gender"].isnull(),normalize="columns") import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"], df["Gender"].isnull())) df["Gender"].value_counts() pd.crosstab(df["Loan_Status"], df["Gender"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Gender"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"],df["Gender"])) ``` ### Var Married ``` df["Married"].isnull().value_counts() df["Married"].value_counts() pd.crosstab(df["Loan_Status"], df["Married"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Married"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"], df["Married"])) df = pd.concat([df, pd.get_dummies(df["Married"], prefix="Married", prefix_sep="_")], axis=1) df.info() x_selected += ["Married_No"] x_selected += ["Married_Yes"] x_selected ``` ### var Dependents ``` df["Dependents"].isnull().value_counts() df["Dependents"].value_counts() pd.crosstab(df["Loan_Status"], df["Dependents"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Dependents"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"],df["Dependents"])) df = pd.concat([df, pd.get_dummies(df["Dependents"], prefix="Dependents", prefix_sep="_")], axis=1) df.info() x_selected += ["Dependents_0"] x_selected += ["Dependents_1"] x_selected += ["Dependents_2"] x_selected += ["Dependents_3+"] x_selected ``` ### var Education ``` df["Education"].isnull().value_counts() df["Education"].value_counts() pd.crosstab(df["Loan_Status"], df["Education"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Education"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"],df["Education"])) df = pd.concat([df, pd.get_dummies(df["Education"], prefix="Education", prefix_sep="_")], axis=1) df.info() x_selected += ["Education_Graduate"] x_selected += ["Education_Not Graduate"] x_selected ``` ### var Self_Employed ``` df["Self_Employed"].isnull().value_counts() pd.crosstab(df["Loan_Status"], df["Self_Employed"].isnull())\ ,pd.crosstab(df["Loan_Status"], df["Self_Employed"].isnull(),normalize="columns") import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"], df["Self_Employed"].isnull())) df["Self_Employed"].value_counts() pd.crosstab(df["Loan_Status"], df["Self_Employed"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Self_Employed"].value_counts(normalize=True) ``` ### var ApplicantIncome ``` df["ApplicantIncome"].isnull().value_counts() df["ApplicantIncome"].min(), df["ApplicantIncome"].max(), df["ApplicantIncome"].mean(), df["ApplicantIncome"].median() ax = df["ApplicantIncome"].plot.box() df[["ApplicantIncome","Loan_Status"]].boxplot(by=["Loan_Status"]) df.groupby("Loan_Status")["ApplicantIncome"].median() df['ApplicantIncome'][(df["Loan_Status"]=='N')].hist(alpha=0.6) df['ApplicantIncome'][(df["Loan_Status"]=='Y')].hist(alpha=0.6) import scipy.stats as scs scs.ttest_rel(df["Loan_Status_int"],df["ApplicantIncome"]) x_selected += ["ApplicantIncome"] x_selected ``` ### var CoapplicantIncome ``` df["CoapplicantIncome"].isnull().value_counts() df["CoapplicantIncome"].min(), df["CoapplicantIncome"].max(), df["CoapplicantIncome"].mean(), df["CoapplicantIncome"].median() ax = df["CoapplicantIncome"].plot.box() df["CoapplicantIncome"][df["CoapplicantIncome"]>0].shape df["CoapplicantIncome"][df["CoapplicantIncome"]>0].min(), df["CoapplicantIncome"][df["CoapplicantIncome"]>0].max(), df["CoapplicantIncome"][df["CoapplicantIncome"]>0].mean(), df["CoapplicantIncome"][df["CoapplicantIncome"]>0].median() ax = df["CoapplicantIncome"][df["CoapplicantIncome"]>0].plot.box() df[["CoapplicantIncome","Loan_Status"]].boxplot(by=["Loan_Status"]) df.groupby("Loan_Status")["CoapplicantIncome"].median() df['CoapplicantIncome'][(df["Loan_Status"]=='N')].hist(alpha=0.6) df['CoapplicantIncome'][(df["Loan_Status"]=='Y')].hist(alpha=0.6) import scipy.stats as scs scs.ttest_rel(df["Loan_Status_int"],df["CoapplicantIncome"]) x_selected += ["CoapplicantIncome"] x_selected ``` ### var LoanAmount ``` df["LoanAmount"].isnull().value_counts() df["LoanAmount"].fillna(df["LoanAmount"].mean(), inplace=True) df["LoanAmount"].isnull().value_counts() df["LoanAmount"].min(), df["LoanAmount"].max(), df["LoanAmount"].mean(), df["LoanAmount"].median() ax = df["LoanAmount"].plot.box() df[["LoanAmount","Loan_Status"]].boxplot(by=["Loan_Status"]) df.groupby("Loan_Status")["LoanAmount"].median() df['LoanAmount'][(df["Loan_Status"]=='N')].hist(alpha=0.6) df['LoanAmount'][(df["Loan_Status"]=='Y')].hist(alpha=0.6) import scipy.stats as scs scs.ttest_rel(df["Loan_Status_int"],df["LoanAmount"]) x_selected += ["LoanAmount"] x_selected ``` ### Var Loan_Amount_Term ``` df["Loan_Amount_Term"].isnull().value_counts() df["Loan_Amount_Term"].fillna(df["Loan_Amount_Term"].mean(), inplace=True) df["Loan_Amount_Term"].isnull().value_counts() df["Loan_Amount_Term"].min(), df["Loan_Amount_Term"].max(), df["Loan_Amount_Term"].mean(), df["Loan_Amount_Term"].median() df[["Loan_Amount_Term","Loan_Status"]].boxplot(by=["Loan_Status"]) df.groupby("Loan_Status")["Loan_Amount_Term"].median() df['Loan_Amount_Term'][(df["Loan_Status"]=='N')].hist(alpha=0.6) df['Loan_Amount_Term'][(df["Loan_Status"]=='Y')].hist(alpha=0.6) import scipy.stats as scs scs.ttest_rel(df["Loan_Amount_Term"],df["CoapplicantIncome"]) ``` ### var Credit_History ``` df["Credit_History"].isnull().value_counts() df["Credit_History"].value_counts() pd.crosstab(df["Loan_Status"], df["Credit_History"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Credit_History"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"],df["Credit_History"])) df = pd.concat([df, pd.get_dummies(df["Credit_History"], prefix="Credit_History", prefix_sep="_")], axis=1) df.info() x_selected += ["Credit_History_0.0"] x_selected += ["Credit_History_1.0"] x_selected ``` ### var Property_Area ``` df["Property_Area"].isnull().value_counts() df["Property_Area"].value_counts() pd.crosstab(df["Loan_Status"], df["Property_Area"], normalize="columns").plot(kind='bar') df.groupby("Loan_Status")["Property_Area"].value_counts(normalize=True) import scipy.stats as scs scs.chi2_contingency(pd.crosstab(df["Loan_Status"],df["Property_Area"])) df = pd.concat([df, pd.get_dummies(df["Property_Area"], prefix="Property_Area", prefix_sep="_")], axis=1) df.info() x_selected += ["Property_Area_Rural"] x_selected += ["Property_Area_Semiurban"] x_selected += ["Property_Area_Urban"] x_selected ``` # Model bouwen ``` x_selected x=df[x_selected] y=df["Loan_Status_int"] x.info() ``` ### Full model (own feature selection) ``` import statsmodels.api as sm logit_model=sm.Logit(y,x) result=logit_model.fit() print(result.summary()) ``` ### Automated feature selection ``` from sklearn import datasets from sklearn.feature_selection import RFE from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() rfe = RFE(logreg, 6) rfe = rfe.fit(x, y) print(rfe.support_) print(rfe.ranking_) list_features = np.atleast_1d(rfe.support_) x_features = x.loc[:,list_features] x_features.info() ``` ### Final model (6 features selected) ``` import statsmodels.api as sm logit_model=sm.Logit(y,x_features) result=logit_model.fit() print(result.summary()) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x_features, y, test_size=0.3, random_state=0) from sklearn.linear_model import LogisticRegression from sklearn import metrics model = LogisticRegression() model.fit(x_train, y_train) ``` ### Accuracy of final model ``` y_pred = model.predict(x_test) print('Accuracy of logistic regression classifier on test set: {:.2f}'.format(model.score(x_test, y_test))) ``` ### Accuracy in cross validation of final model ``` from sklearn import model_selection from sklearn.model_selection import cross_val_score kfold = model_selection.KFold(n_splits=10, random_state=7) scoring = 'accuracy' results = model_selection.cross_val_score(model, x_train, y_train, cv=kfold, scoring=scoring) print("10-fold cross validation average accuracy: %.3f" % (results.mean())) ``` ### Confusion matrix ``` from sklearn.metrics import confusion_matrix confusion_matrix = confusion_matrix(y_test, y_pred) print(confusion_matrix) ``` *The result is telling us that we have 21+132 correct predictions and 2+30 incorrect predictions. ### Precision, recall, F-measure and support ``` from sklearn.metrics import classification_report print(classification_report(y_test, y_pred)) ``` ### ROC curve ``` from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(y_test, model.predict(x_test)) fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(x_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.savefig('Log_ROC') plt.show() ``` # Prediction using the model ``` x_features.info() ``` ### test whether prediction using the model works ``` myvals = np.array([0, 0, 0, 0, 0, 0]).reshape(1, -1) myvals model.predict(myvals) # Closer to 0 is higher likelyhood of getting the loan ``` ## Test data where loan must be predicted ``` df_test = pd.read_csv('C:\\\\Users\kimte\\git\\data-analytics-and-science\\exercises\\exercise 1 - loan prediction problem\\data\\test.csv') df_test.shape type(df_test) df_test.info() df_test = pd.concat([df_test, pd.get_dummies(df_test["Married"], prefix="Married", prefix_sep="_")], axis=1) df_test = pd.concat([df_test, pd.get_dummies(df_test["Dependents"], prefix="Dependents", prefix_sep="_")], axis=1) df_test = pd.concat([df_test, pd.get_dummies(df_test["Education"], prefix="Education", prefix_sep="_")], axis=1) df_test = pd.concat([df_test, pd.get_dummies(df_test["Credit_History"], prefix="Credit_History", prefix_sep="_")], axis=1) df_test = pd.concat([df_test, pd.get_dummies(df_test["Property_Area"], prefix="Property_Area", prefix_sep="_")], axis=1) list_features = x_features.columns.values.tolist() x_features_test = df_test.loc[:,list_features] x_features_test.info() df_test["loan_predicted"] = model.predict(x_features_test) df_test["loan_predicted"].value_counts() ```
github_jupyter
# Using multi-armed bandits to choose the best model for predicting credit card default ## Dependencies - [helm](https://github.com/helm/helm) - [minikube](https://github.com/kubernetes/minikube) --> install 0.25.2 - [s2i](https://github.com/openshift/source-to-image) - Kaggle account to download data. - Python packages: ``` !pip install -r requirements.txt ``` ## Getting data Either head to https://www.kaggle.com/uciml/default-of-credit-card-clients-dataset or use the Kaggle API (instructions at https://github.com/Kaggle/kaggle-api) to download the dataset: ``` !kaggle datasets download -d uciml/default-of-credit-card-clients-dataset !unzip default-of-credit-card-clients-dataset.zip ``` ## Load and inspect data ``` import pandas as pd data = pd.read_csv('UCI_Credit_Card.csv') data.shape data.columns target = 'default.payment.next.month' data[target].value_counts() ``` Note that we have a class imbalance, so if we use accuracy as the performance measure of a classifier, we need to be able to beat the "dummy" model that classifies every instance as 0 (no default): ``` data[target].value_counts().max()/data.shape[0] ``` ## Case study for using multi-armed bandits In deploying a new ML model, it is rarely the case that the existing (if any) model is decommissioned immediately in favour of the new one. More commonly the new model is deployed alongside the existing one(s) and the incoming traffic is shared between the models. Typically A/B testing is performed in which traffic is routed between existing models randomly, this is called the experiment stage. After a set period of time performance statistics are calculated and the best-performing model is chosen to serve 100% of the requests while the other model(s) are decommissioned. An alternative method is to route traffic dynamically to the best performing model using multi-armed bandits. This avoids the opportunity cost of consistently routing a lot of traffic to the worst performing model(s) during an experiment as in A/B testing. This notebook is a case study in deploying two models in parallel and routing traffic between them dynamically using multi-armed bandits (Epsilon-greedy and Thompson sampling in particular). We will use the dataset to simulate a real-world scenario consisting of several steps: 1. Split the data set in half (15K samples in each set) and treat the first half as the only data observes so far 2. Split the first half of the data in proportion 10K:5K samples to use as train:test sets for a first simple model (Random Forest) 3. After training the first model, simulate a "live" environment on the first 5K of data in the second half of the dataset 4. Use the so far observed 20K samples to train a second model (XGBoost) 5. Deploy the second model alongside the first together with a multi-armed bandit and simulate a "live" environment on the last 10K of the unobserved data, routing requests between the two models The following diagram illustrates the proposed simulation design: ![data-split](assets/split.png) ## Data preparation ``` import numpy as np from sklearn.model_selection import train_test_split OBSERVED_DATA = 15000 TRAIN_1 = 10000 TEST_1 = 5000 REST_DATA = 15000 RUN_DATA = 5000 ROUTE_DATA = 10000 # get features and target X = data.loc[:, data.columns!=target].values y = data[target].values # observed/unobserved split X_obs, X_rest, y_obs, y_rest = train_test_split(X, y, random_state=1, test_size=REST_DATA) # observed split into train1/test1 X_train1, X_test1, y_train1, y_test1 = train_test_split(X_obs, y_obs, random_state=1, test_size=TEST_1) # unobserved split into run/route X_run, X_route, y_run, y_route = train_test_split(X_rest, y_rest, random_state=1, test_size=ROUTE_DATA) # observed+run split into train2/test2 X_rest = np.vstack((X_run, X_route)) y_rest = np.hstack((y_run, y_route)) X_train2 = np.vstack((X_train1, X_test1)) X_test2 = X_run y_train2 = np.hstack((y_train1, y_test1)) y_test2 = y_run ``` ## Model training We will train both models at once, but defer evaluation of the second model until simulating the live environment. ``` from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=1) rf.fit(X_train1, y_train1) ``` Now let's see how good our first model is on the test1 set: ``` from sklearn.metrics import accuracy_score, precision_score, recall_score, \ f1_score, confusion_matrix, classification_report y_preds1 = rf.predict(X_test1) print(classification_report(y_test1, y_preds1, target_names=['No default','Default'])) for score in [accuracy_score, precision_score, recall_score, f1_score, confusion_matrix]: print(score.__name__ + ':\n', score(y_test1, y_preds1)) %matplotlib inline from utils import plot_confusion_matrix cm = confusion_matrix(y_test1, y_preds1) plot_confusion_matrix(cm, classes=['No default','Default'], normalize=True) ``` So a simple random forest model without any optimizations is able to outperform random guessing on accuracy and achieves a baseline F1 score of ~0.44. However, it is a poor predictor of default as it only achieves a recall of ~0.34. Train the second model in advance, but defer evaluation: ``` from xgboost import XGBClassifier xgb = XGBClassifier(random_state=1) xgb.fit(X_train2, y_train2) ``` Save trained models to disk: ``` from sklearn.externals import joblib joblib.dump(rf, 'models/rf_model/RFModel.sav') joblib.dump(xgb, 'models/xgb_model/XGBModel.sav') ``` ## Set up Kubernetes for live simulation Pick Kubernetes cluster on GCP or Minikube. ``` minikube = False if minikube: !minikube start --vm-driver kvm2 --memory 4096 --cpus 6 else: !gcloud container clusters get-credentials standard-cluster-1 --zone europe-west1-b --project seldon-demos ``` Create a cluster-wide cluster-admin role assigned to a service account named “default” in the namespace “kube-system”. ``` !kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin \ --serviceaccount=kube-system:default !kubectl create namespace seldon ``` Add current context details to the configuration file in the seldon namespace. ``` !kubectl config set-context $(kubectl config current-context) --namespace=seldon ``` Create tiller service account and give it a cluster-wide cluster-admin role. ``` !kubectl -n kube-system create sa tiller !kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller !helm init --service-account tiller ``` Check deployment rollout status and deploy seldon/spartakus helm charts. ``` !kubectl rollout status deploy/tiller-deploy -n kube-system !helm install ../../../helm-charts/seldon-core-operator --name seldon-core --set usageMetrics.enabled=true --namespace seldon-system !kubectl rollout status deploy/seldon-controller-manager -n seldon-system %%bash helm repo add datawire https://www.getambassador.io helm repo update helm install ambassador datawire/ambassador \ --set image.repository=quay.io/datawire/ambassador \ --set enableAES=false \ --set crds.keep=false !kubectl rollout status deployment.apps/ambassador ``` Install analytics (Prometheus for metrics and Grafana for visualisation): ``` !helm install ../../../helm-charts/seldon-core-analytics --name seldon-core-analytics \ --set grafana_prom_admin_password=password \ --set persistence.enabled=false \ --namespace seldon ``` Port forward Ambassador (run command in terminal): ```sh kubectl port-forward $(kubectl get pods -n seldon -l app.kubernetes.io/name=ambassador -o jsonpath='{.items[0].metadata.name}') -n seldon 8003:8080 ``` Port forward Grafana (run command in terminal): ```sh kubectl port-forward $(kubectl get pods -n seldon -l app=grafana-prom-server -o jsonpath='{.items[0].metadata.name}') -n seldon 3000:3000 ``` You can then view an analytics dashboard inside the cluster at http://localhost:3000/d/rs_zGKYiz/mab?refresh=1s&orgId=1&from=now-2m&to=now. Login with: Username : admin password : password (as set when starting seldon-core-analytics above) **Import the mab dashboard from ```assets/mab.json```.** ### Wrap model and router images with s2i We have prepared the model classes under ```models/rf_model/RFModel.py``` and ```models/xgb_model/XGBModel.py``` for wrapping the trained models as docker images using s2i. The structure of the files is as follows: ``` !pygmentize models/rf_model/RFModel.py ``` Note that we define our own custom metrics which are the entries of the confusion matrix that will be exposed to Prometheus and visualized in Grafana as the model runs in the simulated live environment. If Minikube used: create docker image for the trained models and routers inside Minikube using s2i. ``` if minikube: !eval $(minikube docker-env) && \ make -C models/rf_model build && \ make -C models/xgb_model build && \ make -C ../epsilon-greedy build && \ make -C ../thompson-sampling build ``` ## Deploy the first model ``` !kubectl apply -f assets/rf_deployment.json -n seldon !kubectl rollout status deploy/rf-model-rf-model-7c4643e ``` ## Simulate the first model in production for 5000 samples ``` from utils import rest_request_ambassador, send_feedback_rest for i in range(X_run.shape[0]): if i%1000 == 0: print(f'Processed {i}/{X_run.shape[0]} samples', flush=True) # fetch sample and make a request payload x = X_run[i].reshape(1,-1).tolist() request = {'data':{'ndarray':x}} # send request to model response = rest_request_ambassador('rf-deployment', 'seldon', request) # extract prediction probs = response.get('data').get('ndarray')[0] pred = np.argmax(probs) # send feedback to the model informing it if it made the right decision truth_val = int(y_run[i]) reward = int(pred==truth_val) truth = [truth_val] _ = send_feedback_rest('rf-deployment', 'seldon', request, response, reward, truth) ``` We can see the model performance on the Grafana dashboard: http://localhost:3000/d/rs_zGKYiz/mab?refresh=1s&orgId=1&from=now-2m&to=now (refresh to update) ## Deploy the original model and the new model with a router in front Suppose now we have come up with a new model and want to deploy it alongside the first model with a multi-armed bandit router to make decisions which model should make predictions. We will delete the original deployment and make a new one that has both models in parallel and a router/multi-armed bandit in front. To make things interesting, we will actually deploy 2 parallel deployments with the same 2 models but a different router in front (Epsilon-greedy and Thompson sampling) to compare the performance of two very different multi-armed bandit algorithms. One can think of the first deployment as a production deployment and the second parallel one as a shadow deployment whose responses are used for testing only. But first, let's see what the performance of the new XGBoost model is on its test2 data: ``` y_preds2 = xgb.predict(X_test2) print(classification_report(y_test2, y_preds2, target_names=['No default','Default'])) for score in [accuracy_score, precision_score, recall_score, f1_score, confusion_matrix]: print(score.__name__ + ':\n', score(y_test2, y_preds2)) cm = confusion_matrix(y_test2, y_preds2) plot_confusion_matrix(cm, classes=['No default','Default'], normalize=True) ``` So the XGBoost model is slightly better than the old RFModel, so we expect any decent multi-armed bandit router to pick this up on live data, let's try this out. First, delete the existing deployment of the old RFModel: ``` !kubectl delete sdep rf-deployment ``` Deploy the following two deployments: ``` from utils import get_graph get_graph('assets/eg_deployment.json') get_graph('assets/ts_deployment.json') !kubectl apply -f assets/eg_deployment.json -n seldon !kubectl apply -f assets/ts_deployment.json -n seldon !kubectl rollout status deploy/poc-eg-eg-2-47fb8da !kubectl rollout status deploy/poc-ts-ts-2-75f9d39 ``` ## Simulate both deployments in parellel with the remaining 10000 data samples Here we send request and feedback to both parallel deployments, thus assessing the performance of the Epsilon-greedy router versus Thompson sampling as a method of routing to the best performing model. ``` for i in range(X_route.shape[0]): if i%1000 == 0: print(f'Processed {i}/{X_route.shape[0]} samples', flush=True) # fetch sample and make a request payload x = X_route[i].reshape(1,-1).tolist() request = {'data':{'ndarray':x}} # send request to both deployments eg_response = rest_request_ambassador('eg-deployment', 'seldon', request) ts_response = rest_request_ambassador('ts-deployment', 'seldon', request) # extract predictions eg_probs = eg_response.get('data').get('ndarray')[0] ts_probs = ts_response.get('data').get('ndarray')[0] eg_pred = np.argmax(eg_probs) ts_pred = np.argmax(ts_probs) # send feedback to the model informing it if it made the right decision truth_val = int(y_route[i]) eg_reward = int(eg_pred==truth_val) ts_reward = int(ts_pred==truth_val) truth = [truth_val] _ = send_feedback_rest('eg-deployment', 'seldon', request, eg_response, eg_reward, truth) _ = send_feedback_rest('ts-deployment', 'seldon', request, ts_response, ts_reward, truth) ``` We can see the model performance on the Grafana dashboard: http://localhost:3000/dashboard/db/mab?refresh=5s&orgId=1 (refresh to update) We note that both the Epsilon greedy and Thompson sampling allocate more traffic to the better performing model (XGBoost) over time, but Thompson Sampling does so at a quicker rate as evidenced by the superior metrics (F1 score in particular). ## Clean-up ``` # delete data !rm default-of-credit-card-clients-dataset.zip !rm UCI_Credit_Card.csv # delete trained models !rm models/rf_model/RFModel.sav !rm models/xgb_model/XGBModel.sav # delete Seldon deployment from the cluster !kubectl delete sdep --all ```
github_jupyter
<img src="NotebookAddons/blackboard-banner.png" width="100%" /> <font face="Calibri"> <br> <font size="7"> <b> GEOS 657: Microwave Remote Sensing<b> </font> <font size="5"> <b>Lab 9: InSAR Time Series Analysis using GIAnT within Jupyter Notebooks<br>Part 2: GIAnT <font color='rgba(200,0,0,0.2)'> -- [## Points] </font> </b> </font> <br> <font size="4"> <b> Franz J Meyer & Joshua J C Knicely; University of Alaska Fairbanks</b> <br> <img src="NotebookAddons/UAFLogo_A_647.png" width="170" align="right" /><font color='rgba(200,0,0,0.2)'> <b>Due Date: </b>NONE</font> </font> <font size="3"> This Lab is part of the UAF course <a href="https://radar.community.uaf.edu/" target="_blank">GEOS 657: Microwave Remote Sensing</a>. This lab is divided into 3 parts: 1) data download and preprocessing, 2) GIAnT time series, and 3) a simple Mogi source inversion. The primary goal of this lab is to demonstrate how to process InSAR data, specifically interferograms, using the Generic InSAR Analysis Toolbox (<a href="http://earthdef.caltech.edu/projects/giant/wiki" target="_blank">GIAnT</a>) in the framework of *Jupyter Notebooks*.<br> <b>Our specific objectives for this lab are to:</b> - Prepare data for GIAnT: - Create necessary ancillary files and functions. - Reformat the interferograms. - Run GIAnT - Use GIAnT to create maps of surface deformation: - Understand its capabilities. - Understand its limitations. </font> <br> <font face="Calibri"> <font size="5"> <b> Target Description </b> </font> <font size="4"> <font color='rgba(200,0,0,0.2)'> <b>THIS NOTEBOOK INCLUDES NO HOMEWORK ASSIGNMENTS.</b></font> <br> Contact me at fjmeyer@alaska.edu should you run into any problems. </font> ``` %%javascript var kernel = Jupyter.notebook.kernel; var command = ["notebookUrl = ", "'", window.location, "'" ].join('') kernel.execute(command) from IPython.display import Markdown from IPython.display import display user = !echo $JUPYTERHUB_USER env = !echo $CONDA_PREFIX if env[0] == '': env[0] = 'Python 3 (base)' if env[0] != '/home/jovyan/.local/envs/insar_analysis': display(Markdown(f'<text style=color:red><strong>WARNING:</strong></text>')) display(Markdown(f'<text style=color:red>This notebook should be run using the "insar_analysis" conda environment.</text>')) display(Markdown(f'<text style=color:red>It is currently using the "{env[0].split("/")[-1]}" environment.</text>')) display(Markdown(f'<text style=color:red>Select "insar_analysis" from the "Change Kernel" submenu of the "Kernel" menu.</text>')) display(Markdown(f'<text style=color:red>If the "insar_analysis" environment is not present, use <a href="{notebookUrl.split("/user")[0]}/user/{user[0]}/notebooks/conda_environments/Create_OSL_Conda_Environments.ipynb"> Create_OSL_Conda_Environments.ipynb </a> to create it.</text>')) display(Markdown(f'<text style=color:red>Note that you must restart your server after creating a new environment before it is usable by notebooks.</text>')) ``` <font face='Calibri'><font size='5'><b>Overview</b></font> <br> <font size='3'><b>About GIAnT</b> <br> GIAnT is a Python framework that allows rapid time series analysis of low amplitude deformation signals. It allows users to use multiple time series analysis technqiues: Small Baseline Subset (SBAS), New Small Baseline Subset (N-SBAS), and Multiscale InSAR Time-Series (MInTS). As a part of this, it includes the ability to correct for atmospheric delays by assuming a spatially uniform stratified atmosphere. <br><br> <b>Limitations</b> <br> GIAnT has a number of limitations that are important to keep in mind as these can affect its effectiveness for certain applications. It implements the simplest time-series inversion methods. Its single coherence threshold is very conservative in terms of pixel selection. It does not include any consistency checks for unwrapping errors. It has a limited dictionary of temporal model functions. It cannot correct for atmospheric effects due to differing surface elevations. <br><br> <b>Steps to use GIAnT</b><br> Although GIAnT is an incredibly powerful tool, it requires very specific input. Because of the input requirements, the bulk of the lab and code below is dedicated to getting our data into a form that GIAnT can manipulate and to creating files that tell GIAnT what to do. The general steps to use GIAnT are below. <br><br> More information about GIAnT can be found here, <a href="http://earthdef.caltech.edu/projects/giant/wiki" target="_blank">http://earthdef.caltech.edu/projects/giant/wiki</a>. <br><br> - Download Data - Identify Area of Interest - Subset (Crop) Data to Area of Interest - Prepare Data for GIAnT (Today's lab starts here) - Adjust file names - Remove potentially disruptive default values (optional) - Convert data from '.tiff' to '.flt' format - Create Input Files for GIAnT - Create 'ifg.list' - Create 'date.mli.par' - Make prepxml_SBAS.py - Run prepxml_SBAS.py - Make userfn.py - Run GIAnT - PrepIgramStack.py - ProcessStack.py - SBASInvert.py - SBASxval.py - Data Visualization <br><br> When you use GIAnT, cite the creator's work using:<br> Agram et al., (2013). "New Radar Interferometric Time Series Analysis Toolbox Released." Eos Trans. AGU, 94, 69. <br>AND<br> Agram et al., (2012). "Generic InSAR Analysis Toolbox (GIAnT) - User Guide." <http://earthdef.caltech.edu> <br><br><b><i>DO WE NEED TO ALSO GIVE ASF A CITATION???</i></b> <font face='Calibri'><font size='5'><b>Required Files</b></font> <br> <font size='3'>Before we begin, each student should have a specific subset of files with a specific folder structure as described below. If your folder structure differs, the code will need to be modified. <br> - Folder: Corrected Subsets - Files: TRAIN corrected unwrapped phase subsets - Files: Uncorrected unwrapped phase subsets - Folder: Ingram Subsets - Files: Amplitude subsets - Files: Coherence subsets - Files: Unwrapped phase (ingram) subsets - Theoretically, these are identical to the uncorrected unwrapped phase subsets in the Corrected Subsets folder. </font></font> <font face='Calibri'><font size='5'><b>0 System Setup</b></font><br> <font size='3'>We will first do some system setup. This involves importing requiesite Python libraries and defining all of our user inputs. </font></font> <font face='Calibri'><font size='4'><b>0.0 Import Python Packages</b></font><br> <font size='3'>Let's import the Python libraries we will need to run this lab. </font></font> ``` %%capture import os import h5py import shutil import re from datetime import date import glob import pickle import pathlib import subprocess from math import ceil from osgeo import gdal from osgeo import osr import pandas as pd %matplotlib notebook import matplotlib.pyplot as plt import matplotlib.animation import matplotlib.patches as patches # for Rectangle plt.rcParams.update({'font.size': 10}) import numpy as np from numpy import isneginf from IPython.display import HTML from matplotlib import animation, rc import asf_notebook as asfn asfn.jupytertheme_matplotlib_format() ``` <font face='Calibri' size='4'><b>0.1 Enter an analysis directory prepared in the Part 1 notebook</b></font> ``` pickle_pth = "part1_pickle" while True: analysis_directory = input("Enter the absolute path to the directory holding your data from Part 1:\n") if os.path.exists(f"{analysis_directory}/{pickle_pth}"): break else: print(f"\n{analysis_directory} does not contain {pickle_pth}") continue os.chdir(analysis_directory) print(f"\nanalysis_directory: {analysis_directory}") ``` <font face='Calibri' size='4'><b>0.2 Open our pickle from the Part 1 notebook</b></font> ``` pickle_pth = "part1_pickle" if os.path.exists(pickle_pth): with open(pickle_pth,'rb') as infile: part1_pickle = pickle.load(infile) print(f"part1_pickle = {part1_pickle}") else: print('Invalid Path. Did you follow part 1 and generate your pickle?') ``` <font face='Calibri' size='4'><b>0.3 Define some important paths</b></font> ``` ingram_folder = part1_pickle['ingram_folder'] # Location of the original ingram folders corrected_folder = part1_pickle['corrected_folder'] # Location of the TRAIN corrected subsets subset_folder = part1_pickle['subset_folder'] # Location of the original (uncorrected) subsets giant_dir = f'{analysis_directory}/GIAnT' # directory where we will perform GIAnT analysis giant_data = f'{analysis_directory}/GIAnT_Data' # directory where we will store our data for use by GIAnT output_dir = f'{analysis_directory}/geotiffs_and_animations' pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True) ``` <font face='Calibri'> <font size='4'><b>0.4 Decide whether or not to delete old data</b></font> <br> <font size='3'>True = delete <br> False = save</font> ``` replace_giant_dir = True # True or False; if True, any folder with the same name will be deleted and recreated. replace_giant_data = True replace_output_dir = True # set things to find files unw = '_unw_phase.' unw_corr = '_unw_phase_corrected.' corr = '_corr.' amp = '_amp.' ``` <font face='Calibri' size='4'><b>0.5 Delete the GIAnT data and working directories if 'replace_* = True'</b></font> ``` if replace_giant_dir: try: shutil.rmtree(giant_dir) except: pass if replace_giant_data: try: shutil.rmtree(giant_data) except: pass if replace_output_dir: try: shutil.rmtree(output_dir) except: pass # If the GIAnT data and working directories don't exist, create them. pathlib.Path(giant_dir).mkdir(parents=True, exist_ok=True) pathlib.Path(giant_data).mkdir(parents=True, exist_ok=True) pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True) ``` <font face='Calibri' size='4'><b>0.7 Load the pickled heading_avg</b></font> ``` heading_avg = part1_pickle['heading_avg'] print(f"heading_avg = {heading_avg}") ``` <font face='Calibri' size='4'><b>0.8 Copy a single clipped geotiff into our working GIAnT directory for later data visualization</b></font> ``` amps = [f for f in os.listdir(subset_folder) if '_amp' in f] amps.sort() shutil.copy(os.path.join(subset_folder, amps[0]), giant_dir) radar_tiff = os.path.join(giant_dir, amps[0]) ``` <font face='Calibri'><font size='5'><b>1. Create Input Files And Code for GIAnT</b></font> <br> <font size ='3'>Let's create the input files and specialty code that GIAnT requires. These are listed below. <br> - ifg.list - List of the interferogram properties including primary and secondary dates, perpendicular baseline, and sensor name. - date.mli.par - File from which GIAnT pulls requisite information about the sensor. - This is specifically for GAMMA files. When using other interferogram processing techniques, an alternate file is required. - prepxml_SBAS.py - Python function to create an xml file that specifies the processing options to GIAnT. - This must be modified by the user for their particular application. - userfn.py - Python function to map the interferogram dates to a phyiscal file on disk. - This must be modified by the user for their particular application. </font> </font> <font face='Calibri' size='4'><b>1.1 Create 'ifg.list' File </b></font> <br><br> <font face='Calibri' size='3'><b>1.1.0 Create a list of unwrapped, phase-corrected data</b></font> ``` files = [f for f in os.listdir(corrected_folder) if f.endswith(f'{unw_corr}tif')] # Just get one of each file name. files.sort() print(len(files)) print(*files, sep="\n") ``` <font face='Calibri' size='3'><b>1.1.1 Create a 4 column text file to communicate network information to GIAnT within the GIAnT folder</b> <br> Contains primary date, secondary date, perpendicular baseline, and sensor designation </font> ``` reference_dates = [] secondary_dates = [] for file in files: reference_dates.append(file[0:8]) secondary_dates.append(file[9:17]) # Sort the dates according to the primary dates. p_dates, s_dates = (list(t) for t in zip(*sorted(zip(reference_dates, secondary_dates)))) with open(os.path.join(giant_dir, 'ifg.list'), 'w') as fid: for i, dt in enumerate(p_dates): primary_date = dt # pull out Primary Date (first set of numbers) secondary_date = s_dates[i] # pull out Secondary Date (second set of numbers) bperp = '0.0' # perpendicular baseline. sensor = 'S1' # Sensor designation. # write values to the 'ifg.list' file. fid.write(f'{primary_date} {secondary_date} {bperp} {sensor}\n') ``` <font face='Calibri' size='3'><b>1.1.2 Print ifg.list</b></font> ``` with open(os.path.join(giant_dir, 'ifg.list'), 'r') as fid: print(fid.read()) ``` <font face='Calibri'><font size='3'>You may notice that the code above sets the perpendicular baseline to a value of 0.0 m. This is not the true perpendicular baseline. That value can be found in metadata file (titled <font face='Courier New'>$<$primary timestamp$>$_$<$secondary timestamp$>$.txt</font>) that comes with the original interferogram. Generally, we would want the true baseline for each interferogram. However, since Sentinel-1 has such a short baseline, a value of 0.0 m is sufficient for our purposes. </font></font> <font face='Calibri' size='4'> <b>1.2 Create 'date.mli.par' File </b></font> <br> <font face='Calibri' font size='3'> As we are using GAMMA products, we must create a 'date.mli.par' file from which GIAnT will pull necessary information. If another processing technique is used to create the interferograms, an alternate file name and file inputs are required. <br><br> <b>1.2.0 Make a list of paths to all of the unwrapped interferograms</b> </font> ``` files = [f for f in os.listdir(corrected_folder) if f.endswith(f'{unw_corr}tif')] print(len(files)) print(*files, sep="\n") print(f'\n\nCurrent Working Directory: {os.getcwd()}') print(f'radar_tiff path: {radar_tiff}') ``` <font face='Calibri' font size='3'><b>1.2.1 Gather metadata required by GIAnT and save it to a date.mli.par file</b></font> ``` def get_primary_insar_aquisition_date(ingram_name): regex = '[0-9]{8}T[0-9]{6}' match = re.search(regex, ingram_name) if match: return match[0] ds = gdal.Open(radar_tiff, gdal.GA_ReadOnly) # Get WIDTH (xsize; AKA 'Pixels') and FILE_LENGTH (ysize; AKA 'Lines') information n_lines = ds.RasterYSize n_pixels = ds.RasterXSize ds = None # Get the center line UTC time stamp; can also be found inside <date>_<date>.txt file ingram_name = os.listdir(ingram_folder)[0] tstamp = get_primary_insar_aquisition_date(ingram_name) c_l_utc = int(tstamp[0:2])*3600 + int(tstamp[2:4])*60 + int(tstamp[4:6]) # radar frequency; speed of light divided by radar wavelength of Sentinel-1 in meters rfreq = 299792548.0 / 0.055465763 # write the 'date.mli.par' file with open(os.path.join(giant_dir, 'date.mli.par'), 'w') as fid: # when using GAMMA products, GIAnT requires the radar frequency. Everything else is in wavelength (m) fid.write(f'radar_frequency: {rfreq} \n') # Method from Tom Logan's prepGIAnT code; can also be found inside <date>_<date>.txt file fid.write(f'center_time: {c_l_utc} \n') # inside <date>_<date>.txt file; can be hardcoded or set up so code finds it. fid.write(f'heading: {heading_avg} \n') # number of lines in direction of the satellite's flight path fid.write(f'azimuth_lines: {n_lines} \n') # number of pixels in direction perpendicular to satellite's flight path fid.write(f'range_samples: {n_pixels} \n') ``` <font face='Calibri' font size='3'><b>1.2.2 Print the metadata stored in 'date.mli.par'</b></font> ``` with open(os.path.join(giant_dir, 'date.mli.par'), 'r') as fid: print(fid.read()) ``` <font face='Calibri'><font size='4'><b>1.3 Create prepxml_SBAS.py Function</b> </font> <br> <font size='3'>We will create a prepxml_SBAS.py function and put it into our GIAnT working directory.</font> </font> <font face='Calibri'> <font size='3'><b>Necessary prepxml_SBAS.py edits</b></font> <br> <font size='3'> GIAnT comes with an example prepxml_SBAS.py, but requries significant edits for our purposes. These alterations have already been made, so we don't have to do anything now, but it is good to know the kinds of things that have to be altered. The details of some of these options can be found in the GIAnT documentation. The rest must be found in the GIAnT processing files themselves, most notably the tsxml.py and tsio.py functions. <br>The following alterations were made: <br> - Changed 'example' &#9658; 'date.mli.par' - Removed 'xlim', 'ylim', 'rxlim', and 'rylim' - These are used for clipping the files in GIAnT. As we have already done this, it is not necessary. - Removed latfile='lat.map' and lonfile='lon.map' - These are optional inputs for the latitude and longitude maps. - Removed hgtfile='hgt.map' - This is an optional altitude file for the sensor. - Removed inc=21. - This is the optional incidence angle information. - It can be a constant float value or incidence angle file. - For Sentinel1, it varies from 29.1-46.0&deg;. - Removed masktype='f4' - This is the mask designation. - We are not using any masks for this. - Changed unwfmt='RMG' &#9658; unwfmt='GRD' - Read data using GDAL. - Removed demfmt='RMG' - Changed corfmt='RMG' &#9658; corfmt='GRD' - Read data using GDAL. - Changed nvalid=30 -> nvalid=1 - This is the minimum number of interferograms in which a pixel must be coherent. A particular pixel will be included only if its coherence is above the coherence threshold, cohth, in more than nvalid number of interferograms. - Removed atmos='ECMWF' - This is an amtospheric correction command. It depends on a library called 'pyaps' developed for GIAnT. This library has not been installed yet. - Changed masterdate='19920604' &#9658; masterdate='20161119' - Use our actual masterdate. - I simply selected the earliest date as the masterdate.</font> <br><br> <font size='3'><b>1.3.0 Define some prepxml inputs</b> <br> The reference region and related variables</font></font></font> ``` use_ref_region = False filt = 1.0 / 12 # Start with a temporal filter in length of years ref_region_size = [5, 5] # Reference region size in Lines and Pixels ref_region_center = [-0.9, -91.3] # Center of reference region in lat, lon coordinates rxlim = [0, 10] rylim = [95, 105] primary_date = min([amps[i][0:8] for i in range(len(amps))], key=int) # set the primary date. print(f"Primary Date: {primary_date}") ``` <font face='Calibri'><font size='3'><b>1.3.1 Create the prepxml Python script</b></font> ``` if use_ref_region == True: use_ref = '' else: use_ref = '#' prepxml_sbas_template = ''' #!/usr/bin/env python """Example script for creating XML files for use with the SBAS processing chain. This script is supposed to be copied to the working directory and modified as needed.""" import sys tsinsar_pth = '/home/jovyan/.local/GIAnT' if tsinsar_pth not in sys.path: sys.path.append(tsinsar_pth) import tsinsar as ts import argparse import numpy as np def parse(): parser= argparse.ArgumentParser(description='Preparation of XML files for setting up the processing chain. Check tsinsar/tsxml.py for details on the parameters.') parser.parse_args() parse() g = ts.TSXML('data') g.prepare_data_xml( '{0}/date.mli.par', proc='GAMMA', {7}rxlim = [{1},{2}], rylim=[{3},{4}], inc = 21., cohth=0.10, unwfmt='GRD', corfmt='GRD', chgendian='True', endianlist=['UNW','COR']) g.writexml('data.xml') g = ts.TSXML('params') g.prepare_sbas_xml(nvalid=1, netramp=True, #atmos='NARR', demerr=False, uwcheck=False, regu=True, masterdate='{5}', filt={6}) g.writexml('sbas.xml') ############################################################ # Program is part of GIAnT v1.0 # # Copyright 2012, by the California Institute of Technology# # Contact: earthdef@gps.caltech.edu # ############################################################ ''' with open(os.path.join(giant_dir, 'prepxml_SBAS.py'), 'w') as fid: fid.write(prepxml_sbas_template.format(giant_dir, rxlim[0], rxlim[1], rylim[0], rylim[1], primary_date, filt,use_ref)) ``` <font face='Calibri'><font size='3'><b>1.3.2 Print the prepxml script</b></font> ``` with open(os.path.join(giant_dir, 'prepxml_SBAS.py'), 'r') as fid: print(fid.read()) ``` <font face='Calibri'><font size='4'><b>1.4 Create userfn.py script</b></font> <br> <font size='3'>This file maps the interferogram dates to a physical file on disk. This python file must be in our working directory, <b>/GIAnT</b>. <br><br> <b>1.4.0 Write userfn.py</b> </font> ``` userfn_template = """ #!/usr/bin/env python import os def makefnames(dates1, dates2, sensor): dirname = '{0}' root = os.path.join(dirname, dates1+'_'+dates2) unwname = root+'{1}'+'flt' # for potentially disruptive default values removed. corname = root+'_corr.flt' return unwname, corname """ with open(os.path.join(giant_dir, 'userfn.py'), 'w') as fid: fid.write(userfn_template.format(giant_data, unw_corr)) ``` <font face='Calibri'><font size='3'><b>1.4.1 Print userfn.py</b></font> ``` with open(os.path.join(giant_dir, 'userfn.py'), 'r') as fid: print(fid.read()) ``` <font face='Calibri'> <font size='5'> <b> 2. Prepare Data for GIAnT </b> </font> <br> <font size='3'> Our resultant files need to be adjusted for input into GIAnT. This involves: <ul> <li>Adjusting filenames to start with the date</li> <li>(Optional) Removing potentially disruptive default values</li> <li>Converting data format from '.tif' to '.flt'</li> </ul> </font> </font> <font face='Calibri'> <font size='4'><b>2.1 Adjust File Names</b></font> <font size='3'><br>GIAnT requires the files to have a simple format of <font face='Courier New'>&lt;primary_date&gt;-&lt;secondary_date&gt;_&lt;unwrapped or coherence designation&gt;.tiff</font>. <br><br> <font color='green'><b>We already did this step in Part 1, so section 2.1 is just a reminder that it is also a requirement for GIAnT.</b></font> </font> </font> <font face='Calibri'> <font size='4'><b>2.2 Remove disruptive default values</b></font> <br> <font size='3'>Now we can remove the potentially disruptive default values from the unwrapped interferograms. For this lab, this step is optional. This is because the Sentinel-1 data does not have any of the disruptive default values. However, for other datasources, this may be required.<br>This works by creating an entirely new geotiff with the text <font face='Courier New'>'\_no\_default'</font> added to the file name. <br><br> <b>2.2.0 Write functions to gather and print paths via a wildcard path.</b> </font> ``` def get_tiff_paths(paths): tiff_paths = glob.glob(paths) tiff_paths.sort() return tiff_paths def print_tiff_paths(tiff_paths): for p in tiff_paths: print(f"{p}\n") ``` <font face='Calibri'><font size='3'><b>2.2.1 Gather the paths to the uncorrected and corrected unw_phase tifs</b></font> ``` paths_unc = f"{corrected_folder}/*{unw}tif" paths_corr = f"{corrected_folder}/*{unw_corr}tif" files_unc = get_tiff_paths(paths_unc) files_corr = get_tiff_paths(paths_corr) print_tiff_paths(files_unc) print_tiff_paths(files_corr) ``` <font face='Calibri'><font size='3'><b>2.2.2 Decide if you wish to replace dispruptive NaN values with zeros</b> <br> True = replace NaNs <br> False = keep NaNs </font> ``` replace_nans = False ``` <font face='Calibri'><font size='3'><b>2.2.3 Write a function to remove disruptive (NaN) values</b></font> ``` def replace_nan_values(paths): for file in paths: outfile = os.path.join(analysis_directory, file.replace('.tif','_no_default.tif')) cmd = f"gdal_calc.py --calc=\"(A>-1000)*A\" --outfile={outfile} -A {analysis_directory}/{file} --NoDataValue=0 --format=GTIFF" subprocess.call(cmd, shell=True) ``` <font face='Calibri'> <font size='3'><b>2.2.4 Remove files that have potentially disruptive default values.</b> This step will run only if there is a file with '\_no\_default' in the <font face='Courier New' size='2'>corrected_folder</font> directory.</font> </font> ``` if replace_nans: replace_nan_values(files_unc) replace_nan_values(files_corr) # change 'unw' and 'unw_corr' so the appropriate files will still be found in later code. unw = unw.replace('_unw_phase', '_unw_phase_no_default') unw_corr = unw_corr.replace('_corrected', '_corrected_no_default') else: print("Skipping the removal of disruptive values.") ``` <font face='Calibri'> <font size='4'><b>2.3 Convert data format from '.tif' to '.flt'</b><br></font> <font size='3'>This is a requirement of GIAnT <br><br> <b>2.3.0 Gather the paths to the files to convert</b></font></font> ``` # Find the unwrapped phase files to convert. paths_unc = f"{corrected_folder}/*{unw}tif" paths_corr = f"{corrected_folder}/*{unw_corr}tif" paths_cohr = f"{subset_folder}/*{corr}tif" files_unc = get_tiff_paths(paths_unc) files_corr = get_tiff_paths(paths_corr) files_cohr = get_tiff_paths(paths_cohr) # file format should appear as below # YYYYMMDD-YYYYMMDD_unw_phase.flt # OR, if default values have been removed... # YYYYMMDD-YYYYMMDD_unw_phase_no_default.flt print_tiff_paths(files_unc) print_tiff_paths(files_corr) print_tiff_paths(files_cohr) ``` <font face='Calibri'><font size='3'><b>2.3.1 Convert the .tif files to .flt files</b> <br> tiff_to_flt creates 3 files: '*.flt', '*.flt.aux.xml', and '*.hdr', where the asterisk, '*', is replaced with the file name</font> ``` def tiff_to_flt(paths): for file in paths: newname, old_ext = os.path.splitext(file) # Create system command that will convert the file from a .tiff to a .flt cmd = f"gdal_translate -of ENVI {file} {file.replace('.tif','.flt')}" try: #print(f"cmd = {cmd}") # display what the command looks like. # pass command to the system subprocess.call(cmd, shell=True) except: print(f"Problem with command: {cmd}") print("Conversion from '.tif' to '.flt' complete.") tiff_to_flt(files_unc) tiff_to_flt(files_corr) tiff_to_flt(files_cohr) ``` <font face = 'Calibri' size='3'><b>2.3.1 Gather the paths to the '\*.flt', '\*.hdr', and '\*.aux.xml' files</b></font> ``` paths_flt = f"*/*.flt" paths_hdr = f"*/*.hdr" paths_aux = f"*/*.flt.aux.xml" files_flt = get_tiff_paths(paths_flt) files_hdr = get_tiff_paths(paths_hdr) files_aux = get_tiff_paths(paths_aux) print_tiff_paths(files_flt) print_tiff_paths(files_hdr) print_tiff_paths(files_aux) ``` <font face='Calibri'><font size='3'><b>2.3.2 Move the files and delete the extraneous '.flt.aux.xml' files</b></font> ``` def move_list_of_files(paths, new_analysis_directory): for file in paths: path, name = os.path.split(file) try: shutil.move(file,os.path.join(new_analysis_directory, name)) except FileNotFoundError as e: raise type(e)(f"Failed to find {file}") move_list_of_files(files_flt, giant_data) move_list_of_files(files_hdr, giant_data) for file in files_aux: os.remove(file) ``` <font face='Calibri'> <font size='4'> <b>2.4 Run prepxml_SBAS.py </b> </font> <br> <font size='3'> Here we run <b>prepxml_SBAS.py</b> to create the 2 needed files - data.xml - sbas.xml To use MinTS, we would create and run <b>prepxml_MinTS.py</b> to create - data.xml - mints.xml These files are needed by <b>PrepIgramStack.py</b>. </font> <br><br> <font size='3'><b>Define the path to the GIAnT module, change into giantDir, and run prepxml_SBAS.py</b> <br> Note: We have to change into giant_dir due to GIAnT's use of relative paths to find expected files. <br><br> <b>2.4.0 Define the path to the GIAnT installation and move into giant_dir (in your analysis directory)</b></font> ``` giant_path = "/home/jovyan/.local/GIAnT/SCR" #install cython (replaces weave. Needed for running GIAnT in Python 3) # !pip install --user cython try: os.chdir(giant_dir) except FileNotFoundError as e: raise type(e)(f"Failed to find {file}") print(f"current directory: {os.getcwd()}\n") for file in glob.glob('*.*'): print(file) ``` <font face='Calibri' size='3'><b>2.4.1 Download GIAnT from the asf-jupyter-data S3 bucket</b> <br> GIAnT is no longer supported (Python 2). This unofficial version of GIAnT has been partially ported to Python 3 to run this notebook. Only the portions of GIAnT used in this notebook have been tested. </font> ``` if not os.path.exists("/home/jovyan/.local/GIAnT"): download_path = 's3://asf-jupyter-data/GIAnT_5_21.zip' output_path = f"/home/jovyan/.local/{os.path.basename(download_path)}" !aws --region=us-east-1 --no-sign-request s3 cp $download_path $output_path if os.path.isfile(output_path): !unzip $output_path -d /home/jovyan/.local/ os.remove(output_path) ``` <font face='Calibri'><font size='3'><b>2.4.2 Run prepxml_SBAS.py</b></font> ``` !python prepxml_SBAS.py ``` <font face='Calibri' size='3'><b>2.4.3 View the newly created data.xml</b></font> ``` with open('data.xml', 'r') as f: print(f.read()) ``` <font face='Calibri' size='3'><b>2.4.4 View the newly created 'sbas.xml'</b></font> ``` with open('sbas.xml', 'r') as f: print(f.read()) ``` <font face='Calibri'><font size='5'><b>3. Run GIAnT</b></font> <br> <font size='3'>We have now created all of the necessary files to run GIAnT. The full GIAnT process requires 3 function calls. <ul> <li>PrepIgramStack.py</li> <li>ProcessStack.py</li> <li>SBASInvert.py</li> </ul> We will make a 4th function call that is not necessary, but provides some error estimation that can be useful. <ul> <li>SBASxval.py</li> </ul> </font> <font face='Calibri'> <font size='4'> <b>3.0 Run PrepIgramStack.py </b> </font> <br> <font size='3'> Here we run <b>PrepIgramStack.py</b> to create the files for GIAnT. This will read in the input data and the files we previously created. This will output HDF5 files. As we did not have to modify <b>PrepIgramStack.py</b>, we will call from the installed GIAnT library. <br> Inputs: - ifg.list - data.xml - sbas.xml Outputs: - RAW-STACK.h5 - PNG previews under 'Igrams' folder </font> </font> <br> <font face='Calibri' size='3'><b>3.0.0 Display the help information for PrepIgramStack.py</b></font> ``` !python $giant_path/PrepIgramStack.py -h ``` <font face='Calibri' size='3'><b>3.0.1 Run PrepIgramStack.py</b> <br> Note: The processing status bar may not fully complete when the script is finished running. This is okay.</font> ``` !python $giant_path/PrepIgramStack.py -i ifg.list # The '-i ifg.list' is technically unnecessary as that is the default. ``` <font face='Calibri' size='3'><b>3.0.2 Confirm the correct HDF5 file format</b></font> ``` file = os.path.join('Stack','RAW-STACK.h5') if not h5py.is_hdf5(file): print(f'Not an HDF5 file:{file}') else: print("It's an HDF5 file") ``` <font face='Calibri'> <font size='4'> <b>3.1 Run ProcessStack.py </b> </font> <br> <font size='3'> This seems to be an optional step. Does atmospheric corrections and estimation of orbit residuals. <br> Inputs: - HDF5 files from PrepIgramStack.py, RAW-STACK.h5 - data.xml - sbas.xml - GPS Data (optional; we don't have this) - Weather models (downloaded automatically) Outputs: - HDF5 files, PROC-STACK.h5 These files are then fed into SBAS. </font> </font> <br><br> <font face='Calibri' size='3'><b>3.1.0 Display the help information for ProcessStack.py</b></font> ``` !python $giant_path/ProcessStack.py -h ``` <font face='Calibri' size='3'><b>3.1.1 Run ProcessStack.py</b> <br> Note: The processing status bars may never fully complete. This is okay.</font> ``` !python $giant_path/ProcessStack.py ``` <font face='Calibri' size='3'><b>3.1.2 Confirm the correct HDF5 file format</b></font> ``` file = os.path.join('Stack','PROC-STACK.h5') #print(files) if not h5py.is_hdf5(file): print(f'Not an HDF5 file:{file}') else: print("It's an HDF5 file!") ``` <font face='Calibri'> <font size='4'> <b>3.2 Run SBASInvert.py </b> </font> <br> <font size='3'> Run the time series. Inputs <ul> <li>HDF5 file, PROC-STACK.h5</li> <li>data.xml</li> <li>sbas.xml</li> </ul> Outputs <ul> <li>HDF5 file: LS-PARAMS.h5</li> </ul> </font> </font> <br> <font face='Calibri' size='3'><b>3.2.0 Display the help information for SBASInvert.py</b></font> ``` !python $giant_path/SBASInvert.py -h ``` <font face='Calibri' size='3'><b>3.2.1 Run SBASInvert.py</b> <br><br> Note: The processing status bar may not fully complete when the script is finished running. This is okay.</font> ``` !python $giant_path/SBASInvert.py ``` <font face='Calibri'> <font size='4'> <b>3.3 Run SBASxval.py </b> </font> <br> <font size='3'> Get an uncertainty estimate for each pixel and epoch using a Jacknife test. This is often the most time consuming portion of the code. Inputs: <ul> <li>HDF5 files, PROC-STACK.h5</li> <li>data.xml</li> <li>sbas.xml</li> </ul> Outputs: <ul> <li>HDF5 file, LS-xval.h5</li> </ul> </font> </font> <br> <font face='Calibri' size='3'><b>3.3.0 Display the help information for SBASxval.py</b></font> ``` !python $giant_path/SBASxval.py -h ``` <font face='Calibri' size='3'><b>3.3.1 Run SBASInvert.py</b> <br><br> Note: The processing status bar may not fully complete when the script is finished running. This is okay.</font> ``` !python $giant_path/SBASxval.py ``` <font face='Calibri' size='4'><b>3.4 Having completed our GIAnT processing, return to the analysis' analysis_directory directory</b></font> ``` os.chdir(analysis_directory) print(f'Current directory: {os.getcwd()}') ``` <font face='Calibri'><font size='5'><b>4. Data Visualization</b></font> <br><br> <font size='4'><b>4.0 Prepare data for visualization</b></font> <br> <font size='3'><b>4.0.0 Load the LS-PARAMS stack produced by GIAnT and read it into an array so we can manipulate and display it.</b></font></font> ``` filename = os.path.join(giant_dir, 'Stack/LS-PARAMS.h5') f = h5py.File(filename, 'r') # List all groups group_key = list(f.keys()) # get list of all keys. print(f"group_key: {group_key}") # print list of keys. ``` <font face='Calibri' size='3'><b>4.0.1 Display LS-PARAMS info with gdalinfo</b></font> ``` !gdalinfo {filename} ``` <font face='Calibri'><font size='3'><b>4.0.2 Load the LS-xval stack produced by GIAnT and read it into an array so we can manipulate and display it.</b></font></font> ``` filename = os.path.join(giant_dir, 'Stack/LS-xval.h5') error = h5py.File(filename, 'r') # List all groups error_key = list(error.keys()) # get list of all keys. print(f"error_key: {error_key}") # print list of keys. ``` <font face='Calibri' size='3'><b>4.0.3 Display LS-xval info with gdalinfo</b></font> ``` print(gdal.Info(filename)) ``` <font face='Calibri'><font size='3'>Details on what each of these keys in group_key and error_key means can be found in the GIAnT documentation. For now, the only keys with which we are concerned are 'recons' (the filtered time series of each pixel) and 'dates' (the dates of acquisition). It is important to note that the dates are given in a type of Julian Day number called Rata Die number which we convert to Gregorian dates below. </font></font> <br><br> <font face='Calibri'><font size='3'><b>4.0.4 Get the relevant data and error values from our stacks and confirm that the number of rasters in our data stack, the number of error points, and the number of dates are all the same.</b></font></font> ``` # Get our data from the stack data_cube = f['recons'][()] # Get our error from the stack error_cube = error['error'][()] # Get the dates for each raster from the stack dates = list(f['dates']) # these dates appear to be given in Rata Die style: floor(Julian Day Number - 1721424.5). # Check that the number of rasters in the data cube, error cube, and the number of dates are the same. if data_cube.shape[0] is not len(dates) or error_cube.shape[0] is not len(dates): print('Problem') print('Number of rasters in data_cube: ', data_cube.shape[0]) print('Number of rasters in error_cube: ', error_cube.shape[0]) print('Number of dates: ', len(dates)) else: print('The number of dates and rasters match.') ``` <font face='Calibri'><font size='3'><b>4.0.5 Convert from Rata Die number (similar to Julian Day number) contained in 'dates' to Gregorian date. </b></font></font> ``` tindex = [] for d in dates: tindex.append(date.fromordinal(int(d))) ``` <font face='Calibri'><font size='3'><b>4.0.6 Create an amplitude image of the volcano.</b></font></font> ``` radar = gdal.Open(radar_tiff) # open my radar tiff using GDAL im_radar = radar.GetRasterBand(1).ReadAsArray() # access the band information dbplot = np.ma.log10(im_radar) # plot as a log10 dbplot[isneginf(dbplot)] = 0 ``` <font face='Calibri'> <font size='4'><b>4.1 Select a Point-of-Interest</b></font> <br><br> <font size='3'><b>4.1.0 Write a class to create an interactive matplotlib plot that displays an overlay of the clipped deformation map and amplitude image, and allows the user to select a point of interest.</b></font></font> ``` class pixelPicker: def __init__(self, image1, image2, width, height): self.x = None self.y = None self.fig = plt.figure(figsize=(width, height), tight_layout=True) self.fig.tight_layout() self.ax = self.fig.add_subplot(111, visible=False) self.rect = patches.Rectangle( (0.0, 0.0), width, height, fill=False, clip_on=False, visible=False, ) self.rect_patch = self.ax.add_patch(self.rect) self.cid = self.rect_patch.figure.canvas.mpl_connect( 'button_press_event', self ) self.image1 = image1 self.image2 = image2 self.plot = self.defNradar_plot(self.image1, self.image2, self.fig, return_ax=True) self.plot.set_title('Select a Point of Interest from db-Scaled Amplitude Image') def defNradar_plot(self, deformation, radar, fig, return_ax=False): ax = fig.add_subplot(111) vmin = np.percentile(radar, 3) vmax = np.percentile(radar, 97) im = ax.imshow(radar, cmap='gray', vmin=vmin, vmax=vmax) vmin = np.percentile(deformation, 3) vmax = np.percentile(deformation, 97) fin_plot = ax.imshow(deformation, cmap='RdBu', vmin=vmin, vmax=vmax, alpha=0.75) cbar = fig.colorbar(fin_plot, fraction=0.24, pad=0.02) cbar.ax.set_xlabel('mm') cbar.ax.set_ylabel('Deformation', rotation=270, labelpad=20) #ax.set(title="Integrated Defo [mm] Overlaid on Clipped db-Scaled Amplitude Image") plt.grid() if return_ax: return(ax) def __call__(self, event): print('click', event) self.x = event.xdata self.y = event.ydata for pnt in self.plot.get_lines(): pnt.remove() plt.plot(self.x, self.y, 'ro') ``` <font face='Calibri'><font size='3'><b>4.1.1 Create the interactive point of interest plot, and select a point</b></font></font> ``` fig_xsize = 9 fig_ysize = 5 deformation = data_cube[data_cube.shape[0]-1] my_plot = pixelPicker(deformation, dbplot, fig_xsize, fig_ysize) ``` <font face='Calibri' size='3'><b>4.1.2 Grab the line and pixel for the selected POI</b></font> ``` my_line = ceil(my_plot.y) my_pixel = ceil(my_plot.x) print(f'my_line: {my_line}') print(f'my_pixel: {my_pixel}') ``` <font face='Calibri'> <font size='4'><b>4.2 Visualize the data for the selected POI</b></font> <br><br> <font size='3'><b>4.2.0 Write a function to visualize the time series for a single pixel (POI) as well as the associated error for that pixel.</b></font></font> ``` def time_series_with_error(deformation, radar, series_d, series_e, my_line, my_pixel, tindex, fig_xsize, fig_ysize): # Create base figure; 2 rows, 1 column fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(fig_xsize,fig_ysize*2), gridspec_kw={'width_ratios':[1],'height_ratios':[1,1]}) # Plot radar image with deformation in left column with crosshair over pixel of interest vmin = np.percentile(radar, 3) vmax = np.percentile(radar, 97) axes[0].imshow(radar, cmap='gray', vmin=vmin, vmax=vmax, aspect='equal') vmin = np.percentile(deformation, 3) vmax = np.percentile(deformation, 97) fin_plot = axes[0].imshow(deformation, cmap='RdBu', vmin=vmin, vmax=vmax, alpha=0.75, aspect='equal') cbar = fig.colorbar(fin_plot, fraction=0.24, pad=0.02, ax=axes[0]) cbar.ax.set_xlabel('mm') cbar.ax.set_ylabel('Deformation', rotation=270, labelpad=20) axes[0].set(title="Integrated Defo [mm] Overlain on\nClipped db-Scaled Amplitude Image") axes[0].grid() # overlay a grid on the image. # Put crosshair over POI in first figure. axes[0].plot(my_pixel, my_line, 'cx', markersize=12, markeredgewidth=4) # create a cyan x ('cx') at location [myPixel,myLine] axes[0].legend(labels=['POI']) # Put in a legend with the label 'POI' # Plot time series of pixel in right column with error bars # Make pandas time series object ts_d = pd.Series(series_d, index=tindex) # Plot the time series object with the associated error. ts_d.plot(marker='.', markersize=6, yerr=series_e) axes[1].legend(labels=[f'Time Series for POI at ({my_line}, {my_pixel})']) axes[1].set(title="Integrated Defo [mm] with Error Estimates for a Single Pixel") plt.xlabel('Date') plt.ylabel('Deformation [mm]') for tick in axes[1].get_xticklabels(): tick.set_rotation(90) plt.grid() # overlay a grid on the time series plot. ``` <font face='Calibri'><font size='3'><b>4.2.1 Plot the time series for the selected POI</b></font></font> ``` series_d = data_cube[:, my_line, my_pixel] series_e = error_cube[:, my_line, my_pixel] time_series_with_error(deformation, dbplot, series_d, series_e, my_line, my_pixel, tindex, fig_xsize, fig_ysize) ``` <font face='Calibri'><font size='3'><b>4.2.2 Create an animation of the deformation</b></font></font> ``` %%capture fig = plt.figure(figsize=(14,8)) ax = fig.add_subplot(111) #ax.axis('off') vmin=np.percentile(data_cube.flatten(), 5) vmax=np.percentile(data_cube.flatten(), 95) vmin = np.percentile(deformation, 3) vmax = np.percentile(deformation, 97) im = ax.imshow(data_cube[0], cmap='RdBu', vmin=vmin, vmax=vmax) ax.set_title("Animation of Deformation Time Series - Sierra Negra, Galapagos") cbar = fig.colorbar(im) cbar.ax.set_xlabel('mm') cbar.ax.set_ylabel('Deformation', rotation=270, labelpad=20) plt.grid() def animate(i): ax.set_title("Date: {}".format(tindex[i])) im.set_data(data_cube[i]) ani = matplotlib.animation.FuncAnimation(fig, animate, frames=data_cube.shape[0], interval=400) rc('animation', embed_limit=10.0**9) # set the maximum animation size allowed. ``` <font face='Calibri'><font size='3'><b>4.2.3 Display the animation</b></font></font> ``` HTML(ani.to_jshtml()) ``` <font face='Calibri'><font size='3'><b>Define a prefix to prepend to all output files for identification purposes</b></font></font> ``` while True: prefix = input("Enter an identifiable prefix to prepend to output files: ") if re.search('\W', prefix): print(f"\n\"{prefix}\" contains invalid characters. Please try again.") else: break ``` <font face='Calibri'><font size='3'><b>4.2.5 Save the animation as a gif</b></font></font> ``` ani_path = os.path.join(output_dir, f"{prefix}_filt={filt}_{date.today()}.gif") ani.save(ani_path, writer='pillow', fps=2) ``` <font face='Calibri'><font size='3'>Note: 'date.today()' returns the current date from the system on which it is called. As OpenSAR Lab runs in machines on the East coast of the United States, date.today() will return the date based on Eastern Standard Time (EST).</font> </font> <font face='Calibri'><font size='5'><b>5. HDF5 TO GEOTIFF</b></font> <br> <font size='3'>Convert the HDF5 file to a series of geolocated geotiffs. This method comes from an answer to this <a href="https://gis.stackexchange.com/questions/37238/writing-numpy-array-to-raster-file" target="_blank">StackExchange question</a> which is based on a recipe from the <a href="https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html#create-raster-from-array">Python GDAL/OGR Cookbook</a>.</font> <br> <font size='4'> <b>5.0 Display the size of the data-stack</b> </font> </font> ``` print(f"Number of rasters: {data_cube.shape[0]}") print(f"Height & Width in Pixels: {data_cube.shape[1]}, {data_cube.shape[2]}") ``` <font face='Calibri'><font size='4'><b>5.1 Get raster information from one of the subsets.</b></font></font> ``` print(files_corr[0]) src = gdal.Open(files_corr[0]) geo_transform = src.GetGeoTransform() del src ``` <font face='Calibri'><font size='4'><b>5.2 Write a function to convert a numpy array into a geotiff</b></font></font> ``` def array_to_geotiff(in_raster, geo_transform, array, epsg): cols = array.shape[1] rows = array.shape[0] driver = gdal.GetDriverByName('GTiff') out_raster = driver.Create(in_raster, cols, rows, 1, gdal.GDT_Float32) out_raster.SetGeoTransform(geo_transform) outband = out_raster.GetRasterBand(1) outband.WriteArray(array) out_raster_srs = osr.SpatialReference() out_raster_srs.ImportFromEPSG(epsg) out_raster.SetProjection(out_raster_srs.ExportToWkt()) outband.FlushCache() ``` <font face='Calibri'><font size='4'><b>5.3 Create the geotiffs</b></font></font> ``` for i in range(0, data_cube.shape[0]): try: geotiff_path = os.path.join(output_dir, f"{prefix}_{tindex[i]}.tif") print(f"{i}: {geotiff_path}") array = data_cube[i, :, :].copy() array_to_geotiff(geotiff_path, geo_transform, array, int(part1_pickle['utm'])) print(f"Geotiff {i+1} of {data_cube.shape[0]} created\nFile path: {geotiff_path}") except: print(f"Geotiff {i+1} of {data_cube.shape[0]} FAILED\nFile path: {geotiff_path}") ``` <font face='Calibri'><font size='5'><b>6. Alter the time filter parameter</b></font><br> <font size='3'>Looking at the video above, you may notice that the deformation has a very smoothed appearance. This may be because of our time filter which is currently set to 1 year ('filt=1.0' in the prepxml_SBAS.py code). Let's repeat the lab from there with 2 different time filters. <br>First, using no time filter ('filt=0.0') and then using a 1 month time filter ('filt=0.082'). Change the output filename prefix for anything you want saved (e.g., 'SierraNegraDeformationTS.gif' to 'YourDesiredFileName.gif'). Otherwise, it will be overwritten. <br> <ul> <li>How did these changes affect the output time series?</li> <li>How might we figure out the right filter length?</li> <li>What does this say about the parameters we select?</li> </ul> </font></font> <font face='Calibri'><font size='5'><b>7. Clear data from the Notebook (optional)</b></font> <br> <font size='3'>This lab has produced a large quantity of data. If you look at this notebook in your analysis_directory directory, it should now be ~80 MB. This can take a long time to load in a Jupyter Notebook. It may be useful to clear the cell outputs, which will restore the Notebook to its original size. <br>To clear the cell outputs, go Cell->All Output->Clear. This will clear the outputs of the Jupyter Notebook and restore it to its original size of ~60 kB. This will not delete any of the files we have created. </font> </font> <br> <div class="alert alert-success"> <font face="Calibri" size="5"> <b> <font color='rgba(200,0,0,0.2)'> <u>ASSIGNMENT ##</u>: </font> Explore the effect of Atmospheric Correction </b> <font color='rgba(200,0,0,0.2)'> -- [## Points] </font> </font> <font face="Calibri" size="3"> <u>Compare corrected and uncorrected time series for selected pixels</u>: <ol type="1"> <li>Repeat the time series using the original subsets (i.e., those that TRAIN did not correct). MAKE SURE TO SAVE IT AS A DIFFERENT FILE. Hint: userfn.py will need to be modified. <font color='rgba(200,0,0,0.2)'> -- [## Point] </font></li> <br> <li>Show a plot of deformation through time for 3 selected pixels. Each plot should have the corrected and uncorrected time series for the selected pixels. Makes sure to select at least 1 point near the summit of the volcano (where deformation should be the greatest) and 1 point at low elevation (where deformation should be relatively small). The location of the third point is at your discretion. Hint: the variables 'myLine' and 'myPixel' can be made into a pair of lists over which a loop is run. <font color='rgba(200,0,0,0.2)'> -- [## Points] </font></li> </ol> </font> </div> <hr> <font face="Calibri" size="2"> <i>GEOS 657-Lab9-InSARTimeSeriesAnalysis-Part2-GIAnT.ipynb - Version 3.0.1 - May 2021 <br> <b>Version Changes:</b> <ul> <li>Prepare for insar_analysis conda env</li> </ul> </i> </font> </font>
github_jupyter
*Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017 Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition Code License: [MIT License](https://github.com/rasbt/python-machine-learning-book-2nd-edition/blob/master/LICENSE.txt) ``` from google.colab import drive drive.mount('/content/drive') ``` # Implementing a Multi-Layer Perceptron learning algorithm in Python ``` from IPython.display import Image %matplotlib inline from keras import layers from keras import models from keras.utils import to_categorical ``` # Classifying handwritten digits ## An object-oriented multi-layer perceptron API ``` import numpy as np import sys class NeuralNetMLP(object): """ Feedforward neural network / Multi-layer perceptron classifier. Parameters ------------ n_hidden : int (default: 30) Number of hidden units. l2 : float (default: 0.) Lambda value for L2-regularization. No regularization if l2=0. (default) epochs : int (default: 100) Number of passes over the training set. eta : float (default: 0.001) Learning rate. shuffle : bool (default: True) Shuffles training data every epoch if True to prevent circles. minibatch_size : int (default: 1) Number of training samples per minibatch. seed : int (default: None) Random seed for initalizing weights and shuffling. Attributes ----------- eval_ : dict Dictionary collecting the cost, training accuracy, and validation accuracy for each epoch during training. """ def __init__(self, n_hidden=30, l2=0., epochs=100, eta=0.001, shuffle=True, minibatch_size=1, seed=None): self.random = np.random.RandomState(seed) self.n_hidden = n_hidden self.l2 = l2 self.epochs = epochs self.eta = eta self.shuffle = shuffle self.minibatch_size = minibatch_size def _onehot(self, y, n_classes): """Encode labels into one-hot representation Parameters ------------ y : array, shape = [n_samples] Target values. Returns ----------- onehot : array, shape = (n_samples, n_labels) """ onehot = np.zeros((n_classes, y.shape[0])) for idx, val in enumerate(y.astype(int)): onehot[val, idx] = 1. return onehot.T def _sigmoid(self, z): """Compute logistic function (sigmoid)""" return 1. / (1. + np.exp(-np.clip(z, -250, 250))) def _forward(self, X): """Compute forward propagation step""" # step 1: net input of hidden layer # [n_samples, n_features] dot [n_features, n_hidden] # -> [n_samples, n_hidden] z_h = np.dot(X, self.w_h) + self.b_h # step 2: activation of hidden layer a_h = self._sigmoid(z_h) # step 3: net input of output layer # [n_samples, n_hidden] dot [n_hidden, n_classlabels] # -> [n_samples, n_classlabels] z_out = np.dot(a_h, self.w_out) + self.b_out # step 4: activation output layer a_out = self._sigmoid(z_out) return z_h, a_h, z_out, a_out def _compute_cost(self, y_enc, output): """Compute cost function. Parameters ---------- y_enc : array, shape = (n_samples, n_labels) one-hot encoded class labels. output : array, shape = [n_samples, n_output_units] Activation of the output layer (forward propagation) Returns --------- cost : float Regularized cost """ L2_term = (self.l2 * (np.sum(self.w_h ** 2.) + np.sum(self.w_out ** 2.))) term1 = -y_enc * (np.log(output)) term2 = (1. - y_enc) * np.log(1. - output) cost = np.sum(term1 - term2) + L2_term # If you are applying this cost function to other # datasets where activation # values maybe become more extreme (closer to zero or 1) # you may encounter "ZeroDivisionError"s due to numerical # instabilities in Python & NumPy for the current implementation. # I.e., the code tries to evaluate log(0), which is undefined. # To address this issue, you could add a small constant to the # activation values that are passed to the log function. # # For example: # # term1 = -y_enc * (np.log(output + 1e-5)) # term2 = (1. - y_enc) * np.log(1. - output + 1e-5) return cost def predict(self, X): """Predict class labels Parameters ----------- X : array, shape = [n_samples, n_features] Input layer with original features. Returns: ---------- y_pred : array, shape = [n_samples] Predicted class labels. """ z_h, a_h, z_out, a_out = self._forward(X) y_pred = np.argmax(z_out, axis=1) return y_pred def fit(self, X_train, y_train, X_valid, y_valid): """ Learn weights from training data. Parameters ----------- X_train : array, shape = [n_samples, n_features] Input layer with original features. y_train : array, shape = [n_samples] Target class labels. X_valid : array, shape = [n_samples, n_features] Sample features for validation during training y_valid : array, shape = [n_samples] Sample labels for validation during training Returns: ---------- self """ n_output = np.unique(y_train).shape[0] # number of class labels n_features = X_train.shape[1] ######################## # Weight initialization ######################## # weights for input -> hidden self.b_h = np.zeros(self.n_hidden) self.w_h = self.random.normal(loc=0.0, scale=0.1, size=(n_features, self.n_hidden)) # weights for hidden -> output self.b_out = np.zeros(n_output) self.w_out = self.random.normal(loc=0.0, scale=0.1, size=(self.n_hidden, n_output)) epoch_strlen = len(str(self.epochs)) # for progress formatting self.eval_ = {'cost': [], 'train_acc': [], 'valid_acc': []} y_train_enc = self._onehot(y_train, n_output) # iterate over training epochs for i in range(self.epochs): # iterate over minibatches indices = np.arange(X_train.shape[0]) if self.shuffle: self.random.shuffle(indices) for start_idx in range(0, indices.shape[0] - self.minibatch_size + 1, self.minibatch_size): batch_idx = indices[start_idx:start_idx + self.minibatch_size] # forward propagation z_h, a_h, z_out, a_out = self._forward(X_train[batch_idx]) ################## # Backpropagation ################## # [n_samples, n_classlabels] sigma_out = a_out - y_train_enc[batch_idx] # [n_samples, n_hidden] sigmoid_derivative_h = a_h * (1. - a_h) # [n_samples, n_classlabels] dot [n_classlabels, n_hidden] # -> [n_samples, n_hidden] sigma_h = (np.dot(sigma_out, self.w_out.T) * sigmoid_derivative_h) # [n_features, n_samples] dot [n_samples, n_hidden] # -> [n_features, n_hidden] grad_w_h = np.dot(X_train[batch_idx].T, sigma_h) grad_b_h = np.sum(sigma_h, axis=0) # [n_hidden, n_samples] dot [n_samples, n_classlabels] # -> [n_hidden, n_classlabels] grad_w_out = np.dot(a_h.T, sigma_out) grad_b_out = np.sum(sigma_out, axis=0) # Regularization and weight updates delta_w_h = (grad_w_h + self.l2*self.w_h) delta_b_h = grad_b_h # bias is not regularized self.w_h -= self.eta * delta_w_h self.b_h -= self.eta * delta_b_h delta_w_out = (grad_w_out + self.l2*self.w_out) delta_b_out = grad_b_out # bias is not regularized self.w_out -= self.eta * delta_w_out self.b_out -= self.eta * delta_b_out ############# # Evaluation ############# # Evaluation after each epoch during training z_h, a_h, z_out, a_out = self._forward(X_train) cost = self._compute_cost(y_enc=y_train_enc, output=a_out) y_train_pred = self.predict(X_train) y_valid_pred = self.predict(X_valid) train_acc = ((np.sum(y_train == y_train_pred)).astype(np.float) / X_train.shape[0]) valid_acc = ((np.sum(y_valid == y_valid_pred)).astype(np.float) / X_valid.shape[0]) sys.stderr.write('\r%0*d/%d | Cost: %.2f ' '| Train/Valid Acc.: %.2f%%/%.2f%% ' % (epoch_strlen, i+1, self.epochs, cost, train_acc*100, valid_acc*100)) sys.stderr.flush() self.eval_['cost'].append(cost) self.eval_['train_acc'].append(train_acc) self.eval_['valid_acc'].append(valid_acc) return self ``` ## Obtaining the MNIST dataset The MNIST dataset is publicly available at http://yann.lecun.com/exdb/mnist/ and consists of the following four parts: - Training set images: train-images-idx3-ubyte.gz (9.9 MB, 47 MB unzipped, 60,000 samples) - Training set labels: train-labels-idx1-ubyte.gz (29 KB, 60 KB unzipped, 60,000 labels) - Test set images: t10k-images-idx3-ubyte.gz (1.6 MB, 7.8 MB, 10,000 samples) - Test set labels: t10k-labels-idx1-ubyte.gz (5 KB, 10 KB unzipped, 10,000 labels) After downloading the files, simply run the next code cell to unzip the files. ``` # this code cell unzips mnist import sys import gzip import shutil import os if (sys.version_info > (3, 0)): writemode = 'wb' else: writemode = 'w' zipped_mnist = [f for f in os.listdir('./') if f.endswith('ubyte.gz')] for z in zipped_mnist: with gzip.GzipFile(z, mode='rb') as decompressed, open(z[:-3], writemode) as outfile: outfile.write(decompressed.read()) import os import struct import numpy as np def load_mnist(path, kind='train'): os.chdir('/content/drive/My Drive/deeplearning_cursoCienciaDados_Insight/notebooks/data') """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte' % kind) with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>II', lbpath.read(8)) labels = np.fromfile(lbpath, dtype=np.uint8) with open(images_path, 'rb') as imgpath: magic, num, rows, cols = struct.unpack(">IIII", imgpath.read(16)) images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784) images = ((images / 255.) - .5) * 2 return images, labels !ls path = '' X_train, y_train = load_mnist(path, kind='train') print('Rows: %d, columns: %d' % (X_train.shape[0], X_train.shape[1])) X_test, y_test = load_mnist(path, kind='t10k') print('Rows: %d, columns: %d' % (X_test.shape[0], X_test.shape[1])) ``` ## Visualize the first digit of each class: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True,) ax = ax.flatten() for i in range(10): img = X_train[y_train == i][0].reshape(28, 28) ax[i].imshow(img, cmap='Greys') ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() # plt.savefig('images/12_5.png', dpi=300) plt.show() ``` ## Visualize 25 different versions of "7": ``` fig, ax = plt.subplots(nrows=5, ncols=5, sharex=True, sharey=True,) ax = ax.flatten() for i in range(25): img = X_train[y_train == 7][i].reshape(28, 28) ax[i].imshow(img, cmap='Greys') ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() # plt.savefig('images/12_6.png', dpi=300) plt.show() X_train.shape, X_test.shape, y_train.shape, y_test.shape n_epochs = 200 nn = NeuralNetMLP(n_hidden=100, l2=0.01, epochs=n_epochs, eta=0.0005, minibatch_size=100, shuffle=True, seed=1) nn.fit(X_train=X_train[:55000], y_train=y_train[:55000], X_valid=X_train[55000:], y_valid=y_train[55000:]) import matplotlib.pyplot as plt plt.plot(range(nn.epochs), nn.eval_['cost']) plt.ylabel('Cost') plt.xlabel('Epochs') #plt.savefig('images/12_07.png', dpi=300) plt.show() plt.plot(range(nn.epochs), nn.eval_['train_acc'], label='training') plt.plot(range(nn.epochs), nn.eval_['valid_acc'], label='validation', linestyle='--') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.legend() #plt.savefig('images/12_08.png', dpi=300) plt.show() y_test_pred = nn.predict(X_test) acc = (np.sum(y_test == y_test_pred) .astype(np.float) / X_test.shape[0]) print('Test accuracy: %.2f%%' % (acc * 100)) miscl_img = X_test[y_test != y_test_pred][:25] correct_lab = y_test[y_test != y_test_pred][:25] miscl_lab = y_test_pred[y_test != y_test_pred][:25] fig, ax = plt.subplots(nrows=5, ncols=5, sharex=True, sharey=True,) ax = ax.flatten() for i in range(25): img = miscl_img[i].reshape(28, 28) ax[i].imshow(img, cmap='Greys', interpolation='nearest') ax[i].set_title('%d) t: %d p: %d' % (i+1, correct_lab[i], miscl_lab[i])) ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() #plt.savefig('images/12_09.png', dpi=300) plt.show() ```
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Ragged tensors <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/guide/ragged_tensor"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> ## Setup ``` !pip install -q tf_nightly import math import tensorflow as tf ``` ## Overview Your data comes in many shapes; your tensors should too. *Ragged tensors* are the TensorFlow equivalent of nested variable-length lists. They make it easy to store and process data with non-uniform shapes, including: * Variable-length features, such as the set of actors in a movie. * Batches of variable-length sequential inputs, such as sentences or video clips. * Hierarchical inputs, such as text documents that are subdivided into sections, paragraphs, sentences, and words. * Individual fields in structured inputs, such as protocol buffers. ### What you can do with a ragged tensor Ragged tensors are supported by more than a hundred TensorFlow operations, including math operations (such as `tf.add` and `tf.reduce_mean`), array operations (such as `tf.concat` and `tf.tile`), string manipulation ops (such as `tf.substr`), control flow operations (such as `tf.while_loop` and `tf.map_fn`), and many others: ``` digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) words = tf.ragged.constant([["So", "long"], ["thanks", "for", "all", "the", "fish"]]) print(tf.add(digits, 3)) print(tf.reduce_mean(digits, axis=1)) print(tf.concat([digits, [[5, 3]]], axis=0)) print(tf.tile(digits, [1, 2])) print(tf.strings.substr(words, 0, 2)) print(tf.map_fn(tf.math.square, digits)) ``` There are also a number of methods and operations that are specific to ragged tensors, including factory methods, conversion methods, and value-mapping operations. For a list of supported ops, see the **`tf.ragged` package documentation**. Ragged tensors are supported by many TensorFlow APIs, including [Keras](https://www.tensorflow.org/guide/keras), [Datasets](https://www.tensorflow.org/guide/data), [tf.function](https://www.tensorflow.org/guide/function), [SavedModels](https://www.tensorflow.org/guide/saved_model), and [tf.Example](https://www.tensorflow.org/tutorials/load_data/tfrecord). For more information, see the section on **TensorFlow APIs** below. As with normal tensors, you can use Python-style indexing to access specific slices of a ragged tensor. For more information, see the section on **Indexing** below. ``` print(digits[0]) # First row print(digits[:, :2]) # First two values in each row. print(digits[:, -2:]) # Last two values in each row. ``` And just like normal tensors, you can use Python arithmetic and comparison operators to perform elementwise operations. For more information, see the section on **Overloaded Operators** below. ``` print(digits + 3) print(digits + tf.ragged.constant([[1, 2, 3, 4], [], [5, 6, 7], [8], []])) ``` If you need to perform an elementwise transformation to the values of a `RaggedTensor`, you can use `tf.ragged.map_flat_values`, which takes a function plus one or more arguments, and applies the function to transform the `RaggedTensor`'s values. ``` times_two_plus_one = lambda x: x * 2 + 1 print(tf.ragged.map_flat_values(times_two_plus_one, digits)) ``` Ragged tensors can be converted to nested Python `list`s and numpy `array`s: ``` digits.to_list() digits.numpy() ``` ### Constructing a ragged tensor The simplest way to construct a ragged tensor is using `tf.ragged.constant`, which builds the `RaggedTensor` corresponding to a given nested Python `list` or numpy `array`: ``` sentences = tf.ragged.constant([ ["Let's", "build", "some", "ragged", "tensors", "!"], ["We", "can", "use", "tf.ragged.constant", "."]]) print(sentences) paragraphs = tf.ragged.constant([ [['I', 'have', 'a', 'cat'], ['His', 'name', 'is', 'Mat']], [['Do', 'you', 'want', 'to', 'come', 'visit'], ["I'm", 'free', 'tomorrow']], ]) print(paragraphs) ``` Ragged tensors can also be constructed by pairing flat *values* tensors with *row-partitioning* tensors indicating how those values should be divided into rows, using factory classmethods such as `tf.RaggedTensor.from_value_rowids`, `tf.RaggedTensor.from_row_lengths`, and `tf.RaggedTensor.from_row_splits`. #### `tf.RaggedTensor.from_value_rowids` If you know which row each value belongs in, then you can build a `RaggedTensor` using a `value_rowids` row-partitioning tensor: ![value_rowids](https://www.tensorflow.org/images/ragged_tensors/value_rowids.png) ``` print(tf.RaggedTensor.from_value_rowids( values=[3, 1, 4, 1, 5, 9, 2], value_rowids=[0, 0, 0, 0, 2, 2, 3])) ``` #### `tf.RaggedTensor.from_row_lengths` If you know how long each row is, then you can use a `row_lengths` row-partitioning tensor: ![row_lengths](https://www.tensorflow.org/images/ragged_tensors/row_lengths.png) ``` print(tf.RaggedTensor.from_row_lengths( values=[3, 1, 4, 1, 5, 9, 2], row_lengths=[4, 0, 2, 1])) ``` #### `tf.RaggedTensor.from_row_splits` If you know the index where each row starts and ends, then you can use a `row_splits` row-partitioning tensor: ![row_splits](https://www.tensorflow.org/images/ragged_tensors/row_splits.png) ``` print(tf.RaggedTensor.from_row_splits( values=[3, 1, 4, 1, 5, 9, 2], row_splits=[0, 4, 4, 6, 7])) ``` See the `tf.RaggedTensor` class documentation for a full list of factory methods. Note: By default, these factory methods add assertions that the row partition tensor is well-formed and consistent with the number of values. The `validate=False` parameter can be used to skip these checks if you can guarantee that the inputs are well-formed and consistent. ### What you can store in a ragged tensor As with normal `Tensor`s, the values in a `RaggedTensor` must all have the same type; and the values must all be at the same nesting depth (the *rank* of the tensor): ``` print(tf.ragged.constant([["Hi"], ["How", "are", "you"]])) # ok: type=string, rank=2 print(tf.ragged.constant([[[1, 2], [3]], [[4, 5]]])) # ok: type=int32, rank=3 try: tf.ragged.constant([["one", "two"], [3, 4]]) # bad: multiple types except ValueError as exception: print(exception) try: tf.ragged.constant(["A", ["B", "C"]]) # bad: multiple nesting depths except ValueError as exception: print(exception) ``` ## Example use case The following example demonstrates how `RaggedTensor`s can be used to construct and combine unigram and bigram embeddings for a batch of variable-length queries, using special markers for the beginning and end of each sentence. For more details on the ops used in this example, see the `tf.ragged` package documentation. ``` queries = tf.ragged.constant([['Who', 'is', 'Dan', 'Smith'], ['Pause'], ['Will', 'it', 'rain', 'later', 'today']]) # Create an embedding table. num_buckets = 1024 embedding_size = 4 embedding_table = tf.Variable( tf.random.truncated_normal([num_buckets, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) # Look up the embedding for each word. word_buckets = tf.strings.to_hash_bucket_fast(queries, num_buckets) word_embeddings = tf.nn.embedding_lookup(embedding_table, word_buckets) # ① # Add markers to the beginning and end of each sentence. marker = tf.fill([queries.nrows(), 1], '#') padded = tf.concat([marker, queries, marker], axis=1) # ② # Build word bigrams & look up embeddings. bigrams = tf.strings.join([padded[:, :-1], padded[:, 1:]], separator='+') # ③ bigram_buckets = tf.strings.to_hash_bucket_fast(bigrams, num_buckets) bigram_embeddings = tf.nn.embedding_lookup(embedding_table, bigram_buckets) # ④ # Find the average embedding for each sentence all_embeddings = tf.concat([word_embeddings, bigram_embeddings], axis=1) # ⑤ avg_embedding = tf.reduce_mean(all_embeddings, axis=1) # ⑥ print(avg_embedding) ``` ![ragged_example](https://www.tensorflow.org/images/ragged_tensors/ragged_example.png) ## Ragged and uniform dimensions A ***ragged dimension*** is a dimension whose slices may have different lengths. For example, the inner (column) dimension of `rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices (`rt[0, :]`, ..., `rt[4, :]`) have different lengths. Dimensions whose slices all have the same length are called *uniform dimensions*. The outermost dimension of a ragged tensor is always uniform, since it consists of a single slice (and so there is no possibility for differing slice lengths). The remaining dimensions may be either ragged or uniform. For example, we might store the word embeddings for each word in a batch of sentences using a ragged tensor with shape `[num_sentences, (num_words), embedding_size]`, where the parentheses around `(num_words)` indicate that the dimension is ragged. ![sent_word_embed](https://www.tensorflow.org/images/ragged_tensors/sent_word_embed.png) Ragged tensors may have multiple ragged dimensions. For example, we could store a batch of structured text documents using a tensor with shape `[num_documents, (num_paragraphs), (num_sentences), (num_words)]` (where again parentheses are used to indicate ragged dimensions). As with `tf.Tensor`, the ***rank*** of a ragged tensor is its total number of dimensions (including both ragged and uniform dimensions). A ***potentially ragged tensor*** is a value that might be either a `tf.Tensor` or a `tf.RaggedTensor`. When describing the shape of a RaggedTensor, ragged dimensions are conventionally indicated by enclosing them in parentheses. For example, as we saw above, the shape of a 3-D RaggedTensor that stores word embeddings for each word in a batch of sentences can be written as `[num_sentences, (num_words), embedding_size]`. The `RaggedTensor.shape` attribute returns a `tf.TensorShape` for a ragged tensor, where ragged dimensions have size `None`: ``` tf.ragged.constant([["Hi"], ["How", "are", "you"]]).shape ``` The method `tf.RaggedTensor.bounding_shape` can be used to find a tight bounding shape for a given `RaggedTensor`: ``` print(tf.ragged.constant([["Hi"], ["How", "are", "you"]]).bounding_shape()) ``` ## Ragged vs. sparse A ragged tensor should *not* be thought of as a type of sparse tensor. In particular, sparse tensors are *efficient encodings for tf.Tensor*, that model the same data in a compact format; but ragged tensor is an *extension to tf.Tensor*, that models an expanded class of data. This difference is crucial when defining operations: * Applying an op to a sparse or dense tensor should always give the same result. * Applying an op to a ragged or sparse tensor may give different results. As an illustrative example, consider how array operations such as `concat`, `stack`, and `tile` are defined for ragged vs. sparse tensors. Concatenating ragged tensors joins each row to form a single row with the combined length: ![ragged_concat](https://www.tensorflow.org/images/ragged_tensors/ragged_concat.png) ``` ragged_x = tf.ragged.constant([["John"], ["a", "big", "dog"], ["my", "cat"]]) ragged_y = tf.ragged.constant([["fell", "asleep"], ["barked"], ["is", "fuzzy"]]) print(tf.concat([ragged_x, ragged_y], axis=1)) ``` But concatenating sparse tensors is equivalent to concatenating the corresponding dense tensors, as illustrated by the following example (where Ø indicates missing values): ![sparse_concat](https://www.tensorflow.org/images/ragged_tensors/sparse_concat.png) ``` sparse_x = ragged_x.to_sparse() sparse_y = ragged_y.to_sparse() sparse_result = tf.sparse.concat(sp_inputs=[sparse_x, sparse_y], axis=1) print(tf.sparse.to_dense(sparse_result, '')) ``` For another example of why this distinction is important, consider the definition of “the mean value of each row” for an op such as `tf.reduce_mean`. For a ragged tensor, the mean value for a row is the sum of the row’s values divided by the row’s width. But for a sparse tensor, the mean value for a row is the sum of the row’s values divided by the sparse tensor’s overall width (which is greater than or equal to the width of the longest row). ## TensorFlow APIs ### Keras [tf.keras](https://www.tensorflow.org/guide/keras) is TensorFlow's high-level API for building and training deep learning models. Ragged tensors may be passed as inputs to a Keras model by setting `ragged=True` on `tf.keras.Input` or `tf.keras.layers.InputLayer`. Ragged tensors may also be passed between Keras layers, and returned by Keras models. The following example shows a toy LSTM model that is trained using ragged tensors. ``` # Task: predict whether each sentence is a question or not. sentences = tf.constant( ['What makes you think she is a witch?', 'She turned me into a newt.', 'A newt?', 'Well, I got better.']) is_question = tf.constant([True, False, True, False]) # Preprocess the input strings. hash_buckets = 1000 words = tf.strings.split(sentences, ' ') hashed_words = tf.strings.to_hash_bucket_fast(words, hash_buckets) # Build the Keras model. keras_model = tf.keras.Sequential([ tf.keras.layers.Input(shape=[None], dtype=tf.int64, ragged=True), tf.keras.layers.Embedding(hash_buckets, 16), tf.keras.layers.LSTM(32, use_bias=False), tf.keras.layers.Dense(32), tf.keras.layers.Activation(tf.nn.relu), tf.keras.layers.Dense(1) ]) keras_model.compile(loss='binary_crossentropy', optimizer='rmsprop') keras_model.fit(hashed_words, is_question, epochs=5) print(keras_model.predict(hashed_words)) ``` ### tf.Example [tf.Example](https://www.tensorflow.org/tutorials/load_data/tfrecord) is a standard [protobuf](https://developers.google.com/protocol-buffers/) encoding for TensorFlow data. Data encoded with `tf.Example`s often includes variable-length features. For example, the following code defines a batch of four `tf.Example` messages with different feature lengths: ``` import google.protobuf.text_format as pbtext def build_tf_example(s): return pbtext.Merge(s, tf.train.Example()).SerializeToString() example_batch = [ build_tf_example(r''' features { feature {key: "colors" value {bytes_list {value: ["red", "blue"]} } } feature {key: "lengths" value {int64_list {value: [7]} } } }'''), build_tf_example(r''' features { feature {key: "colors" value {bytes_list {value: ["orange"]} } } feature {key: "lengths" value {int64_list {value: []} } } }'''), build_tf_example(r''' features { feature {key: "colors" value {bytes_list {value: ["black", "yellow"]} } } feature {key: "lengths" value {int64_list {value: [1, 3]} } } }'''), build_tf_example(r''' features { feature {key: "colors" value {bytes_list {value: ["green"]} } } feature {key: "lengths" value {int64_list {value: [3, 5, 2]} } } }''')] ``` We can parse this encoded data using `tf.io.parse_example`, which takes a tensor of serialized strings and a feature specification dictionary, and returns a dictionary mapping feature names to tensors. To read the variable-length features into ragged tensors, we simply use `tf.io.RaggedFeature` in the feature specification dictionary: ``` feature_specification = { 'colors': tf.io.RaggedFeature(tf.string), 'lengths': tf.io.RaggedFeature(tf.int64), } feature_tensors = tf.io.parse_example(example_batch, feature_specification) for name, value in feature_tensors.items(): print("{}={}".format(name, value)) ``` `tf.io.RaggedFeature` can also be used to read features with multiple ragged dimensions. For details, see the [API documentation](https://www.tensorflow.org/api_docs/python/tf/io/RaggedFeature). ### Datasets [tf.data](https://www.tensorflow.org/guide/data) is an API that enables you to build complex input pipelines from simple, reusable pieces. Its core data structure is `tf.data.Dataset`, which represents a sequence of elements, in which each element consists of one or more components. ``` # Helper function used to print datasets in the examples below. def print_dictionary_dataset(dataset): for i, element in enumerate(dataset): print("Element {}:".format(i)) for (feature_name, feature_value) in element.items(): print('{:>14} = {}'.format(feature_name, feature_value)) ``` #### Building Datasets with ragged tensors Datasets can be built from ragged tensors using the same methods that are used to build them from `tf.Tensor`s or numpy `array`s, such as `Dataset.from_tensor_slices`: ``` dataset = tf.data.Dataset.from_tensor_slices(feature_tensors) print_dictionary_dataset(dataset) ``` Note: `Dataset.from_generator` does not support ragged tensors yet, but support will be added soon. #### Batching and unbatching Datasets with ragged tensors Datasets with ragged tensors can be batched (which combines *n* consecutive elements into a single elements) using the `Dataset.batch` method. ``` batched_dataset = dataset.batch(2) print_dictionary_dataset(batched_dataset) ``` Conversely, a batched dataset can be transformed into a flat dataset using `Dataset.unbatch`. ``` unbatched_dataset = batched_dataset.unbatch() print_dictionary_dataset(unbatched_dataset) ``` #### Batching Datasets with variable-length non-ragged tensors If you have a Dataset that contains non-ragged tensors, and tensor lengths vary across elements, then you can batch those non-ragged tensors into ragged tensors by applying the `dense_to_ragged_batch` transformation: ``` non_ragged_dataset = tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8]) non_ragged_dataset = non_ragged_dataset.map(tf.range) batched_non_ragged_dataset = non_ragged_dataset.apply( tf.data.experimental.dense_to_ragged_batch(2)) for element in batched_non_ragged_dataset: print(element) ``` #### Transforming Datasets with ragged tensors Ragged tensors in Datasets can also be created or transformed using `Dataset.map`. ``` def transform_lengths(features): return { 'mean_length': tf.math.reduce_mean(features['lengths']), 'length_ranges': tf.ragged.range(features['lengths'])} transformed_dataset = dataset.map(transform_lengths) print_dictionary_dataset(transformed_dataset) ``` ### tf.function [tf.function](https://www.tensorflow.org/guide/function) is a decorator that precomputes TensorFlow graphs for Python functions, which can substantially improve the performance of your TensorFlow code. Ragged tensors can be used transparently with `@tf.function`-decorated functions. For example, the following function works with both ragged and non-ragged tensors: ``` @tf.function def make_palindrome(x, axis): return tf.concat([x, tf.reverse(x, [axis])], axis) make_palindrome(tf.constant([[1, 2], [3, 4], [5, 6]]), axis=1) make_palindrome(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]), axis=1) ``` If you wish to explicitly specify the `input_signature` for the `tf.function`, then you can do so using `tf.RaggedTensorSpec`. ``` @tf.function( input_signature=[tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int32)]) def max_and_min(rt): return (tf.math.reduce_max(rt, axis=-1), tf.math.reduce_min(rt, axis=-1)) max_and_min(tf.ragged.constant([[1, 2], [3], [4, 5, 6]])) ``` #### Concrete functions [Concrete functions](https://www.tensorflow.org/guide/concrete_function) encapsulate individual traced graphs that are built by `tf.function`. Starting with TensorFlow 2.3 (and in `tf-nightly`), ragged tensors can be used transparently with concrete functions. ``` # Preferred way to use ragged tensors with concrete functions (TF 2.3+): try: @tf.function def increment(x): return x + 1 rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) cf = increment.get_concrete_function(rt) print(cf(rt)) except Exception as e: print(f"Not supported before TF 2.3: {type(e)}: {e}") ``` If you need to use ragged tensors with concrete functions prior to TensorFlow 2.3, then we recommend decomposing ragged tensors into their components (`values` and `row_splits`), and passing them in as separate arguments. ``` # Backwards-compatible way to use ragged tensors with concrete functions: @tf.function def decomposed_ragged_increment(x_values, x_splits): x = tf.RaggedTensor.from_row_splits(x_values, x_splits) return x + 1 rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) cf = decomposed_ragged_increment.get_concrete_function(rt.values, rt.row_splits) print(cf(rt.values, rt.row_splits)) ``` ### SavedModels A [SavedModel](https://www.tensorflow.org/guide/saved_model) is a serialized TensorFlow program, including both weights and computation. It can be built from a Keras model or from a custom model. In either case, ragged tensors can be used transparently with the functions and methods defined by a SavedModel. #### Example: saving a Keras model ``` import tempfile keras_module_path = tempfile.mkdtemp() tf.saved_model.save(keras_model, keras_module_path) imported_model = tf.saved_model.load(keras_module_path) imported_model(hashed_words) ``` #### Example: saving a custom model ``` class CustomModule(tf.Module): def __init__(self, variable_value): super(CustomModule, self).__init__() self.v = tf.Variable(variable_value) @tf.function def grow(self, x): return x * self.v module = CustomModule(100.0) # Before saving a custom model, we must ensure that concrete functions are # built for each input signature that we will need. module.grow.get_concrete_function(tf.RaggedTensorSpec(shape=[None, None], dtype=tf.float32)) custom_module_path = tempfile.mkdtemp() tf.saved_model.save(module, custom_module_path) imported_model = tf.saved_model.load(custom_module_path) imported_model.grow(tf.ragged.constant([[1.0, 4.0, 3.0], [2.0]])) ``` Note: SavedModel [signatures](https://www.tensorflow.org/guide/saved_model#specifying_signatures_during_export) are concrete functions. As discussed in the section on Concrete Functions above, ragged tensors are only handled correctly by concrete functions starting with TensorFlow 2.3 (and in `tf_nightly`). If you need to use SavedModel signatures in a previous version of TensorFlow, then we recommend decomposing the ragged tensor into its component tensors. ## Overloaded operators The `RaggedTensor` class overloads the standard Python arithmetic and comparison operators, making it easy to perform basic elementwise math: ``` x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) y = tf.ragged.constant([[1, 1], [2], [3, 3, 3]]) print(x + y) ``` Since the overloaded operators perform elementwise computations, the inputs to all binary operations must have the same shape, or be broadcastable to the same shape. In the simplest broadcasting case, a single scalar is combined elementwise with each value in a ragged tensor: ``` x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) print(x + 3) ``` For a discussion of more advanced cases, see the section on **Broadcasting**. Ragged tensors overload the same set of operators as normal `Tensor`s: the unary operators `-`, `~`, and `abs()`; and the binary operators `+`, `-`, `*`, `/`, `//`, `%`, `**`, `&`, `|`, `^`, `==`, `<`, `<=`, `>`, and `>=`. ## Indexing Ragged tensors support Python-style indexing, including multidimensional indexing and slicing. The following examples demonstrate ragged tensor indexing with a 2-D and a 3-D ragged tensor. ### Indexing examples: 2D ragged tensor ``` queries = tf.ragged.constant( [['Who', 'is', 'George', 'Washington'], ['What', 'is', 'the', 'weather', 'tomorrow'], ['Goodnight']]) print(queries[1]) # A single query print(queries[1, 2]) # A single word print(queries[1:]) # Everything but the first row print(queries[:, :3]) # The first 3 words of each query print(queries[:, -2:]) # The last 2 words of each query ``` ### Indexing examples 3D ragged tensor ``` rt = tf.ragged.constant([[[1, 2, 3], [4]], [[5], [], [6]], [[7]], [[8, 9], [10]]]) print(rt[1]) # Second row (2-D RaggedTensor) print(rt[3, 0]) # First element of fourth row (1-D Tensor) print(rt[:, 1:3]) # Items 1-3 of each row (3-D RaggedTensor) print(rt[:, -1:]) # Last item of each row (3-D RaggedTensor) ``` `RaggedTensor`s supports multidimensional indexing and slicing, with one restriction: indexing into a ragged dimension is not allowed. This case is problematic because the indicated value may exist in some rows but not others. In such cases, it's not obvious whether we should (1) raise an `IndexError`; (2) use a default value; or (3) skip that value and return a tensor with fewer rows than we started with. Following the [guiding principles of Python](https://www.python.org/dev/peps/pep-0020/) ("In the face of ambiguity, refuse the temptation to guess" ), we currently disallow this operation. ## Tensor type conversion The `RaggedTensor` class defines methods that can be used to convert between `RaggedTensor`s and `tf.Tensor`s or `tf.SparseTensors`: ``` ragged_sentences = tf.ragged.constant([ ['Hi'], ['Welcome', 'to', 'the', 'fair'], ['Have', 'fun']]) # RaggedTensor -> Tensor print(ragged_sentences.to_tensor(default_value='', shape=[None, 10])) # Tensor -> RaggedTensor x = [[1, 3, -1, -1], [2, -1, -1, -1], [4, 5, 8, 9]] print(tf.RaggedTensor.from_tensor(x, padding=-1)) #RaggedTensor -> SparseTensor print(ragged_sentences.to_sparse()) # SparseTensor -> RaggedTensor st = tf.SparseTensor(indices=[[0, 0], [2, 0], [2, 1]], values=['a', 'b', 'c'], dense_shape=[3, 3]) print(tf.RaggedTensor.from_sparse(st)) ``` ## Evaluating ragged tensors To access the values in a ragged tensor, you can: 1. Use `tf.RaggedTensor.to_list()` to convert the ragged tensor to a nested python list. 1. Use `tf.RaggedTensor.numpy()` to convert the ragged tensor to a numpy array whose values are nested numpy arrays. 1. Decompose the ragged tensor into its components, using the `tf.RaggedTensor.values` and `tf.RaggedTensor.row_splits` properties, or row-paritioning methods such as `tf.RaggedTensor.row_lengths()` and `tf.RaggedTensor.value_rowids()`. 1. Use Python indexing to select values from the ragged tensor. ``` rt = tf.ragged.constant([[1, 2], [3, 4, 5], [6], [], [7]]) print("python list:", rt.to_list()) print("numpy array:", rt.numpy()) print("values:", rt.values.numpy()) print("splits:", rt.row_splits.numpy()) print("indexed value:", rt[1].numpy()) ``` ## Broadcasting Broadcasting is the process of making tensors with different shapes have compatible shapes for elementwise operations. For more background on broadcasting, see: * [Numpy: Broadcasting](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) * `tf.broadcast_dynamic_shape` * `tf.broadcast_to` The basic steps for broadcasting two inputs `x` and `y` to have compatible shapes are: 1. If `x` and `y` do not have the same number of dimensions, then add outer dimensions (with size 1) until they do. 2. For each dimension where `x` and `y` have different sizes: * If `x` or `y` have size `1` in dimension `d`, then repeat its values across dimension `d` to match the other input's size. * Otherwise, raise an exception (`x` and `y` are not broadcast compatible). Where the size of a tensor in a uniform dimension is a single number (the size of slices across that dimension); and the size of a tensor in a ragged dimension is a list of slice lengths (for all slices across that dimension). ### Broadcasting examples ``` # x (2D ragged): 2 x (num_rows) # y (scalar) # result (2D ragged): 2 x (num_rows) x = tf.ragged.constant([[1, 2], [3]]) y = 3 print(x + y) # x (2d ragged): 3 x (num_rows) # y (2d tensor): 3 x 1 # Result (2d ragged): 3 x (num_rows) x = tf.ragged.constant( [[10, 87, 12], [19, 53], [12, 32]]) y = [[1000], [2000], [3000]] print(x + y) # x (3d ragged): 2 x (r1) x 2 # y (2d ragged): 1 x 1 # Result (3d ragged): 2 x (r1) x 2 x = tf.ragged.constant( [[[1, 2], [3, 4], [5, 6]], [[7, 8]]], ragged_rank=1) y = tf.constant([[10]]) print(x + y) # x (3d ragged): 2 x (r1) x (r2) x 1 # y (1d tensor): 3 # Result (3d ragged): 2 x (r1) x (r2) x 3 x = tf.ragged.constant( [ [ [[1], [2]], [], [[3]], [[4]], ], [ [[5], [6]], [[7]] ] ], ragged_rank=2) y = tf.constant([10, 20, 30]) print(x + y) ``` Here are some examples of shapes that do not broadcast: ``` # x (2d ragged): 3 x (r1) # y (2d tensor): 3 x 4 # trailing dimensions do not match x = tf.ragged.constant([[1, 2], [3, 4, 5, 6], [7]]) y = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) try: x + y except tf.errors.InvalidArgumentError as exception: print(exception) # x (2d ragged): 3 x (r1) # y (2d ragged): 3 x (r2) # ragged dimensions do not match. x = tf.ragged.constant([[1, 2, 3], [4], [5, 6]]) y = tf.ragged.constant([[10, 20], [30, 40], [50]]) try: x + y except tf.errors.InvalidArgumentError as exception: print(exception) # x (3d ragged): 3 x (r1) x 2 # y (3d ragged): 3 x (r1) x 3 # trailing dimensions do not match x = tf.ragged.constant([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]) y = tf.ragged.constant([[[1, 2, 0], [3, 4, 0], [5, 6, 0]], [[7, 8, 0], [9, 10, 0]]]) try: x + y except tf.errors.InvalidArgumentError as exception: print(exception) ``` ## RaggedTensor encoding Ragged tensors are encoded using the `RaggedTensor` class. Internally, each `RaggedTensor` consists of: * A `values` tensor, which concatenates the variable-length rows into a flattened list. * A `row_partition`, which indicates how those flattened values are divided into rows. ![ragged_encoding_2](https://www.tensorflow.org/images/ragged_tensors/ragged_encoding_2.png) The `row_partition` can be stored using four different encodings: * `row_splits` is an integer vector specifying the split points between rows. * `value_rowids` is an integer vector specifying the row index for each value. * `row_lengths` is an integer vector specifying the length of each row. * `uniform_row_length` is an integer scalar specifying a single length for all rows. ![partition_encodings](https://www.tensorflow.org/images/ragged_tensors/partition_encodings.png) An integer scalar `nrows` can also be included in the `row_partition` encoding, to account for empty trailing rows with `value_rowids`, or empty rows with `uniform_row_length`. ``` rt = tf.RaggedTensor.from_row_splits( values=[3, 1, 4, 1, 5, 9, 2], row_splits=[0, 4, 4, 6, 7]) print(rt) ``` The choice of which encoding to use for row partitions is managed internally by ragged tensors, to improve efficiency in some contexts. In particular, some of the advantages and disadvantages of the different row-partitioning schemes are: + **Efficient indexing**: The `row_splits` encoding enables constant-time indexing and slicing into ragged tensors. + **Efficient concatenation**: The `row_lengths` encoding is more efficient when concatenating ragged tensors, since row lengths do not change when two tensors are concatenated together. + **Small encoding size**: The `value_rowids` encoding is more efficient when storing ragged tensors that have a large number of empty rows, since the size of the tensor depends only on the total number of values. On the other hand, the `row_splits` and `row_lengths` encodings are more efficient when storing ragged tensors with longer rows, since they require only one scalar value for each row. + **Compatibility**: The `value_rowids` scheme matches the [segmentation](https://www.tensorflow.org/api_docs/python/tf/math#about_segmentation) format used by operations such as `tf.segment_sum`. The `row_limits` scheme matches the format used by ops such as `tf.sequence_mask`. + **Uniform dimensions**: As discussed below, the `uniform_row_length` encoding is used to encode ragged tensors with uniform dimensions. ### Multiple ragged dimensions A ragged tensor with multiple ragged dimensions is encoded by using a nested `RaggedTensor` for the `values` tensor. Each nested `RaggedTensor` adds a single ragged dimension. ![ragged_rank_2](https://www.tensorflow.org/images/ragged_tensors/ragged_rank_2.png) ``` rt = tf.RaggedTensor.from_row_splits( values=tf.RaggedTensor.from_row_splits( values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], row_splits=[0, 3, 3, 5, 9, 10]), row_splits=[0, 1, 1, 5]) print(rt) print("Shape: {}".format(rt.shape)) print("Number of partitioned dimensions: {}".format(rt.ragged_rank)) ``` The factory function `tf.RaggedTensor.from_nested_row_splits` may be used to construct a RaggedTensor with multiple ragged dimensions directly, by providing a list of `row_splits` tensors: ``` rt = tf.RaggedTensor.from_nested_row_splits( flat_values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], nested_row_splits=([0, 1, 1, 5], [0, 3, 3, 5, 9, 10])) print(rt) ``` ### Ragged rank and flat values A ragged tensor's ***ragged rank*** is the number of times that the underlying `values` Tensor has been partitioned (i.e., the nesting depth of `RaggedTensor` objects). The innermost `values` tensor is known as its ***flat_values***. In the following example, `conversations` has ragged_rank=3, and its `flat_values` is a 1D `Tensor` with 24 strings: ``` # shape = [batch, (paragraph), (sentence), (word)] conversations = tf.ragged.constant( [[[["I", "like", "ragged", "tensors."]], [["Oh", "yeah?"], ["What", "can", "you", "use", "them", "for?"]], [["Processing", "variable", "length", "data!"]]], [[["I", "like", "cheese."], ["Do", "you?"]], [["Yes."], ["I", "do."]]]]) conversations.shape assert conversations.ragged_rank == len(conversations.nested_row_splits) conversations.ragged_rank # Number of partitioned dimensions. conversations.flat_values.numpy() ``` ### Uniform inner dimensions Ragged tensors with uniform inner dimensions are encoded by using a multidimensional `tf.Tensor` for the flat_values (i.e., the innermost `values`). ![uniform_inner](https://www.tensorflow.org/images/ragged_tensors/uniform_inner.png) ``` rt = tf.RaggedTensor.from_row_splits( values=[[1, 3], [0, 0], [1, 3], [5, 3], [3, 3], [1, 2]], row_splits=[0, 3, 4, 6]) print(rt) print("Shape: {}".format(rt.shape)) print("Number of partitioned dimensions: {}".format(rt.ragged_rank)) print("Flat values shape: {}".format(rt.flat_values.shape)) print("Flat values:\n{}".format(rt.flat_values)) ``` ### Uniform non-inner dimensions Ragged tensors with uniform non-inner dimensions are encoded by partitioning rows with `uniform_row_length`. ![uniform_outer](https://www.tensorflow.org/images/ragged_tensors/uniform_outer.png) ``` rt = tf.RaggedTensor.from_uniform_row_length( values=tf.RaggedTensor.from_row_splits( values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], row_splits=[0, 3, 5, 9, 10]), uniform_row_length=2) print(rt) print("Shape: {}".format(rt.shape)) print("Number of partitioned dimensions: {}".format(rt.ragged_rank)) ```
github_jupyter
``` #Imported relevant and necessary libraries and data cleaning tools import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import hypertools as hyp from glob import glob as lsdir import os import re import datetime as dt from sklearn import linear_model from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split %matplotlib inline #Code from Professor Manning to set up and read in the relevant UVLT data data_readers = {'xlsx': pd.read_excel, 'xls': pd.read_excel, 'dta': pd.read_stata} get_extension = lambda x: x.split('.')[-1] def read_data(datadir, readers): files = lsdir(os.path.join(datadir, '*')) readable_files = [] data = [] for f in files: ext = get_extension(f) if ext in readers.keys(): readable_files.append(f) data.append(data_readers[ext](f)) return readable_files, data fnames, data = read_data('data', data_readers) #A summary of the data files that are now read into the notebook fnames #This is the individual data #Most of the initial cleaning that I have done has been on this data set, though obviously it can be applied if necessary to any of the data sets data[0].head() #Renaming relevant columns in UVLT individual data to be more easily readable names={'DeceasedDateYN' : 'Is the donor Deceased?', 'U_Tot_Amt': 'Total Unrestricted Donations', 'U_Tot_Cnt': 'Total Number of Unrestricted Donations Given', 'ConservedOwner' : 'Owns Conserved Land?', 'RTotAmt' : 'Total Restricted Donations', 'RTotCnt': 'Total Number of Restricted Donations Given', 'VTotCnt' : 'Total Volunteer Occurances', 'ETotCnt' : 'Total Event Attendances'} data[0].rename(names, inplace=True, axis=1) #Summary of the column values in data set 1 data[0].columns.values #copying each set of data into more memorably named versions #I figured different analyses require different aspects of each dataframe, so starting here and using copies of the data for different analyses may be helpful for organizationa and fidelity Individual_data=data[0].copy() Final_data=data[1].copy() Mailing_data=data[2].copy() Town_Data=data[5].copy() #Similarly to the individual data, the final data could benefit from some cleaner column names Final_data.rename(names, inplace=True, axis=1) to_drop={'U200001', 'U200102', 'U200203', 'U200304', 'U200405', 'U200506', 'U200607', 'U200708', 'U200809', 'U200910', 'U201011', 'U201112', 'U201213', 'U201314', 'U201415', 'U201516', 'U201617', 'U201718', 'U201819', 'R200001', 'R200102', 'R200203', 'R200304', 'R200405', 'R200506', 'R200607', 'R200708', 'R200809', 'R200910', 'R201011', 'R201112', 'R201213', 'R201314', 'R201415', 'R201516', 'R201617', 'R201718', 'R201819', 'V200001', 'V200102', 'V200203', 'V200304', 'V200405', 'V200506', 'V200607', 'V200708', 'V200809', 'V200910', 'V201011', 'V201112', 'V201213', 'V201314', 'V201415', 'V201516', 'V201617', 'V201718', 'V201819', 'E200001', 'E200102', 'E200203', 'E200304', 'E200405', 'E200506', 'E200607', 'E200708', 'E200809', 'E200910', 'E201011', 'E201112', 'E201213', 'E201314', 'E201415', 'E201516', 'E201617', 'E201718', 'E201819'} Individual_data_SUMMARY=data[0].copy() Individual_data_SUMMARY.drop(to_drop, inplace=True, axis=1) #The summary cleaning gets rid of the year-by-year data and leaves only the summary of the donations for analyses #obviously there are pros and cons to this, but I figured it was a tedious process to undertake so now it's a simple dictionary that can be used on the various data sets Individual_data_SUMMARY.head(15) Final_data_SUMMARY=Final_data.copy() Final_data_SUMMARY.drop(to_drop, inplace=True, axis=1) Final_data_SUMMARY.head(15) ```
github_jupyter
# Ex 12 ``` import tensorflow as tf from tensorflow import keras import os import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.datasets import mnist from tensorflow.keras import models from tensorflow.keras import layers from tensorflow.keras.utils import to_categorical from matplotlib.pyplot import figure from time import time seed=0 np.random.seed(seed) # fix random seed start_time = time() OTTIMIZZATORE = 'rmsprop' LOSS = 'categorical_crossentropy' BATCH = 120 EPOCHS = 10 BATCH_CONV = 120 EPOCHS_CONV = 10 ``` ### Exercise 12.1 By keeping fixed all the other parameters, try to use at least two other optimizers, different from SGD. <span style="color:red">Watch to accuracy and loss for training and validation data and comment on the performances</span>. ``` (train_images, train_labels), (test_images, test_labels) = mnist.load_data() pixel_rows = train_images.shape[1] pixel_col = train_images.shape[2] def prepare_data(array): array = array.reshape(array.shape[0], array.shape[1]*array.shape[2]) return array.astype('float32')/255. x_train = prepare_data(train_images) x_test = prepare_data(test_images) y_train = to_categorical(train_labels) y_test = to_categorical(test_labels) def dense_model(): model = models.Sequential() model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) model.add(layers.Dropout(0.5)) model.add(layers.Dense(10, activation='softmax')) return model network = dense_model() network.compile(optimizer=OTTIMIZZATORE, loss=LOSS, metrics=['accuracy']) history = network.fit(x_train, y_train, batch_size = BATCH, epochs = EPOCHS, validation_split = 0.1, verbose=True, shuffle=True) figure(figsize=((10,5)), dpi=200) plt.subplot(1,2,1) plt.plot(history.history['loss'], label='Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title("Model Loss") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend(loc='best') plt.subplot(1,2,2) plt.plot(history.history['accuracy'], label='Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title("Model Accuracy") plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend(loc='best') plt.show() network.evaluate(x_test, y_test) ``` ### Exercise 12.2 Change the architecture of your DNN using convolutional layers. Use `Conv2D`, `MaxPooling2D`, `Dropout`, but also do not forget `Flatten`, a standard `Dense` layer and `soft-max` in the end. I have merged step 2 and 3 in the following definition of `create_CNN()` that **<span style="color:red">you should complete</span>**: ``` def prepare_data_conv(array): if keras.backend.image_data_format() == 'channels_first': array = array.reshape(array.shape[0], 1, array.shape[1], array.shape[2]) shape = (1, array.shape[1], array.shape[2]) else: array = array.reshape(array.shape[0], array.shape[1], array.shape[2], 1) shape = (array.shape[1], array.shape[2], 1) return array.astype('float32')/255., shape x_train, INPUT_SHAPE = prepare_data_conv(train_images) x_test, test_shape = prepare_data_conv(test_images) def conv_model(): model = models.Sequential() model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=INPUT_SHAPE)) model.add(layers.MaxPooling2D((2,2))) model.add(layers.Conv2D(64, (3,3), activation='relu',)) model.add(layers.MaxPooling2D((2,2))) model.add(layers.Conv2D(64, (3,3), activation='relu',)) model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10, activation='softmax')) return model network_conv = conv_model() network_conv.compile(optimizer=OTTIMIZZATORE, loss=LOSS, metrics=['accuracy']) history = network_conv.fit(x_train, y_train, validation_split=0.1, verbose=True, batch_size=BATCH, epochs=5, shuffle=True) figure(figsize=((10,5)), dpi=200) plt.subplot(1,2,1) plt.plot(history.history['loss'], label='Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title("Model Loss") plt.xlabel('Epochs') plt.ylabel('Loss') plt.grid(True) plt.legend(loc='best') plt.subplot(1,2,2) plt.plot(history.history['accuracy'], label='Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title("Model Accuracy") plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend(loc='best') plt.grid(True) plt.show() network_conv.evaluate(x_test, y_test) ``` ### Exercise 12.3 Use the `gimp` application to create 10 pictures of your "handwritten" digits, import them in your jupyter-notebook and try to see if your CNN is able to recognize your handwritten digits. For example, you can use the following code to import a picture of an handwritten digit: ``` from PIL import Image import os plt.figure(figsize=(20,40), dpi=50) full_data = np.zeros((10,28,28)) for k in range(0,10): digit_filename = str(k)+".png" digit_in = Image.open(digit_filename).convert('L') pix=digit_in.load(); data = np.zeros((28, 28)) for j in range(28): for i in range(28): data[i,j]=pix[j,i] plt.subplot(1,10,k+1) plt.imshow(data, cmap='gray') full_data[k,:,:] = data[:,:] #data /= 255 plt.show() print(data.shape) ``` Test di accuratezza con i numeri scritti a mano da me. ``` plt.figure(figsize=(20,40), dpi=50) for k in range(0,10): data = full_data[k,:,:] data_conv = np.zeros((1,data.shape[0], data.shape[1])) data_conv[0,:,:] = data[:,:] data_conv, aa = prepare_data_conv(data_conv) data = data.reshape(1, 28*28) pred_0 = network.predict(data) pred_1 = network_conv.predict(data_conv) data = data.reshape(28,28) plt.subplot(1,10,k+1) plt.imshow(data, cmap='gray') plt.title("Dense {}".format(np.argmax(pred_0))+"\n \nConv {}".format(np.argmax(pred_1))) plt.axis('off') plt.show() ``` Test di accuratezza con alcune cifre sempre dal ```MNIST```. ``` #X_test = X_test.reshape(X_test.shape[0], img_rows*img_cols) predictions = network_conv.predict(x_test) x_test = x_test.reshape(x_test.shape[0], 28, 28,1) plt.figure(figsize=(15, 15)) for i in range(10): ax = plt.subplot(2, 10, i + 1) plt.imshow(x_test[i, :, :, 0], cmap='gray') plt.title("Digit: {}\nPredicted: {}".format(np.argmax(y_test[i]), np.argmax(predictions[i]))) plt.axis('off') plt.show() end_time = time() minutes = int((end_time - start_time)/60.) seconds = int((end_time - start_time) - minutes*60) print("Computation time: ", minutes, "min ", seconds, "sec.") ```
github_jupyter
# Prophecy of ATM Withdrawals Agus Gunawan, Holy Lovenia ## Importing dataset ``` from datetime import datetime from pandas import read_csv import pandas as pd from os import listdir, mkdir from os.path import exists, isfile, join ``` ### Read train data #### Functions ``` def get_files_from_dir_path(dir_path): files = [] for file in listdir(dir_path): if file.endswith('.csv'): files.append(file) return files def import_all_datasets(base_src_dir_path): src_files = get_files_from_dir_path(base_src_dir_path) date_parser = lambda dates: datetime.strptime(dates, '%Y-%m-%d') datasets = {} for i in range(0, len(src_files)): current_src_file = src_files[i] current_id = current_src_file.split('.')[0] current_id = current_id.split('_')[0] datasets[int(current_id)] = read_csv(base_src_dir_path + current_src_file, parse_dates=['date'], date_parser=date_parser) datasets[int(current_id)] = datasets[int(current_id)].rename(columns={'date': 'ds', 'Withdrawals': 'y'}) return datasets ``` ### Import all split training datasets Due to different natures and patterns generated by each ATM machine, the training dataset was split based on the ATM machines, e.g. K1, K2, ... ATM machine has its own dataset respectively. ``` train_datasets = import_all_datasets('dataset/train/') ``` ## Prophet model building ``` from fbprophet import Prophet from fbprophet.diagnostics import cross_validation, performance_metrics from fbprophet.plot import plot_cross_validation_metric, plot_yearly, plot_weekly import calendar ``` ### Define Payday (holiday seasonality) During the end of the month, usually the `Withdrawals` value gets higher ``` gajian = pd.DataFrame({ 'holiday' : 'gajian', 'ds' : pd.to_datetime(['2018-03-30', '2018-02-28', '2018-01-31']), 'lower_window' : -2, 'upper_window' : 2} ) holidays = gajian ``` ### Define weekly seasonality for Sunday On Sundays, `Withdrawals` is almost half of the other days ``` def take_money(ds): date = pd.to_datetime(ds) switcher = { 6: 0.5 } return switcher.get(date.weekday(), 1) ``` ### Adding regressor column for Sunday's `take_money` in dataset ``` for i in range(1, len(train_datasets) + 1): train_datasets[i]['take_money'] = train_datasets[i]['ds'].apply(take_money) ``` ### Training Prophet models for each dataset In this step, each model is trained using its own dataset. An additional regressor for Sunday's `take_money` (weekly seasonality) is added for every model. ``` prophets = {} for i in range(1, len(train_datasets) + 1): prophet = Prophet(yearly_seasonality=False, weekly_seasonality=False, daily_seasonality=False, holidays=holidays) prophet.add_regressor(name='take_money', mode='multiplicative') prophet.fit(train_datasets[i]) prophets[i] = prophet ``` ### Forecasting `Withdrawals` For the sake of demonstration, let's just predict the next seven days using the first 10 ATM machines. ``` forecast_data = {} for i in range(1, 10 + 1): if i % 10 == 0: print(str(i) + ' from ' + str(len(prophets))) future_data = prophets[i].make_future_dataframe(periods=7, freq='d') future_data['take_money'] = future_data['ds'].apply(take_money) forecast_data[i] = prophets[i].predict(future_data) ``` ## Performance measure The performance measure for 10 first ATM machines is computed using cross-validation. ### Get performance metrics with cross-validation ``` pm = {} for i in range(1, 10 + 1): cv = cross_validation(prophets[i], horizon='7 days') pm[i] = performance_metrics(cv) ``` ### Show averaged MSE and MAPE from each data point ``` for i in range(1, len(pm) + 1): print(i, pm[i][['mse']].mean(), pm[i][['mape']].mean()) ``` ## Result ### Preparing the answers ``` temp_forecast_data = forecast_data.copy() for i in range(1, len(temp_forecast_data) + 1): temp_forecast_data[i]['no. ATM'] = "K" + str(i) for i in range(1, len(temp_forecast_data) + 1): temp_forecast_data[i] = temp_forecast_data[i].rename(columns={'ds': 'date'}) answer = {} for i in range(1, len(temp_forecast_data) + 1): answer[i] = temp_forecast_data[i].loc[temp_forecast_data[i]['date'] > '2018-03-24'] answer[i] = answer[i][['no. ATM', 'date', 'yhat']] answer[i] = answer[i].rename(columns={'yhat': 'prediction'}) if i % 10 == 0: print(str(i) + ' from ' + str(len(temp_forecast_data))) ``` ### Concat all of the answers into a single `DataFrame` ``` final_answer = pd.DataFrame() final_answer_list = [] for i in range(1, len(answer) + 1): final_answer_list.append(answer[i]) final_answer = pd.concat(final_answer_list) ``` ### Save it as CSV ``` final_answer.to_csv('result/prediction.csv', index=False) ```
github_jupyter
``` import os os.chdir('/Users/sheldon/git/podly_app/new_files') import glob files = [f for f in os.listdir('.') if os.path.isfile(f)] files = glob.glob('*.txt') import pandas as pd series = [] for i in files: series.append(i.split('.mp3')[0]) x = pd.DataFrame(series) def read_podcast(file): tempFile = open(file).read() return tempFile transcriptions = [] for i in files: transcription = open(i).read() transcriptions.append(transcription) x['transcription'] = transcriptions x.head() x.columns = ['file','transcription'] fileList = range(1, len(files)+1) x['index'] = fileList x.head() from nltk.corpus import stopwords stop = set(stopwords.words('english')) def tokenize_and_lower(textfile): tokens = word_tokenize(textfile) lower = [w.lower() for w in tokens] filtered_words = [word for word in lower if word not in stop] return filtered_words from nltk.corpus import stopwords from collections import Counter import pandas as pd import numpy as np import nltk.data from __future__ import division # Python 2 users only import nltk, re, pprint from nltk import word_tokenize tokenized_all_docs = [tokenize_and_lower(doc) for doc in transcriptions] tokenized_all_docs from gensim import corpora dictionary = corpora.Dictionary(tokenized_all_docs) dictionary.save('sample.dict') print dictionary corpus = [dictionary.doc2bow(text) for text in tokenized_all_docs] corpora.MmCorpus.serialize('corpus.mm', corpus) from gensim import models, corpora, similarities tfidf = models.TfidfModel(corpus) corpus_tfidf = tfidf[corpus] lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10) corpus_lsi = lsi[corpus_tfidf] index = similarities.MatrixSimilarity(lsi[corpus]) lsi.print_topics(10) def get_related_podcasts_query(query): query = query.lower() vec_box = dictionary.doc2bow(query.split()) vec_lsi = lsi[vec_box] sims = index[vec_lsi] sims = sorted(enumerate(sims), key=lambda item: -item[1])[0:10] related_df = pd.DataFrame(sims,columns=['index','score']) final_df = pd.merge(related_df, x, on='index')[['index','file','score']] return final_df def get_related_podcasts(index): def getKey(item): return item[1] corpus = corpus_lsi[index] corpus = sorted(corpus, key=getKey, reverse=True)[0:10] related_df = pd.DataFrame(corpus,columns=['index','score']) final_df = pd.merge(related_df, x, on='index')[['index','file','score']] return final_df get_related_podcasts_query('math') related_podcasts = list(get_related_podcasts(1)['index']) def get_topics_per_podcast(podcast_index): def getKey(item): return item[1] topic_ids = [i for i in sorted(corpus_lsi[podcast_index], key=getKey, reverse=True) if i[1] > 0.10] def get_topic_arrays(topic_ids): x = [] for id in topic_ids: list_of_words = sorted(lsi.show_topic(id[0], topn=5),key=getKey, reverse=True) z = [] for word in list_of_words: if word[1] > .05: z.append(word) x.append(z) return x topic_arrays = get_topic_arrays(topic_ids) return topic_arrays related_podcasts_topics_words = [[related_podcasts[i],get_topics_per_podcast(related_podcasts[i])] for i in range(0, len(related_podcasts))] episode_podcasts = list(get_related_podcasts(1)['file']) for i,k in enumerate(related_podcasts_topics_words): print "Podcast: {}, ID: {}".format(i+1, k[0]) print "Episode Title: {}".format(episode_podcasts[i]) for num, topic in enumerate(k[1]): print "topic: {}".format(num) for word in topic: print "word: {}, score:{}".format(word[0], word[1]) ```
github_jupyter
# Imports ``` import pandas as pd import numpy as np import seaborn as sns import pycountry_convert as pc import statsmodels.formula.api as sm from statsmodels.tsa.seasonal import STL from scipy.stats import pearsonr from scipy.misc import derivative from scipy.optimize import fsolve import numpy as np sns.set_style('darkgrid') ``` # Data view ``` df = pd.read_csv('final_data.csv') df.head() df.info() df.dt = pd.to_datetime(df.dt) df.describe() df.isna().sum() ``` # Aggregate to continents ``` def get_continent(country): try: return pc.country_alpha2_to_continent_code(pc.country_name_to_country_alpha2(country)) except: pass df['Continent'] = df.apply(lambda row: get_continent(row.Country), axis=1) df[df.Continent.isna()].loc[:, 'Country'].unique() # to be mapped/removed #TODO instead of this there should be mapping of not detected countries to continent df.dropna(inplace=True) def avg_continent(continent): time_series = pd.DataFrame(df[df.Continent==continent].groupby('dt').AverageTemperature.mean()) time_series['Continent'] = continent time_series['x'] = list(range(len(time_series))) return time_series agg_continents = pd.concat([avg_continent(continent) for continent in df.Continent.unique()]) ``` # Growth significancy ``` g = sns.lmplot(data=agg_continents, x='x', y='AverageTemperature', hue='Continent', scatter=False, lowess=True) g.axes.flat[0].set_xticks(list(range(0, len(agg_continents.index.unique()), 120))) g.axes.flat[0].set_xticklabels(list(df.year.unique())[::10], rotation=45) g def linear_regression(continental): data = pd.DataFrame({'x': list(range(len(continental))), 'y': continental.values}) return sm.ols(data=data, formula='y ~ x').fit().params.x agg_continents.groupby('Continent').AverageTemperature.agg(linear_regression).reset_index() # consider using another test def correlation_test(continental): # optional but gives different results - to consider res = STL(continental.values, period=12, seasonal=3).fit() # value of `seasonal` can be changed continental -= res.seasonal data = pd.DataFrame({'x': list(range(len(continental))), 'y': continental.values}) return pearsonr(data.x, data.y) agg_continents.groupby('Continent').AverageTemperature.agg(correlation_test).reset_index() ``` # Start of global warming ``` def inflection_point(y, deg=3): x = np.arange(len(y)) x0 = np.mean([x[0], x[-1]]) coef = np.polyfit(x, y, deg) construct_polynomial = lambda coef: np.vectorize( lambda x: np.dot(coef, np.array([x**i for i in range(len(coef)-1, -1, -1)]))) return y.index[int(round(fsolve(lambda x_prime: derivative(construct_polynomial(coef), x_prime, n=2), x0)[0]))], coef[0] agg_continents.groupby('Continent').AverageTemperature.agg(inflection_point).reset_index() ```
github_jupyter
``` import numpy as np import pandas as pd np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from keras.models import Model from keras.layers import Dense, Conv2D, BatchNormalization, MaxPooling2D, Flatten, Dropout, Input from keras.preprocessing.image import ImageDataGenerator from keras.optimizers import SGD import os print(os.listdir("../input/")) from PIL import Image # Create a class to store global variables. Easier for adjustments. class Configuration: def __init__(self): self.epochs = 50 self.batch_size = 16 self.maxwidth =0 self.maxheight=0 self.minwidth = 35000 self.minheight = 35000 self.imgcount=0 self.img_width_adjust = 224 self.img_height_adjust= 224 #Kaggle self.data_dir = "../input/train/" config = Configuration() ``` ## Data Exploration ``` #Load an example photo import matplotlib.pyplot as plt import matplotlib.image as mpimg img=mpimg.imread('../input/train/c0/img_4013.jpg') imgplot = plt.imshow(img) img.shape plt.show() #Find the largest and smallest dimensions of all the pictures def findPictureDims(path): for subdir, dirs, files in os.walk(path): for file in files: if file.endswith(".jpg"): config.imgcount+=1 filename = os.path.join(subdir, file) image = Image.open(filename) width, height = image.size if width < config.minwidth: config.minwidth = width if height < config.minheight: config.minheight = height if width > config.maxwidth: config.maxwidth = width if height > config.maxheight: config.maxheight = height return #Count the number of files in each subdirectory def listDirectoryCounts(path): d = [] for subdir, dirs, files in os.walk(path,topdown=False): filecount = len(files) dirname = subdir d.append((dirname,filecount)) return d def SplitCat(df): for index, row in df.iterrows(): directory=row['Category'].split('/') if directory[3]!='': directory=directory[3] df.at[index,'Category']=directory else: df.drop(index, inplace=True) return #Get image count per category dirCount=listDirectoryCounts(config.data_dir) categoryInfo = pd.DataFrame(dirCount, columns=['Category','Count']) SplitCat(categoryInfo) categoryInfo=categoryInfo.sort_values(by=['Category']) print(categoryInfo.to_string(index=False)) #Print out mins and maxes and the image counts findPictureDims(config.data_dir) print("Minimum Width:\t",config.minwidth, "\tMinimum Height:",config.minheight) print("Maximum Width:\t",config.maxwidth, "\tMaximum Height:",config.maxheight, "\tImage Count:\t",config.imgcount) ``` ## Analysis -All of the data in the training directory is of the same height and width. -The aspect ratio of the pictures is 4:3, so any adjustments are made should be close to that ratio (see configuration) ## Building the Model ``` import numpy as np from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras.applications.imagenet_utils import preprocess_input import pydot from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from keras.utils import plot_model #from resnets_utils import * from keras.initializers import glorot_uniform import scipy.misc from matplotlib.pyplot import imshow import keras.backend as K K.set_image_data_format('channels_last') K.set_learning_phase(1) %matplotlib inline # In[2]: def identity_block(X, f, filters, stage, block): """ Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage -- integer, used to name the layers, depending on their position in the network block -- string/character, used to name the layers, depending on their position in the network Returns: X -- output of the identity block, tensor of shape (n_H, n_W, n_C) """ # defining name basis conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Retrieve Filters F1, F2, F3 = filters # Save the input value. You'll need this later to add back to the main path. X_shortcut = X # First component of main path X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X) X = Activation('relu')(X) # Second component of main path X = Conv2D(filters = F2, kernel_size = (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) X = Activation('relu')(X) # Third component of main path X = Conv2D(filters = F3, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X) # Final step: Add shortcut value to main path, and pass it through a RELU activation X = Add()([X, X_shortcut]) X = Activation('relu')(X) return X # In[3]: def convolutional_block(X, f, filters, stage, block, s = 2): """ Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage -- integer, used to name the layers, depending on their position in the network block -- string/character, used to name the layers, depending on their position in the network s -- Integer, specifying the stride to be used Returns: X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C) """ # defining name basis conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Retrieve Filters F1, F2, F3 = filters # Save the input value X_shortcut = X ##### MAIN PATH ##### # First component of main path X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X) X = Activation('relu')(X) # Second component of main path X = Conv2D(filters = F2, kernel_size = (f, f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X) X = Activation('relu')(X) # Third component of main path X = Conv2D(filters = F3, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X) ##### SHORTCUT PATH #### X_shortcut = Conv2D(filters = F3, kernel_size = (1, 1), strides = (s,s), padding = 'valid', name = conv_name_base + '1', kernel_initializer = glorot_uniform(seed=0))(X_shortcut) X_shortcut = BatchNormalization(axis = 3, name = bn_name_base + '1')(X_shortcut) # Final step: Add shortcut value to main path, and pass it through a RELU activation X = Add()([X, X_shortcut]) X = Activation('relu')(X) return X # In[49]: def ResNet50(input_shape = (224,224,3), classes = 10): """ Implementation of the popular ResNet50 the following architecture: CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3 -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras """ # Define the input as a tensor with shape input_shape X_input = Input(input_shape) # Zero-Padding X = ZeroPadding2D((3, 3))(X_input) # Stage 1 X = Conv2D(32, (7, 7), strides = (2, 2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = 'bn_conv1')(X) X = Activation('relu')(X) X = MaxPooling2D((3, 3), strides=(2, 2))(X) # Stage 2 X = convolutional_block(X, f = 5, filters = [32, 32, 128], stage = 2, block='a', s = 1) X = identity_block(X, 5, [32, 32, 128], stage=2, block='b') X = identity_block(X, 5, [32, 32, 128], stage=2, block='c') # Stage 3 X = convolutional_block(X, f = 3, filters = [64,64,256], stage = 3, block='a', s = 2) X = identity_block(X, 3, [64,64,256], stage=3, block='b') X = identity_block(X, 3, [64,64,256], stage=3, block='c') X = identity_block(X, 3, [64,64,256], stage=3, block='d') # Stage 4 X = convolutional_block(X, f = 3, filters = [128,128,512], stage = 4, block='a', s = 2) X = identity_block(X, 3, [128,128,512], stage=4, block='b') X = identity_block(X, 3, [128,128,512], stage=4, block='c') X = identity_block(X, 3, [128,128,512], stage=4, block='d') X = identity_block(X, 3, [128,128,512], stage=4, block='e') X = identity_block(X, 3, [128,128,512], stage=4, block='f') # Stage 5 X = convolutional_block(X, f = 3, filters = [256,256,1024], stage = 5, block='a', s = 2) X = identity_block(X, 3, [256,256,1024], stage=5, block='b') X = identity_block(X, 3, [256,256,1024], stage=5, block='c') # AVGPOOL X = AveragePooling2D(pool_size=(5, 5), padding='valid')(X) # output layer X = Flatten()(X) X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X) # Create model model = Model(inputs = X_input, outputs = X, name='ResNet50') return model # In[50]: model = ResNet50(input_shape = (224, 224, 3), classes = 10) model.summary() #Model Definition def build_model(): inputs = Input(shape=(config.img_width_adjust,config.img_height_adjust,3), name="input") #Convolution 1 conv1 = Conv2D(128, kernel_size=(3,3), activation="relu", name="conv_1")(inputs) pool1 = MaxPooling2D(pool_size=(2, 2), name="pool_1")(conv1) #Convolution 2 conv2 = Conv2D(64, kernel_size=(3,3), activation="relu", name="conv_2")(pool1) pool2 = MaxPooling2D(pool_size=(2, 2), name="pool_2")(conv2) #Convolution 3 conv3 = Conv2D(32, kernel_size=(3,3), activation="relu", name="conv_3")(pool2) pool3 = MaxPooling2D(pool_size=(2, 2), name="pool_3")(conv3) #Convolution 4 conv4 = Conv2D(16, kernel_size=(3,3), activation="relu", name="conv_4")(pool3) pool4 = MaxPooling2D(pool_size=(2, 2), name="pool_4")(conv4) #Fully Connected Layer flatten = Flatten()(pool4) fc1 = Dense(1024, activation="relu", name="fc_1")(flatten) #output output=Dense(10, activation="softmax", name ="softmax")(fc1) # finalize and compile model = Model(inputs=inputs, outputs=output) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=["accuracy"]) return model model1 = build_model() model1.summary() #Setup data, and create split for training, testing 80/20 def setup_data(train_data_dir, val_data_dir, img_width=config.img_width_adjust, img_height=config.img_height_adjust, batch_size=config.batch_size): train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, validation_split=0.2) # set validation split train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', subset='training') validation_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', subset='validation') #Note uses training dataflow generator return train_generator, validation_generator def fit_model(model, train_generator, val_generator, batch_size, epochs): model.fit_generator( train_generator, steps_per_epoch=train_generator.samples // batch_size, epochs=epochs, validation_data=val_generator, validation_steps=val_generator.samples // batch_size, verbose=1) return model #Verbose: 0: no output, 1: output with status bar, 2: Epochs Only # Model Evaluation def eval_model(model, val_generator, batch_size): scores = model.evaluate_generator(val_generator, steps=val_generator.samples // batch_size) print("Loss: " + str(scores[0]) + " Accuracy: " + str(scores[1])) # Create Data 80/20 train_generator, val_generator = setup_data(config.data_dir, config.data_dir, batch_size=config.batch_size) import time #let's also import the abstract base class for our callback from keras.callbacks import Callback #defining the callback class TimerCallback(Callback): def __init__(self, maxExecutionTime, byBatch = False, on_interrupt=None): # Arguments: # maxExecutionTime (number): Time in minutes. The model will keep training # until shortly before this limit # (If you need safety, provide a time with a certain tolerance) # byBatch (boolean) : If True, will try to interrupt training at the end of each batch # If False, will try to interrupt the model at the end of each epoch # (use `byBatch = True` only if each epoch is going to take hours) # on_interrupt (method) : called when training is interrupted # signature: func(model,elapsedTime), where... # model: the model being trained # elapsedTime: the time passed since the beginning until interruption self.maxExecutionTime = maxExecutionTime * 60 self.on_interrupt = on_interrupt #the same handler is used for checking each batch or each epoch if byBatch == True: #on_batch_end is called by keras every time a batch finishes self.on_batch_end = self.on_end_handler else: #on_epoch_end is called by keras every time an epoch finishes self.on_epoch_end = self.on_end_handler #Keras will call this when training begins def on_train_begin(self, logs): self.startTime = time.time() self.longestTime = 0 #time taken by the longest epoch or batch self.lastTime = self.startTime #time when the last trained epoch or batch was finished #this is our custom handler that will be used in place of the keras methods: #`on_batch_end(batch,logs)` or `on_epoch_end(epoch,logs)` def on_end_handler(self, index, logs): currentTime = time.time() self.elapsedTime = currentTime - self.startTime #total time taken until now thisTime = currentTime - self.lastTime #time taken for the current epoch #or batch to finish self.lastTime = currentTime #verifications will be made based on the longest epoch or batch if thisTime > self.longestTime: self.longestTime = thisTime #if the (assumed) time taken by the next epoch or batch is greater than the #remaining time, stop training remainingTime = self.maxExecutionTime - self.elapsedTime if remainingTime < self.longestTime: self.model.stop_training = True #this tells Keras to not continue training print("\n\nTimerCallback: Finishing model training before it takes too much time. (Elapsed time: " + str(self.elapsedTime/60.) + " minutes )\n\n") #if we have passed the `on_interrupt` callback, call it here if self.on_interrupt is not None: self.on_interrupt(self.model, self.elapsedTime) timerCallback = TimerCallback(350) from keras.callbacks import ModelCheckpoint model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) batch_size = 16 model.fit_generator( train_generator, steps_per_epoch=train_generator.samples // 16, epochs=config.epochs, validation_data=val_generator, validation_steps=val_generator.samples // 16, verbose=1,callbacks = [timerCallback, ModelCheckpoint('my_weights.h5')]) ``` ## Evaluation ``` # Evaluate your model. eval_model(model, val_generator, batch_size=config.batch_size) ```
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import glob %matplotlib inline ### Reading all file from glob module ### The glob module is used to retrieve files/pathnames matching a specified pattern. path = r'E:\project\Transport_Vehicle_Online_Sales\Data_Vehicle_Sales' all_files = glob.glob(path + "/*.csv") all_file_list= [] for filename in all_files: df = pd.read_csv(filename, index_col=None, header=0, encoding = "latin") all_file_list.append(df) ### Concating all the dataframes of differnt csv files data1 = pd.concat(all_file_list[1:], axis=0, ignore_index=True) ### Droped 'fromdata' and 'todate' columns from "data1" dataframe data1 = data1.drop(['fromdate', 'todate'], axis=1) ### Droped 'Approved_Dt' columns ### data2 in this dataframe InsuranceCompany name is given data2 = all_file_list[0].drop(['Apprved_Dt'], axis=1) ### Droped 'InsuranceCompany' columns from data2 inorder to make the frame collumns and data2Temp columns equal data2Temp = data2.drop(['InsuranceCompany'], axis=1) data2Temp.columns ### change columns names data2Temp.columns = ['slno', 'modelDesc', 'fuel', 'colour', 'vehicleClass', 'makeYear', 'seatCapacity', 'insuranceValidity', 'secondVehicle', 'tempRegistrationNumber', 'category', 'makerName', 'OfficeCd'] ### Again concating two data frames i.e frame and data2Temp li=[data1, data2Temp] data1 = pd.concat(li, axis=0, ignore_index=True) ### Dropped slno columns from data1 data1=data1.drop(['slno'], axis=1) data1.head(2) ### drop insuranceValidity data1 = data1.drop(['insuranceValidity'], axis=1) data1['fuel'].unique() data1.loc[data1['fuel']=='D', 'fuel'] = 'DIESEL' data1.loc[data1['fuel']=='P', 'fuel'] = 'PETROL' data1.loc[data1['fuel']=='L', 'fuel'] = 'LPG' data1.loc[data1['fuel']=='B', 'fuel'] = 'BATTERY' data1.loc[data1['fuel']=='C', 'fuel'] = 'CNG' data1['fuel'].unique() ``` ## Handling missing values ``` data1.isnull().sum() data1[data1['fuel'].isnull()]['vehicleClass'].value_counts() sop=data1[data1['vehicleClass']=='Trailer For Commercial Use']['fuel'].notnull() sop=list(sop[sop].index) data1.loc[sop, 'fuel'].value_counts() ### Gathering all notnull value of the different catogery of model name i.e 'modelDesc' depending on its fuel type ### Gathering of fuel type value from 'vehicleClass' of 'Trailer For Commercial Use' TC = data1[data1['vehicleClass'] == 'Trailer For Commercial Use']['fuel'].notnull() TC = list(TC[TC].index) dieselName = data1.loc[TC, 'fuel'] == 'DIESEL' dieselName = list(dieselName[dieselName].index) dieselName = list(data1.iloc[dieselName,1].unique()) oneName = data1.loc[TC, 'fuel'] == '-1' oneName = list(oneName[oneName].index) oneName = list(data1.loc[oneName, 'modelDesc'].unique()) TC = data1[data1['vehicleClass'] == 'Trailer For Commercial Use']['fuel'].isnull() TC = list(TC[TC].index) data1.loc[TC, 'modelDesc'].isin(dieselName).value_counts() TC = data1[data1['vehicleClass'] == 'Trailer For Commercial Use']['fuel'].isnull() TC = list(TC[TC].index) dcc=0 occ=0 for i in TC: if data1.loc[i, 'modelDesc'] in dieselName: dcc=dcc+1 elif data1.loc[i, 'modelDesc'] in oneName: occ=occ+1 print("diesel name of notnull fuel value match with nan fuel value's model name",dcc) print("-1 name of notnull fuel value match with nan fuel value's model name",occ) ### filling missing value based on same model name ### also noticed that some name are common among diesel and non fuel varient name ### so as per data without fuel varient is large in number and diesel varient is less in number ### so we try to fill diesel value first dieN = data1.loc[TC,'modelDesc'].isin(dieselName) oneN = data1.loc[TC,'modelDesc'].isin(oneName) data1.loc[dieN[dieN].index, 'fuel'] = 'DIESEL' data1.loc[oneN[oneN].index, 'fuel'] = '-1' data1[data1['fuel'].isnull()]['vehicleClass'].value_counts() ### fuel type in "Trailer For Commercial Use" dddd=data1[data1['fuel'].notnull()]['vehicleClass']=='Trailer For Commercial Use' data1.loc[dddd[dddd].index,'fuel'].value_counts().plot.bar() ### filling rest missing value with most occured value catt=data1[data1['fuel'].isnull()]['vehicleClass'] == 'Trailer For Commercial Use' data1.loc[catt[catt].index, 'fuel'] = '-1' data1[data1['fuel'].isnull()]['vehicleClass'].value_counts() ### Handling missing 'fuel' value of 'vehicleClass' sub category "Trailer for Agriculture Purpose" dddd=data1[data1['fuel'].notnull()]['vehicleClass'] == 'Trailer for Agriculture Purpose' data1.loc[dddd[dddd].index,'fuel'].value_counts().plot.bar() ### Gathering all notnull value of the different catogery of model name i.e 'modelDesc' depending on its fuel type ### Gathering of fuel type value from 'vehicleClass' of 'Trailer for Agriculture Purpose' TC = data1[data1['vehicleClass'] == 'Trailer for Agriculture Purpose']['fuel'].notnull() TC = list(TC[TC].index) dieselName = data1.loc[TC, 'fuel'] == 'DIESEL' dieselName = list(dieselName[dieselName].index) dieselName = list(data1.loc[dieselName, 'modelDesc'].unique()) petrolName = data1.loc[TC, 'fuel'] == 'PETROL' petrolName = list(petrolName[petrolName].index) petrolName = list(data1.loc[petrolName,'modelDesc'].unique()) oneName = data1.loc[TC, 'fuel'] == '-1' oneName = list(oneName[oneName].index) oneName = list(data1.loc[oneName,'modelDesc'].unique()) TC = data1[data1['vehicleClass'] == 'Trailer for Agriculture Purpose']['fuel'].isnull() TC = list(TC[TC].index) data1.loc[TC, 'modelDesc'].isin(oneName).value_counts() ### notnull fuel type model name match with nan fuel value model name TC = data1[data1['vehicleClass'] == 'Trailer for Agriculture Purpose']['fuel'].isnull() TC = list(TC[TC].index) dcc=0 occ=0 pcc=0 for i in TC: if data1.loc[i, 'modelDesc'] in dieselName: dcc=dcc+1 elif data1.loc[i, 'modelDesc'] in oneName: occ=occ+1 elif data1.loc[i, 'modelDesc'] in petrolName: pcc=pcc+1 print("Diesel name of notnull fuel value match with nan fuel value's model name = ",dcc) print("") print("Petrol name of notnull fuel value match with nan fuel value's model name = ",pcc) print("") print("-1 name of notnull fuel value match with nan fuel value's model name = ",occ) dieN = data1.loc[TC, 'modelDesc'].isin(dieselName) oneN = data1.loc[TC, 'modelDesc'].isin(oneName) data1.loc[dieN[dieN].index, 'fuel'] = 'DIESEL' data1.loc[oneN[oneN].index, 'fuel'] = '-1' data1[data1['fuel'].isnull()]['vehicleClass'].value_counts() ### fuel type in "Trailer for Agriculture Purpose" dddd=data1[data1['fuel'].notnull()]['vehicleClass']=='Trailer for Agriculture Purpose' data1.loc[dddd[dddd].index,'fuel'].value_counts().plot.bar() ### filling rest missing value with most occured value catt=data1[data1['fuel'].isnull()]['vehicleClass'] == 'Trailer for Agriculture Purpose' data1.loc[catt[catt].index, 'fuel'] = '-1' #### handling missing values of 'MOTOR CYCLE' of vehicleClass ### fuel type in "MOTOR CYCLE" dddd=data1[data1['fuel'].notnull()]['vehicleClass']=='MOTOR CYCLE' data1.loc[dddd[dddd].index,'fuel'].value_counts() ### filling rest missing value with most occured value of 'MOTOR CYCLE' catt=data1[data1['fuel'].isnull()]['vehicleClass'] == 'MOTOR CYCLE' data1.loc[catt[catt].index, 'fuel'] = 'PETROL' #### handling missing values of 'MOTOR CAR' of vehicleClass ### fuel type in "MOTOR CAR" dddd=data1[data1['fuel'].notnull()]['vehicleClass']=='MOTOR CAR' data1.loc[dddd[dddd].index,'fuel'].value_counts().plot.bar() ### Motor car missing value filled by random value i.e (Petrol,Diesel) because occurrence of both is maximum car=data1[data1['vehicleClass'] == 'MOTOR CAR']['fuel'].isnull() count_car = len(car[car]) np.random.seed(0) car_varient = np.random.choice(['DIESEL','PETROL'], size=count_car) data1.loc[car[car].index, 'fuel'] = car_varient data1[data1['fuel'].isnull()]['vehicleClass'].value_counts().sort_values( ascending=False) ### maximum missing value of top 3 vehicleClass fuel varient val=data1[data1['fuel'].isnull()]['vehicleClass'].unique()[:3] fig, axes = plt.subplots(nrows=1,ncols=3, figsize=(15,4),constrained_layout=True) data1.loc[data1['vehicleClass']=='Tractor for Agricultural Purpose','fuel'].value_counts().plot(ax=axes[0], kind='bar', title='Tractor for Agricultural Purpose') data1.loc[data1['vehicleClass']=='Luxory Tourist Cab','fuel'].value_counts().plot(ax=axes[1], kind='bar', title='Luxory Tourist Cab') data1.loc[data1['vehicleClass']=='Motor Cab','fuel'].value_counts().plot(ax=axes[2], kind='bar', title='Motor Cab') data1.loc[data1['fuel'].isnull(),'fuel']='DIESEL' ``` ### Handling OfficeCd missing value ``` d=data1.isnull().sum().sort_values(ascending=False) d[d.values>0] ### vehicle first 4 digit number data1["rto"]=data1['tempRegistrationNumber'].astype(str).str[0:4] ### vehicle state data1['state'] = data1['rto'].astype(str).str[:2] data1.apply(lambda x : pd.factorize(x)[0]).corr(method='pearson', min_periods=1) ### for OfficeCd missing values ### 1.) group the rto and category ### 2.) take the top 3 most frequent OfficeCd of peticular group ### 3.) randomly fill that value in perticular group c_test=data1.groupby(['rto', 'category']).groups for cate_rto in c_test.keys(): missing_office=data1.loc[c_test[cate_rto], 'OfficeCd'].isnull().sum() if missing_office: dat = data1.loc[c_test[cate_rto], 'OfficeCd'].value_counts().sort_values(ascending=False).keys()[:3] count_office = data1.loc[c_test[cate_rto],'OfficeCd'].isnull().sum() np.random.seed(0) choice_cate = np.random.choice(dat, size=count_office) d=data1.loc[c_test[cate_rto], 'OfficeCd'].isnull() data1.loc[d[d].index, 'OfficeCd'] = choice_cate d=data1.isnull().sum() d[d>0] ### Replacing Colour NIL value with most frequent colour of perticular vehicle class d=data1['colour']=='NIL' vehi_class = data1.loc[d[d].index, 'vehicleClass'].unique() for clas in vehi_class: val = data1[data1['vehicleClass'] == clas]['colour'].value_counts().sort_values(ascending=False).keys() if val[0].upper() == 'NIL': val = val[1] else: val=val[0] d = data1[(data1['vehicleClass'] == clas)&(data1['colour']=='NIL')] data1.loc[d.index, 'colour'] = val ### handling colour missing value ### filling nan value with most frequent colour of perticular vehicle class d=data1['colour'].isnull() vehi_class = data1.loc[d[d].index, 'vehicleClass'].unique() data1['colour'] = data1['colour'].str.upper() for clas in vehi_class: val = data1[data1['vehicleClass'] == clas]['colour'].value_counts().sort_values(ascending=False).keys() if val[0].upper() == 'NIL': print(val) else: val=val[0] d = data1[data1['vehicleClass'] == clas]['colour'].isnull() data1.loc[d[d].index, 'colour'] = val data1.isnull().sum() ``` ### Features play ``` ### manufacturing month and manufacturing year d=data1['makeYear'].notnull() data1['manufacturing_year']=data1.loc[d[d].index,'makeYear'].apply(lambda x: str('20') + x.split('/')[2] if len(x.split('/')[2])==2 else x.split('/')[2]) data1['manufacturing_year'] = data1['manufacturing_year'].astype(int) dict_month={'02':'February', '01':'January', '04':'April ', '03':'March', '05':'May', '11':'November', '07':'July', '12':'December', '09':'September', '10':'October', '08':'August', '06':'Jun'} data1['manufacturing_month']=data1.loc[d[d].index,'makeYear'].apply(lambda x: x.split('/')[1]).map(dict_month) c=data1['manufacturing_year'].astype(int) c[c>2020].index data1.loc[3577031,'manufacturing_year']=1985 data1['howOld']=2020-data1['manufacturing_year'].astype(int) data1.columns ### maximum missing value of top 3 vehicleClass fuel varient #fig, axes = plt.subplots(nrows=2,ncols=2, figsize=(15,6),constrained_layout=True) fig = plt.figure(figsize=(15,6)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(212) data1.boxplot(column = 'manufacturing_year', ax=ax1, vert=False) data1.boxplot(column='howOld', ax=ax2, vert=False) data1.boxplot(column='seatCapacity', ax=ax3, vert=False) import matplotlib fig, ax1 = plt.subplots(figsize=(18, 15)) c=[c for c in data1.groupby(['howOld']).groups.keys()] cy = [len(i) for i in list(data1.groupby(['howOld']).groups.values())] ax1.plot(c,cy, '*g--') ax1.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax1.grid() plt.xlabel("How old vehicle", axes=ax1, size=15) plt.ylabel("Total registerd vehicle", axes=ax1, size=15) plt.title("Total vehicle distribution as per its age", axes=ax1, size=20) plt.show() fig, ax1 = plt.subplots(figsize=(18, 15)) c=[c for c in data1.groupby(['seatCapacity']).groups.keys()] cy = [len(i) for i in list(data1.groupby(['seatCapacity']).groups.values())] ax1.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax1.plot(c,cy, '*r--') #plt.xticks(keys, rotation='vertical', size=15, axes=ax1) ax1.grid() plt.xlabel("Vehicle count", axes=ax1, size=15) plt.ylabel("Vehicle Seat capacity", axes=ax1, size=15) plt.title("Total vehicle distribution as per its Seat Capacity", axes=ax1, size=20) plt.show() ### year sold vehicle class keys = [pair for pair in data1.groupby(['manufacturing_year']).groups] fig, ax = plt.subplots(figsize=(25, 20)) ax.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) c=[c for c in data1.groupby(['manufacturing_year']).groups.keys()] cy = [len(i) for i in list(data1.groupby(['manufacturing_year']).groups.values())] ax.plot(c,cy, '*r--') plt.xticks(keys, rotation='vertical', size=15, axes=ax) plt.yticks(np.arange(0, max(cy), 100000), axes=ax, size=20) ax.grid(color='lightgreen') plt.xlabel("Vehicle count", axes=ax1, size=20) plt.ylabel("Vehicle Manufacturing Year", axes=ax1, size=20) plt.title("Total vehicle distribution as per its Manufacturing Year", size=25) plt.show() data1['vehicleClass'].unique() from random import randrange c=[i for i in data1.groupby(['vehicleClass']).groups.keys()] cy=[len(i) for i in data1.groupby('vehicleClass').groups.values()] fig, ax =plt.subplots(figsize=(25, 20)) c_data = [randrange(50,250) for i in range(len(c))] my_cmap = matplotlib.cm.get_cmap('jet') plt.bar(c, cy, axes=ax, color=my_cmap(c_data)) plt.xticks(c, rotation='vertical', axes=ax, size=20) plt.yticks(np.arange(0, max(cy), 100000), axes=ax, size=20) ax.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) plt.xlabel("Vehicle count", axes=ax, size=30) plt.ylabel("Vehicle class", axes=ax, size=30) plt.title("Total vehicle distribution as per Vehicle class", axes=ax, size=30) plt.grid(color='lightblue') plt.show() ```
github_jupyter
``` from collections import Counter import matplotlib.pyplot as plt import pandas as pd import numpy as np import ast import json df = pd.read_csv('/home/amir/projects/light-sa-type-inf/ManyTypes4Py_processed_fix_feb2/all_fns.csv', low_memory=False) jsons_merged = json.load(open('/home/amir/ManyTypes4Py_processed_Mar1/merged_projects.json', 'r')) df.head() print("Number of projects: ", len(set(df.apply(lambda x: x['author'] + "/" + x['repo'], axis=1)))) print(f"Number of source code files: {len(df['file'].unique()):,}") print(f"Number of files with type annotations: {len(df[df['has_type'] == True].drop_duplicates('file', keep='last')):,}") print(f"Number of functions: {len(df.fn_name):,}") print(f"Number of classes: {df.cls_name.count():,}") print(f"Number of functions with a type: {len(df[df['has_type'] == True]):,}") print(f"Number of arguemts: {sum(df['arg_names'].apply(lambda x: len(ast.literal_eval(x)))):,}") print(f"Number of arguemts with types: {sum(df['arg_types'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))):,}") print(f"Number of functions with a return type: {df['return_type'].count():,}") print(f"Number of functions with docstring: {df['docstring'].count():,}") print(f"Number of functions with description: {df['func_descr'].count():,}") print(f"Number of arguemts with comments: {sum(df['arg_descrs'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))):,}") print(f"Number of functions with a comment: {df['docstring'].count() + df['fn_descr'].count() + sum(df['arg_descrs'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))) + df['return_descr'].count():,}") print(f"Number functions with a return type comment: {df['return_descr'].count():,}") args_t = list(df['arg_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) ret_t = list(df[df['return_type'].notnull()]['return_type'].values) fn_vars_t = list(df['fn_variables_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) cls_vars_t = [t for cls_t in df.drop_duplicates('cls_name', keep='last')[df['cls_variables_types'].notnull()]['cls_variables_types'] for t in ast.literal_eval(cls_t) if t != ''] mod_vars_t = list(df.drop_duplicates('file', keep='last')['mod_variables_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) print(f"Total Number of type annotations: {sum([len(t)for t in args_t]) + len(ret_t) + sum([len(t) for t in fn_vars_t]) + len(cls_vars_t) + sum([len(t) for t in mod_vars_t]):,}") print(f"Number of unique types: {len(set([t for l in args_t for t in l] + ret_t + [t for l in fn_vars_t for t in l] + cls_vars_t + [t for l in mod_vars_t for t in l])):,}") def set_stats(d, s): print(f"Number of projects: ", len(set(d[d['set'] == s].apply(lambda x: x['author'] + "/" + x['repo'], axis=1)))) print(f"Number of source code files: {len(d[d['set'] == s]['file'].unique()):,}") print(f"Number of files with type annotations: {len(d[d['set'] == s][d['has_type'] == True].drop_duplicates('file', keep='last')):,}") print(f"Number of functions: {len(d[d['set'] == s].fn_name):,}") print(f"Number of functions with a type: {len(d[d['set'] == s][d['has_type'] == True]):,}") print(f"Number of functions with a return type: {d[d['set'] == s]['return_type'].count():,}") print(f"Number of functions with docstring: {d[d['set'] == s]['docstring'].count():,}") print(f"Number of functions with description: {d[d['set'] == s]['fn_descr'].count():,}") print(f"Number functions with a return type comment: {d[d['set'] == s]['return_descr'].count():,}") print(f"Number of functions with a comment: {d[d['set'] == s]['docstring'].count() + d[d['set'] == s]['fn_descr'].count() + sum(d[d['set'] == s]['arg_descrs'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))) + d[d['set'] == s]['return_descr'].count():,}") print(f"Number of arguemts: {sum(d[d['set'] == s]['arg_names'].apply(lambda x: len(ast.literal_eval(x)))):,}") print(f"Number of arguemts with types: {sum(d[d['set'] == s]['arg_types'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))):,}") print(f"Number of arguemts with comments: {sum(d[d['set'] == s]['arg_descrs'].apply(lambda x: len([t for t in ast.literal_eval(x) if t != '']))):,}") set_stats(df, 'test') set_stats(df, 'train') def find_all_types_set(d, s): args_t = list(d[d['set'] == s]['arg_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) ret_t = list(d[d['set'] == s][d['return_type'].notnull()]['return_type'].values) fn_vars_t = list(d[d['set'] == s]['fn_variables_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) cls_vars_t = [t for cls_t in d.drop_duplicates('cls_name', keep='last')[d['cls_variables_types'].notnull()]['cls_variables_types'] for t in ast.literal_eval(cls_t) if t != ''] mod_vars_t = list(d.drop_duplicates('file', keep='last')['mod_variables_types'].apply(lambda x: [t for t in ast.literal_eval(x) if t != ''])) print(f"Total Number of type annotations: {sum([len(t)for t in args_t]) + len(ret_t) + sum([len(t) for t in fn_vars_t]) + len(cls_vars_t) + sum([len(t) for t in mod_vars_t]):,}") print(f"Number of unique types: {len(set([t for l in args_t for t in l] + ret_t + [t for l in fn_vars_t for t in l] + cls_vars_t + [t for l in mod_vars_t for t in l])):,}") find_all_types_set(df, 'train') ``` ## Distribution of Top 10 frequent types in the dataset ``` all_types = [l for t in args_t for l in t] + ret_t + \ [l for t in fn_vars_t for l in t] + cls_vars_t + [l for t in mod_vars_t for l in t] top_n=10 # Already sorted df_plot = pd.DataFrame.from_records(Counter(all_types).most_common(top_n), columns=['type', 'count']) print(f"Sum of Top {top_n} frequent types: {sum(counts)}") types = df_plot['type'].values[:top_n] counts = df_plot['count'].values[:top_n] y_pos = np.arange(len(counts)) plt.barh(y_pos, counts, align='center', alpha=0.5) plt.yticks(y_pos, types) plt.xlabel('Count') plt.ylabel('Types') #plt.title('Top %d most frequent types in the dataset' % top_n) plt.tight_layout() # Fixes the Y axis lables to be shown completely. # plt.savefig('top-%d-most-frequent-types.pdf' % top_n, format='pdf', bbox_inches='tight', # dpi=256) plt.show() all_types ``` Finding type annotation coverage ``` p_type_annote_cove = [(p, round(jsons_merged['projects'][p]['type_annot_cove'] * 100, 1)) for p in jsons_merged['projects'].keys()] len(list(filter(lambda x: x[1] > 0, p_type_annote_cove))) f_type_annote_cove = [(f, round(jsons_merged['projects'][p]['src_files'][f]['type_annot_cove'] * 100, 1)) for p in jsons_merged['projects'].keys() for f in jsons_merged['projects'][p]['src_files']] f_type_annote_cove type_cove_interval = {"[%d%%-%d%%%s" % (i, i+20, ']' if i + 20 == 100 else ')' ):[(i, i+20), 0] for i in range(0, 100, 20)} for p, t_c in p_type_annote_cove: for i, v in type_cove_interval.items(): if t_c >= v[0][0] and t_c < v[0][1]: type_cove_interval[i][1] += 1 print(type_cove_interval) f_type_cove_interval = {"[%d%%-%d%%%s" % (i, i+20, ']' if i + 20 == 100 else ')' ):[(i, i+20), 0] for i in range(0, 100, 20)} for p, t_c in f_type_annote_cove: for i, v in f_type_cove_interval.items(): if t_c >= v[0][0] and t_c < v[0][1]: f_type_cove_interval[i][1] += 1 f_type_cove_interval ``` ## Type annotations coverage for projects ``` f = plt.bar([i for i, v in type_cove_interval.items()], [v[1] for i, v in type_cove_interval.items()]) plt.xlabel("Percentage of type annotation coverage") plt.ylabel("No. of projects") for rect, v in zip(f.patches, [v[1] for i, v in type_cove_interval.items()]): plt.text(rect.get_x() + rect.get_width() / 2, rect.get_height()+5, str(v), fontweight='bold', ha='center', va='bottom') plt.tight_layout() plt.show() ``` ## Type annotations coverage for source code files ``` f = plt.bar([i for i, v in f_type_cove_interval.items()], [v[1] for i, v in f_type_cove_interval.items()]) plt.xlabel("Percentage of type annotation coverage") plt.ylabel("No. of source code files") for rect, v in zip(f.patches, [v[1] for i, v in f_type_cove_interval.items()]): plt.text(rect.get_x() + rect.get_width() / 2, rect.get_height()+5, str(v), fontweight='bold', ha='center', va='bottom') plt.tight_layout() plt.show() ```
github_jupyter
``` d ``` ## Import Required Libraries ``` import glob import numpy as np import pandas as pd EXPERIMENT_ID = '1005' experiment_dir = 'outputs/experiment_{}/'.format(EXPERIMENT_ID) results_path = experiment_dir + 'results.npy' schedules_path = experiment_dir + 'schedulesWithMakespan.npy' log_paths = glob.glob(experiment_dir + '*.log') ``` ## Read log files, and results ``` # logs = pd.concat([pd.read_csv(log_file) for log_file in log_paths], axis=0) result_columns = ['batch_id', 'makespan_mean', 'cum_makespan_mean', 'time', 'cum_time'] results = pd.DataFrame(np.load(results_path), columns=result_columns) with open(schedules_path, 'rb') as f: batch_schedules = np.load(f) batch_makespans = np.load(f) def convert_schedules_np_to_df(batch_schedules, batch_makespans): """Convert batch schedules from numpy array to dataframe""" n_batch_instance, batch_size, n_nodes, _ = batch_schedules.shape schedules = batch_schedules.reshape((n_batch_instance*batch_size, n_nodes, 2)) # remove machine-to-machine pair schedules = schedules[ np.not_equal( schedules[:,:,:1], schedules[:,:,1:] )[:,:,-1] ].reshape(schedules.shape[0], -1, schedules.shape[-1]).astype(str) n_jobs = schedules.shape[1] makespans = batch_makespans.reshape((n_batch_instance*batch_size,1)) df_schedules = pd.DataFrame( np.concatenate([ np.apply_along_axis( ' -> '.join, 0, [schedules[:,:,0], schedules[:,:,1]]), makespans ], axis=1), columns= list(map(lambda v: "J_"+str(v), range(n_jobs)))+['makespan'] ) return df_schedules df_schedules = convert_schedules_np_to_df(batch_schedules, batch_makespans) df_schedules.head(10) makespans.shape, schedules.shape np.apply_along_axis( ' -> '.join, 0, [schedules[:,:,0], schedules[:,:,1]]).shape np.concatenate([ np.apply_along_axis( ' -> '.join, 0, [schedules[:,:,0], schedules[:,:,1]]), makespans ], axis=1) #"V_".join(list(range(n_nodes))) list(map(lambda v: "V_"+str(v), range(1,n_nodes+1)))+['makespan'] "V_".join(map(str, range(1, n_nodes+1))) makespans.shape batch_makespans # r = best_schedules.reshape((64, 7, 2)) # #np.transpose(r, (0,2,1)) # r = r.astype(str) # r[:,:,0]# + "," + r[:,:,1] # #np.core.defchararray.add(r[:,:,0], r[:,:,1]) # # list(zip(r[:,:,0], r[:,:,1])) # # numpy.char.join(r[:,:,0], r[:,:,1]) #best_makespans.shape, a = np.arange(6).reshape((3, 2)) np.chararray((3, 3)) path = 'outputs/experiment_{}/schedulesWithMakespan.npy'.format(experiment_id) with open(path, 'rb') as f: best_schedules = np.load(f) best_makespans = np.load(f) path = 'outputs/experiment_{}/results.npy'.format(experiment_id) with open(path, 'rb') as f: results = np.load(f) log_path = 'outputs/experiment_{}/results.npy'.format(experiment_id) _columns = ['batch_id', 'makespan_mean', 'cum_makespan_mean', 'time', 'cum_time'] df = pd.DataFrame(results, columns=_columns) df ``` # Modules: Datasets and Graphs ``` import tensorflow as tf import tensorflow as tf from tensorflow.keras.layers import Layer from msp.datasets import make_data, load_sample_data, make_sparse_data from msp.graphs import MSPGraph, MSPSparseGraph from msp.models.encoders import GGCNEncoder from msp.models.decoders import AttentionDecoder %load_ext autoreload %autoreload 2 dataset = make_sparse_data(40, msp_size=(2,5), random_state=2021) type_ = tf.constant([[[4,3,6,1]],[[9,3,6,1]]]) # tf.slice(type_, [0,0,2], [-1,-1,-1]) temp = tf.zeros(type_.shape) cur_node = tf.constant([[2],[1]]) tf.tensor_scatter_nd_update(temp, indices, [1,1]) self._visited = tf.tensor_scatter_nd_update( tf.squeeze(temp, axis=-2), tf.concat([tf.reshape(tf.range(batch_size, dtype=tf.int64),cur_node.shape), cur_node], axis=1), tf.ones((batch_size,), dtype=self._visited.dtype) )[:,tf.newaxis,:] indices = tf.constant([[2],[1]]) tf.gather(tf.squeeze(type_), indices, batch_dims=1) tf.squeeze(type_) batch_size = 2 batch_dataset = dataset.batch(batch_size) inputs = list(batch_dataset.take(1))[0] inputs ``` # Modules: Layers and Encoders ``` units = 6 layers = 2 ecoder_model = GGCNEncoder(units, layers) embedded_inputs = ecoder_model(inputs) embedded_inputs.node_embed embedded_inputs.edge_embed ``` # Modules: Decoder ``` model = AttentionDecoder(units, aggregation_graph='mean', n_heads=3) makespan, ll, pi = model(embedded_inputs) pi ``` # All together ``` n_instances = 640 instance_size = (2, 8) batch_size = 64 units = 64 # embedding dims layers = 2 dataset = make_sparse_data(n_instances, msp_size=instance_size, random_state=2021) batch_dataset = dataset.batch(batch_size) inputs = list(batch_dataset.take(1))[0] ecoder_model = GGCNEncoder(units, layers) embedded_inputs = ecoder_model(inputs) n_heads = 8 model = AttentionDecoder(units, aggregation_graph='mean', n_heads=n_heads) makespan, ll, pi = model(embedded_inputs) pi inputs.adj_matrix[0] tf.math.reduce_all(tf.math.equal(inputs.adj_matrix[1], inputs.adj_matrix[2])) import sys import numpy numpy.set_printoptions(threshold=sys.maxsize) print(inputs.adj_matrix[0].numpy()) print(inputs.adj_matrix[7].numpy()) from typing import NamedTuple from tensorflow import Tensor class MSPState: def __init__(self, inputs): """ """ self.adj_matrix = inputs.adj_matrix self.node_embed = inputs.node_embed batch_size, num_nodes, node_embed_dims = self.node_embed.shape self._first_node = tf.zeros((batch_size,1), dtype=tf.int64) self._last_node = self._first_node self._visited = tf.zeros((batch_size,1,num_nodes), dtype=tf.int64) self._makespan = tf.zeros((batch_size,1)) self.i = tf.zeros(1, dtype=tf.int64) # # Vector with length num_steps self.ids = tf.range(5, delta=1, dtype=tf.int64)[:, None] # # Add steps dimension #self._step_num = tf.zeros(1, dtype=tf.int64) @property def first_node(self): return self._first_node # self._node_embed = None # self._edge_embed = None # self._adj_matrix = None # self._first_job = None # self._last_job = None # @property # def node_embed(self): # return self._node_embed # @node_embed.setter # def node_embed(self, node_embed): # self._node_embed = node_embed # @property # def adj_matrix(self): # return self._adj_matrix # @adj_matrix.setter # def adj_matrix(self, adj_matrix): # self._adj_matrix = adj_matrix # def initialize(self, inputs): # self.adj_matrix = inputs.adj_matrix # return self class MSPSolution: def __init__(self): pass # sequence: Tensor # makespan: Tensor # a: int import torch torch.arange(5, dtype=torch.int64)[:, None], tf.range(5, delta=1, dtype=tf.int64)[:, None] class MSPSparseGraph2(NamedTuple): """ """ adj_matrix: Tensor node_features: Tensor edge_features: Tensor alpha: Tensor @property def num_node(self): return self.adj_matrix.shape[-2] from collections import namedtuple class A(NamedTuple): a: int @property def num(self): return self.a # jane._replace(a=26) class C( NamedTuple( 'SSSSS', A._field_types.items() ), A ): pass class B( NamedTuple( 'SSSB', [ *A._field_types.items(), ('weight', int) ] ), A ): @property def h(self): return self.weight # class B(namedtuple('SSSB', [*A._fields, "weight"]), A): # #[*A._fields, "weight"] # @property # def h(self): # return self.weight # def __getitem__(self, key): # return self[key] #B(A(a=90)._asdict(), weight=90) #B(**A(a=9090)._asdict(), weight=90).num #Ba = 2343, weight=23).num #dir(B) #C(a=90) B(*(34,), weight=34) list(A._field_types.items()) A._field_types def fun(a): print(a) fun(**inputs._asdict()) [*A._field_types, ('v','d')] # for attr, val in inputs._asdict().items(): # print(attr, val) from typing import NamedTuple class AttentionModelFixed(NamedTuple): """ Context for AttentionModel decoder that is fixed during decoding so can be precomputed/cached This class allows for efficient indexing of multiple Tensors at once """ node_embeddings: torch.Tensor context_node_projected: torch.Tensor glimpse_key: torch.Tensor glimpse_val: torch.Tensor logit_key: torch.Tensor def __getitem__(self, key): if tf.is_tensor(key) or isinstance(key, slice): return AttentionModelFixed( node_embeddings=self.node_embeddings[key], context_node_projected=self.context_node_projected[key], glimpse_key=self.glimpse_key[:, key], # dim 0 are the heads glimpse_val=self.glimpse_val[:, key], # dim 0 are the heads logit_key=self.logit_key[key] ) return super(AttentionModelFixed, self).__getitem__(key) """ """ import math import tensorflow as tf import tensorflow_probability as tfp from tensorflow.keras import Model from msp.layers import GGCNLayer from msp.graphs import MSPSparseGraph from msp.solutions import MSPState class AttentionDecoder(Model): def __init__(self, units, *args, activation='relu', aggregation_graph='mean', n_heads=2, # make it 8 mask_inner=True, tanh_clipping=10, decode_type='sampling', extra_logging=False, **kwargs): """ """ super(AttentionDecoder, self).__init__(*args, **kwargs) self.aggregation_graph = aggregation_graph self.n_heads = n_heads self.mask_inner = mask_inner self.tanh_clipping = tanh_clipping self.decode_type = decode_type self.extra_logging = extra_logging embedding_dim = units self.W_placeholder = self.add_weight(shape=(2*embedding_dim,), initializer='random_uniform', #Placeholder should be in range of activations (think) name='W_placeholder', trainable=True) graph_embed_shape = tf.TensorShape((None, units)) self.fixed_context_layer = tf.keras.layers.Dense(units, use_bias=False) self.fixed_context_layer.build(graph_embed_shape) # For each node we compute (glimpse key, glimpse value, logit key) so 3 * embedding_dim project_node_embeddings_shape = tf.TensorShape((None, None, None, units)) self.project_node_embeddings = tf.keras.layers.Dense(3*units, use_bias=False) self.project_node_embeddings.build(project_node_embeddings_shape) # # Embedding of first and last node step_context_dim = 2*units project_step_context_shape = tf.TensorShape((None, None, step_context_dim)) self.project_step_context = tf.keras.layers.Dense(embedding_dim, use_bias=False) self.project_step_context.build(project_step_context_shape) assert embedding_dim % n_heads == 0 # Note n_heads * val_dim == embedding_dim so input to project_out is embedding_dim project_out_shape = tf.TensorShape((None, None, 1, embedding_dim)) self.project_out = tf.keras.layers.Dense(embedding_dim, use_bias=False) self.project_out.build(project_out_shape) # self.context_layer = tf.keras.layers.Dense(units, use_bias=False) # self.mha_layer = None # dynamic router def call(self, inputs, training=False, return_pi=False): """ """ state = MSPState(inputs) node_embedding = inputs.node_embed # AttentionModelFixed(node_embedding, fixed_context, *fixed_attention_node_data) fixed = self._precompute(node_embedding) # for i in range(num_steps): # i == 0 should be machine # AttentionCell(inputs, states) outputs = [] sequences = [] # i = 0 while not state.all_finished(): # B x 1 x V # Get log probabilities of next action log_p, mask = self._get_log_p(fixed, state) selected = self._select_node( tf.squeeze(tf.exp(log_p), axis=-2), tf.squeeze(mask, axis=-2)) # Squeeze out steps dimension state.update(selected) outputs.append(log_p[:, 0, :]) sequences.append(selected) # if i == 1: # break # i+=1 _log_p, pi = tf.stack(outputs, axis=1), tf.stack(sequences, axis=1) if self.extra_logging: self.log_p_batch = _log_p self.log_p_sel_batch = tf.gather(tf.squeeze(_log_p,axis=-2), pi, batch_dims=1) # # Get predicted costs # cost, mask = self.problem.get_costs(nodes, pi) mask = None ################################################### # Need Clarity ############################################################# # loglikelihood ll = self._calc_log_likelihood(_log_p, pi, mask) ## Just for checking return_pi = True if return_pi: return state.makespan, ll, pi return state.makespan, ll def _precompute(self, node_embedding, num_steps=1): graph_embed = self._get_graph_embed(node_embedding) fixed_context = self.fixed_context_layer(graph_embed) # fixed context = (batch_size, 1, embed_dim) to make broadcastable with parallel timesteps fixed_context = tf.expand_dims(fixed_context, axis=-2) glimpse_key_fixed, glimpse_val_fixed, logit_key_fixed = tf.split( self.project_node_embeddings(tf.expand_dims(node_embedding, axis=-3)), num_or_size_splits=3, axis=-1 ) # No need to rearrange key for logit as there is a single head fixed_attention_node_data = ( self._make_heads(glimpse_key_fixed, num_steps), self._make_heads(glimpse_val_fixed, num_steps), logit_key_fixed ) return AttentionModelFixed(node_embedding, fixed_context, *fixed_attention_node_data) def _get_graph_embed(self, node_embedding): """ """ if self.aggregation_graph == "sum": graph_embed = tf.reduce_sum(node_embedding, axis=-2) elif self.aggregation_graph == "max": graph_embed = tf.reduce_max(node_embedding, axis=-2) elif self.aggregation_graph == "mean": graph_embed = tf.reduce_mean(node_embedding, axis=-2) else: # Default: dissable graph embedding graph_embed = tf.reduce_sum(node_embedding, axis=-2) * 0.0 return graph_embed def _make_heads(self, v, num_steps=None): assert num_steps is None or v.shape[1] == 1 or v.shape[1] == num_steps batch_size, _, num_nodes, embed_dims = v.shape num_steps = num_steps if num_steps else 1 head_dims = embed_dims//self.n_heads # M x B x N x V x (H/M) return tf.transpose( tf.broadcast_to( tf.reshape(v, shape=[batch_size, v.shape[1], num_nodes, self.n_heads, head_dims]), shape=[batch_size, num_steps, num_nodes, self.n_heads, head_dims] ), perm=[3, 0, 1, 2, 4] ) def _get_log_p(self, fixed, state, normalize=True): # Compute query = context node embedding # B x 1 x H query = fixed.context_node_projected + \ self.project_step_context(self._get_parallel_step_context(fixed.node_embeddings, state)) # Compute keys and values for the nodes glimpse_K, glimpse_V, logit_K = self._get_attention_node_data(fixed, state) # Compute the mask, for masking next action based on previous actions mask = state.get_mask() graph_mask = state.get_graph_mask() # Compute logits (unnormalized log_p) log_p, glimpse = self._one_to_many_logits(query, glimpse_K, glimpse_V, logit_K, mask, graph_mask) # [B x N x V] # log-softmax activation function so that we get log probabilities over actions if normalize: log_p = tf.nn.log_softmax(log_p/1.0, axis=-1) assert not tf.reduce_any(tf.math.is_nan(log_p)), "Log probabilities over the nodes should be defined" return log_p, mask def _get_parallel_step_context(self, node_embedding, state, from_depot=False): """ Returns the context per step, optionally for multiple steps at once (for efficient evaluation of the model) """ # last_node at time t last_node = state.get_current_node() batch_size, num_steps = last_node.shape if num_steps == 1: # We need to special case if we have only 1 step, may be the first or not if state.i.numpy()[0] == 0: # First and only step, ignore prev_a (this is a placeholder) # B x 1 x 2H return tf.broadcast_to(self.W_placeholder[None, None, :], shape=[batch_size, 1, self.W_placeholder.shape[-1]]) else: return tf.concat( [ tf.gather(node_embedding,state.first_node,batch_dims=1), tf.gather(node_embedding,last_node,batch_dims=1) ], axis=-1 ) # print('$'*20) # node_embedding = torch.from_numpy(node_embedding.numpy()) # f = torch.from_numpy(state.first_node.numpy()) # l = torch.from_numpy(state.last_node.numpy()) # GG = node_embedding\ # .gather( # 1, # torch.cat((f, l), 1)[:, :, None].expand(batch_size, 2, node_embedding.size(-1)) # ).view(batch_size, 1, -1) # print(GG) # print('$'*20) # ############################################## # # PENDING # ############################################## # pass def _get_attention_node_data(self, fixed, state): return fixed.glimpse_key, fixed.glimpse_val, fixed.logit_key def _one_to_many_logits(self, query, glimpse_K, glimpse_V, logit_K, mask, graph_mask=None): batch_size, num_steps, embed_dim = query.shape query_size = key_size = val_size = embed_dim // self.n_heads # M x B x N x 1 x (H/M) # Compute the glimpse, rearrange dimensions to (n_heads, batch_size, num_steps, 1, key_size) glimpse_Q = tf.transpose( tf.reshape( query, # B x 1 x H shape=[batch_size, num_steps, self.n_heads, 1, query_size] ), perm=[2, 0, 1, 3, 4] ) # [M x B x N x 1 x (H/M)] X [M x B x N x (H/M) x V] = [M x B x N x 1 x V] # Batch matrix multiplication to compute compatibilities (n_heads, batch_size, num_steps, graph_size) compatibility = tf.matmul(glimpse_Q, tf.transpose(glimpse_K, [0,1,2,4,3])) / math.sqrt(query_size) mask_temp = tf.cast(tf.broadcast_to(mask[None, :, :, None, :], shape=compatibility.shape), dtype=tf.double) compatibility = tf.cast(compatibility, dtype=tf.double) + (mask_temp * -1e9) graph_mask_temp = tf.cast(tf.broadcast_to(graph_mask[None, :, :, None, :], shape=compatibility.shape), dtype=tf.double) compatibility = tf.cast(compatibility, dtype=tf.double) + (graph_mask_temp * -1e9) compatibility = tf.cast(compatibility, dtype=tf.float32) # compatibility[tf.broadcast_to(mask[None, :, :, None, :], shape=compatibility.shape)] = -1e10 # compatibility[tf.broadcast_to(graph_mask[None, :, :, None, :], shape=compatibility.shape)] = -1e10 # attention weights a(c,j): attention_weights = tf.nn.softmax(compatibility, axis=-1) # [M x B x N x 1 x V] x [M x B x N x V x (H/M)] = [M x B x N x 1 x (H/M)] heads = tf.matmul(attention_weights, glimpse_V) # B x N x 1 x H # Project to get glimpse/updated context node embedding (batch_size, num_steps, embedding_dim) glimpse = self.project_out( tf.reshape( tf.transpose(heads, perm=[1, 2, 3, 0, 4]), shape=[batch_size, num_steps, 1, self.n_heads*val_size] ) ) # B x N x 1 x H # Now projecting the glimpse is not needed since this can be absorbed into project_out # final_Q = self.project_glimpse(glimpse) final_Q = glimpse # [B x N x 1 x H] x [B x 1 x H x V] = [B x N x 1 x V] --> [B x N x V] (Squeeze) # Batch matrix multiplication to compute logits (batch_size, num_steps, graph_size) # logits = 'compatibility' logits = tf.squeeze(tf.matmul(final_Q, tf.transpose(logit_K, perm=[0,1,3,2])), axis=-2) / math.sqrt(final_Q.shape[-1]) logits = logits + ( tf.cast(graph_mask, dtype=tf.float32) * -1e9) logits = tf.math.tanh(logits) * self.tanh_clipping logits = logits + ( tf.cast(mask, dtype=tf.float32) * -1e9) # logits[graph_mask] = -1e10 # logits = torch.tanh(logits) * self.tanh_clipping # logits[mask] = -1e10 return logits, tf.squeeze(glimpse, axis=-2) def _select_node(self, probs, mask): assert tf.reduce_all(probs == probs) == True, "Probs should not contain any nans" if self.decode_type == "greedy": selected = tf.math.argmax(probs, axis=1) assert not tf.reduce_any(tf.cast(tf.gather_nd(mask, tf.expand_dims(selected, axis=-1), batch_dims=1), dtype=tf.bool)), "Decode greedy: infeasible action has maximum probability" elif self.decode_type == "sampling": dist = tfp.distributions.Multinomial(total_count=1, probs=probs) selected = tf.argmax(dist.sample(), axis=1) # Check if sampling went OK while tf.reduce_any(tf.cast(tf.gather_nd(mask, tf.expand_dims(selected, axis=-1), batch_dims=1), dtype=tf.bool)): print('Sampled bad values, resampling!') selected = tf.argmax(dist.sample(), axis=1) else: assert False, "Unknown decode type" return selected def _calc_log_likelihood(self, _log_p, a, mask): # Get log_p corresponding to selected actions batch_size, steps_count = a.shape indices = tf.concat([ tf.expand_dims(tf.broadcast_to(tf.range(steps_count, dtype=tf.int64), shape=a.shape), axis=-1), tf.expand_dims(a, axis=-1)], axis=-1 ) log_p = tf.gather_nd(_log_p, indices, batch_dims=1) # _log_p = torch.from_numpy(_log_p.numpy()) # a = torch.from_numpy(a.numpy()) # AA = _log_p.gather(2, a.unsqueeze(-1)).squeeze(-1) # print(AA) # print(log_p) # print('DONE') # Get log_p corresponding to selected actions # log_p = tf.gather(tf.squeeze(_log_p,axis=-2), a, batch_dims=1) #_log_p.gather(2, a.unsqueeze(-1)).squeeze(-1) # Optional: mask out actions irrelevant to objective so they do not get reinforced if mask is not None: log_p[mask] = 0 # Why?????? # assert (log_p > -1000).data.all(), "Logprobs should not be -inf, check sampling procedure!" # Calculate log_likelihood return tf.reduce_sum(log_p, axis=1) # log_p.sum(1) # import numpy as np # # x = tf.constant([[True, True], [False, False]]) # # assert not tf.reduce_any(x), "asdf" # tf.keras.losses.SparseCategoricalCrossentropy( # from_logits=True, reduction='none')([]).dtype # t = torch.tensor([[[2,3],[5,2]], [[6,1],[0,4]]]) # indices = torch.tensor([[[0, 0]],[[0, 0]]]) # torch.gather(t, 1, indices) # # t = tf.constant([[[2,3],[5,2]], [[6,1],[0,4]]]) # # indices = tf.constant([[0,0,0]]) # # tf.gather_nd(t, indices=indices).numpy() # # #tf.gather_nd() # # t = tf.constant([[[1,0],[1,0]], [[0,1],[1,1]]]) # # t = embedded_inputs.adj_matrix # # indices = tf.constant([[0], [0]]) # # indices = tf.expand_dims(indices, axis=-1) # # ~tf.cast(tf.gather_nd(t, indices=indices, batch_dims=1), tf.bool) # a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) # b = tf.keras.activations.tanh(a) # c = tf.math.tanh(a) # b.numpy(), c.numpy() model = AttentionDecoder(6, aggregation_graph='mean', n_heads=3) makespan, ll, pi = model(embedded_inputs) pi tf.range(4, dtype=tf.int64) indices = [[[1, 0]], [[0, 1]]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] #output = [['c0'], ['b1']] tf.gather a = tf.Tensor( [[[0,1] [1,2]], [[0,0] # [1 1]]], shape=(2, 2, 2), dtype=int64) # tf.Tensor( # [[[-1.0886807e+00 -1.2036482e+00 -1.0126851e+00] # [-9.8199100e+00 -1.0000000e+09 -5.4357959e-05]] # [[-5.4339290e-01 -1.6555539e+00 -1.4773605e+00] # [-1.0000000e+09 -7.7492166e-01 -6.1755723e-01]]], shape=(2, 2, 3), dtype=float32) embeddings.gather( 1, torch.cat((state.first_a, current_node), 1)[:, :, None].expand(batch_size, 2, embeddings.size(-1)) ).view(batch_size, 1, -1) _log_p, pi#tf.expand_dims(pi,axis=-1) _log_p tf.gather(tf.squeeze(_log_p,axis=-2), pi, batch_dims=1) _log_p = torch.Tensor(_log_p.numpy()) pi = torch.from_numpy(tf.cast(pi, dtype=tf.int64).numpy()) log_p = _log_p.gather(2, pi.unsqueeze(-1)).squeeze(-1) log_p.sum(1) log_p # pi.unsqueeze(-1) # tf.cast(pi, dtype=tf.int64) _log_p # seq = [torch.Tensor(i.numpy()) for i in seq] # torch.stack(seq, 1) pi last_node = tf.constant([[0], [1]], dtype=tf.int64) cur_node = selected[:, tf.newaxis] cur_node #cur_node tf.gather_nd( tf.gather_nd(embedded_inputs.edge_features, tf.concat([last_node, cur_node], axis=1), batch_dims=1), tf.reshape(tf.range(2), shape=(2,1)), # feature_indexfor processing time batch_dims=0 ) A = tf.gather_nd(embedded_inputs.edge_features, tf.concat([last_node, cur_node], axis=1), batch_dims=1)[:,0:1] A tf.reshape(tf.range(2), shape=(2,1)) embedded_inputs.node_features[:,] cur_node[:,tf.newaxis,:] #embedded_inputs.node_features[:, ] tf.gather_nd(embedded_inputs.edge_features, tf.concat([last_node, cur_node], axis=1), batch_dims=1)[:,0:1] + \ tf.gather_nd(embedded_inputs.node_features, cur_node, batch_dims=1)[:,0:1] cur_node tf.rank(tf.ones(30,10)) t = tf.constant([[[1, 1, 1, 4], [2, 2, 2, 4]], [[3, 3, 3, 4], [4, 4, 4, 4]]]) tf.rank(t) _visited = tf.zeros((batch_size,1,3), dtype=tf.uint8) _visited cur_node #[:,:,None] #, tf.ones([2,1,1]) tf.concat([tf.reshape(tf.range(2, dtype=tf.int64),cur_node.shape), cur_node], axis=1) _visited.dtype batch_size, _, _ = _visited.shape tf.tensor_scatter_nd_update( tf.squeeze(_visited, axis=-2), tf.concat([tf.reshape(tf.range(batch_size, dtype=tf.int64),cur_node.shape), cur_node], axis=1), tf.ones((batch_size,), dtype=_visited.dtype) )[:,tf.newaxis,:] #_visited, cur_node[:,:,None], tf.ones([2,1,1], dtype=tf.uint8)) cur_node = selected[:, tf.newaxis] cur_node #cur_node tf.concat([cur_node, cur_node], axis=1) tf.gather_nd( tf.gather_nd(embedded_inputs.edge_features, tf.concat([cur_node, cur_node], axis=1), batch_dims=1), tf.zeros((2,1), dtype=tf.int32) ) tf.gather_nd(embedded_inputs.edge_features, tf.concat([cur_node, cur_node], axis=1), batch_dims=1) tf.zeros((2,), dtype=tf.int32) tf.range(2) embedded_inputs.edge_features probs_ = tf.squeeze(tf.exp(log_p), axis=-2) tf.squeeze(mask, axis=-2) embedded_inputs.node_features probs = torch.Tensor(log_p.numpy()).exp()[:, 0, :] mask_ = torch.Tensor(mask.numpy())[:, 0, :] probs, probs.multinomial(1) #.squeeze(1) # _, selected = probs.max(1) # assert not mask_.gather(1, selected.unsqueeze( # -1)).data.any(), "Decode greedy: infeasible action has maximum probability" # mask_.gather(1, selected.unsqueeze(-1)) #.data.any() probs_ probs.multinomial(1) # p = [.2, .3, .5] # dist = tfp.distributions.Multinomial(total_count=1, probs=probs_) p = [[.1, .2, .7], [.3, .3, .4]] # Shape [2, 3] dist = tfp.distributions.Multinomial(total_count=1, probs=probs_) selected = tf.argmax(dist.sample(), axis=1) selected = tf.math.argmax(tf.squeeze(tf.exp(log_p), axis=-2), axis=1) assert not tf.reduce_any(tf.cast(tf.gather_nd(mask_, tf.expand_dims(selected, axis=-1), batch_dims=1), dtype=tf.bool)), "Decode greedy: infeasible action has maximum probability" tf.expand_dims(selected, axis=-1), mask_, probs_ tf.broadcast_to(mask[None, :, None, :, :], shape=compatibility.shape) compatibility compatibility[graph_mask[None, :, :, None, :].expand_as(compatibility)] = -1e10 def _make_heads(v, num_steps=None): assert num_steps is None or v.size(1) == 1 or v.size(1) == num_steps n_heads = 2 return ( v.contiguous().view(v.size(0), v.size(1), v.size(2), n_heads, -1) .expand(v.size(0), v.size(1) if num_steps is None else num_steps, v.size(2), n_heads, -1) .permute(3, 0, 1, 2, 4) # (n_heads, batch_size, num_steps, graph_size, head_dim) ) from torch import nn W_placeholder = nn.Parameter(torch.Tensor(2 * 6)) W_placeholder[None, None, :].expand(2, 1, W_placeholder.size(-1)) tf.ones((3,4)).dtype _make_heads2(A, num_steps=4) _make_heads2(A, num_steps=2) A.shape tf.broadcast_to(A, tf.TensorShape([-1, 4, None, None])) tf.split( tf.matmul(tf.ones((5,3))[None,:,:], tf.ones((3,3*3))), 3, axis=-1 ) tf.matmul(tf.ones((5,3))[None,:,:], tf.ones((3,3*3))) import torch embeddings = torch.Tensor(embedded_inputs.node_features.numpy()) torch.cat((state.first_a, current_node), 1)[:, :, None] embedded_inputs.node_features import torch from torch import nn W_placeholder = nn.Parameter(torch.Tensor(2 * 5)) W_placeholder[None, None, :].expand(batch_size, 1, W_placeholder.size(-1)).shape tf.constant(W_placeholder[None, None, :].detach().numpy()).shape[-1] tf.broadcast_to? W_placeholder[None, None, :].shape self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer='random_normal', trainable=True) tf.reduce_mean(embedded_inputs.node_features, axis=-2) import torch torch.Tensor(embedded_inputs.node_features.numpy()).max(1)[0] embedded_inputs.node_features.numpy() """ """ import tensorflow as tf from tensorflow.keras import Model from msp.layers import GGCNLayer from msp.graphs import MSPSparseGraph from msp.solutions import MSPState class AttentionDecoder(Model): def __init__(self, units, *args, activation='relu', aggregation_graph='mean', n_heads=8, **kwargs): """ """ super(AttentionDecoder, self).__init__(*args, **kwargs) self.aggregation_graph = aggregation_graph self.n_heads = n_heads embedding_dim = units self.W_placeholder = self.add_weight(shape=(2*embedding_dim,), initializer='random_uniform', #Placeholder should be in range of activations (think) trainable=True) graph_embed_shape = tf.TensorShape((None, units)) self.fixed_context_layer = tf.keras.layers.Dense(units, use_bias=False) self.fixed_context_layer.build(graph_embed_shape) # For each node we compute (glimpse key, glimpse value, logit key) so 3 * embedding_dim project_node_embeddings_shape = tf.TensorShape((None, None, None, units)) self.project_node_embeddings = tf.keras.layers.Dense(3*units, use_bias=False) self.project_node_embeddings.build(project_node_embeddings_shape) # # Embedding of first and last node step_context_dim = 2*units project_step_context_shape = tf.TensorShape((None, None, step_context_dim)) self.project_step_context = tf.keras.layers.Dense(embedding_dim, use_bias=False) self.project_step_context.build(project_step_context_shape) #nn.Linear(step_context_dim, embedding_dim, bias=False) # self.context_layer = tf.keras.layers.Dense(units, use_bias=False) # self.mha_layer = None # dynamic router # self.initial_layer_1 = tf.keras.layers.Dense(units) # self.initial_layer_2 = tf.keras.layers.Dense(units) # self.ggcn_layers = [GGCNLayer(units, activation=activation) # for _ in range(layers)] def call(self, inputs, training=False): """ """ state = MSPState(inputs) node_embedding = inputs.node_embed # AttentionModelFixed(node_embedding, fixed_context, *fixed_attention_node_data) fixed = self._precompute(node_embedding) return fixed while not state.all_finished(): log_p, mask = self._get_log_p(fixed, state) node_embed = inputs.node_features return self._get_parallel_step_context(node_embed) def _precompute(self, node_embedding, num_steps=1): graph_embed = self._get_graph_embed(node_embedding) fixed_context = self.fixed_context_layer(graph_embed) # fixed context = (batch_size, 1, embed_dim) to make broadcastable with parallel timesteps fixed_context = tf.expand_dims(fixed_context, axis=-2) glimpse_key_fixed, glimpse_val_fixed, logit_key_fixed = tf.split( self.project_node_embeddings(tf.expand_dims(node_embedding, axis=-3)), num_or_size_splits=3, axis=-1 ) return glimpse_key_fixed # No need to rearrange key for logit as there is a single head fixed_attention_node_data = ( self._make_heads(glimpse_key_fixed, num_steps), self._make_heads(glimpse_val_fixed, num_steps), logit_key_fixed ) return AttentionModelFixed(node_embedding, fixed_context, *fixed_attention_node_data) def _get_graph_embed(self, node_embedding): """ """ if self.aggregation_graph == "sum": graph_embed = tf.reduce_sum(node_embedding, axis=-2) elif self.aggregation_graph == "max": graph_embed = tf.reduce_max(node_embedding, axis=-2) elif self.aggregation_graph == "mean": graph_embed = tf.reduce_mean(node_embedding, axis=-2) else: # Default: dissable graph embedding graph_embed = tf.reduce_sum(node_embedding, axis=-2) * 0.0 return graph_embed def _make_heads(self, v, num_steps=None): assert num_steps is None or v.shape[1] == 1 or v.shape[1] == num_steps batch_size, _, num_nodes, embed_dims = v.shape num_steps = num_steps if num_steps else 1 # M x B x N x V x H return tf.broadcast_to( tf.broadcast_to(v, shape=[batch_size, num_steps, num_nodes, embed_dims])[None,:,:,:,:], shape=[self.n_heads, batch_size, num_steps, num_nodes, embed_dims] ) def _get_log_p(self, fixed, state, normalize=True): # Compute query = context node embedding # B x 1 x H query = fixed.context_node_projected + \ self.project_step_context(self._get_parallel_step_context(fixed.node_embeddings, state)) # Compute keys and values for the nodes glimpse_K, glimpse_V, logit_K = self._get_attention_node_data(fixed, state) graph_mask = None if self.mask_graph: # Compute the graph mask, for masking next action based on graph structure graph_mask = state.get_graph_mask() # Pending........................................... # Compute logits (unnormalized log_p) log_p, glimpse = self._one_to_many_logits(query, glimpse_K, glimpse_V, logit_K, mask, graph_mask) def _get_parallel_step_context(self, node_embedding, state, from_depot=False): """ Returns the context per step, optionally for multiple steps at once (for efficient evaluation of the model) """ current_node = state.get_current_node() batch_size, num_steps = current_node.shape if num_steps == 1: # We need to special case if we have only 1 step, may be the first or not if self.i.numpy()[0] == 0: # First and only step, ignore prev_a (this is a placeholder) # B x 1 x 2H return tf.broadcast_to(self.W_placeholder[None, None, :], shape=[batch_size, 1, self.W_placeholder.shape[-1]]) # else: # return embeddings.gather( # 1, # torch.cat((state.first_a, current_node), 1)[:, :, None].expand(batch_size, 2, embeddings.size(-1)) # ).view(batch_size, 1, -1) def _get_attention_node_data(self, fixed, state): return fixed.glimpse_key, fixed.glimpse_val, fixed.logit_key def _one_to_many_logits(self, query, glimpse_K, glimpse_V, logit_K, mask, graph_mask=None): pass tf.boolean_mask MSPSparseGraph._fields dataset = make_sparse_data(4, msp_size=(1,2), random_state=2021) graph = list(dataset.take(1))[0] graph indices= tf.cast(tf.transpose( tf.concat([ edge_index, tf.scatter_nd( tf.constant([[1],[0]]), edge_index, edge_index.shape ) ], axis=-1) ), tf.int64) indices adj_matrix = tf.sparse.SparseTensor( indices= indices, values = tf.ones([2*edge_index.shape[-1]]), dense_shape = [3,3] ) adj_matrix tf.sparse.to_dense(tf.sparse.reorder(adj_matrix)) reorder tf.ones([edge_index.shape[-1]]) E = tf.sparse.SparseTensor(indices=[[0, 0], [1, 2], [2, 0]], values=[1, 2], dense_shape=[3, 4]) tf.sparse.to_dense() tf.ones((2,3)) class GGCNLayer(Layer): # @validate_hyperparams def __init__(self, units, *args, activation='relu', use_bias=True, normalization='batch', aggregation='mean', **kwargs): """ """ super(GGCNLayer, self).__init__(*args, **kwargs) self.units = units self.activation = tf.keras.activations.get(activation) self.use_bias = use_bias self.normalization= normalization self.aggregation = aggregation def build(self, input_shape): """Create the state of the layer (weights)""" print('Build') node_features_shape = input_shape.node_features edge_featues_shape = input_shape.edge_features embedded_shape = tf.TensorShape((None, self.units)) # _initial_projection_layer (think on it) with tf.name_scope('node'): with tf.name_scope('U'): self.U = tf.keras.layers.Dense(self.units, use_bias=self.use_bias) self.U.build(node_features_shape) with tf.name_scope('V'): self.V = tf.keras.layers.Dense(self.units, use_bias=self.use_bias) self.V.build(node_features_shape) with tf.name_scope('norm'): self.norm_h = { "batch": tf.keras.layers.BatchNormalization(), "layer": tf.keras.layers.LayerNormalization() }.get(self.normalization, None) if self.norm_h: self.norm_h.build(embedded_shape) with tf.name_scope('edge'): with tf.name_scope('A'): self.A = tf.keras.layers.Dense(self.units, use_bias=self.use_bias) self.A.build(tf.TensorShape((None, node_features_shape[-1]))) with tf.name_scope('B'): self.B = tf.keras.layers.Dense(self.units, use_bias=self.use_bias) self.B.build(node_features_shape) with tf.name_scope('C'): self.C = tf.keras.layers.Dense(self.units, use_bias=self.use_bias) self.C.build(edge_featues_shape) with tf.name_scope('norm'): self.norm_e = { 'batch': tf.keras.layers.BatchNormalization(), 'layer': tf.keras.layers.LayerNormalization(axis=-2) }.get(self.normalization, None) if self.norm_e: self.norm_e.build(embedded_shape) super().build(input_shape) def call(self, inputs): """ """ print('call') adj_matrix = inputs.adj_matrix h = inputs.node_features e = inputs.edge_features # Edges Featuers Ah = self.A(h) Bh = self.B(h) Ce = self.C(e) e = self._update_edges(e, [Ah, Bh, Ce]) edge_gates = tf.sigmoid(e) # Nodes Features Uh = self.U(h) Vh = self.V(h) h = self._update_nodes( h, [Uh, self._aggregate(Vh, edge_gates, adj_matrix)] ) outputs = MSPSparseGraph(adj_matrix, h, e, inputs.alpha) return inputs def _update_edges(self, e, transformations:list): """Update edges features""" Ah, Bh, Ce = transformations e_new = tf.expand_dims(Ah, axis=1) + tf.expand_dims(Bh, axis=2) + Ce # Normalization batch_size, num_nodes, num_nodes, hidden_dim = e_new.shape if self.norm_e: e_new = tf.reshape( self.norm_e( tf.reshape(e_new, [batch_size*num_nodes*num_nodes, hidden_dim]) ), e_new.shape ) # Activation e_new = self.activation(e_new) # Skip/residual Connection e_new = e + e_new return e_new def _update_nodes(self, h, transformations:list): """ """ Uh, aggregated_messages = transformations h_new = tf.math.add_n([Uh, aggregated_messages]) # Normalization batch_size, num_nodes, hidden_dim = h_new.shape if self.norm_h: h_new = tf.reshape( self.norm_h( tf.reshape(h_new, [batch_size*num_nodes, hidden_dim]) ), h_new.shape ) # Activation h_new = self.activation(h_new) # Skip/residual Connection h_new = h + h_new return h_new def _aggregate(self, Vh, edge_gates, adj_matrix): """ """ # Reshape as edge_gates Vh = tf.broadcast_to( tf.expand_dims(Vh, axis=1), edge_gates.shape ) # Gating mechanism Vh = edge_gates * Vh # Enforce graph structure # mask = tf.broadcast_to(tf.expand_dims(adj_matrix,axis=-1), Vh.shape) # Vh[~mask] = 0 # message aggregation if self.aggregation == 'mean': total_messages = tf.cast( tf.expand_dims( tf.math.reduce_sum(adj_matrix, axis=-1), axis=-1 ), Vh.dtype ) return tf.math.reduce_sum(Vh, axis=2) / total_messages elif self.aggregation == 'sum': return tf.math.reduce_sum(Vh, axis=2) # B, V, H = 1, 3, 2 h = tf.ones((B, V, H)) dataset = make_sparse_data(4, msp_size=(1,2), random_state=2020) graphs = list(dataset.batch(2)) VVh = list(graphs)[0].edge_features A = list(graphs)[0].adj_matrix VVh.shape, A.shape # mask = tf.cast(tf.broadcast_to( # tf.expand_dims(A, axis=-1), # VVh.shape # ), tf.bool) # VVh[~mask] ggcn.variables units = graphs[0].edge_features.shape[-1] ggcn = GGCNLayer(units=units, use_bias=True, name='GGCN_Layer') output = ggcn(graphs[0]) output tf.cast( tf.expand_dims( tf.math.reduce_sum(list(graphs)[0].adj_matrix, axis=-1), axis=-1 ), Vh.dtype ) tf.expand_dims( tf.math.reduce_sum(list(graphs)[0].adj_matrix, axis=-1), axis=-1).dtype tf.math.reduce_max(graphs[0].edge_features, axis=-2 )[0] list(graphs)[0].adj_matrix # ggcn = GGCNLayer(units=units, use_bias=True, name='GGCN_Layer') # output = ggcn(graphs[0]) # output graphs = list(make_data(1, msp_size=(1,2), random_state=2021).take(1))[0] num_edges = 3 A = tf.sparse.SparseTensor( indices= tf.cast(tf.transpose(graphs['edge_index']), tf.int64), values = tf.ones([num_edges]), dense_shape = [3,3] ) tf.sparse.to_dense(A) tf.cast(tf.transpose(graphs['edge_index']), tf.int64) # ggcn.variables tf.cast(tf.transpose(graphs['edge_index']), tf.int64) edge_index = tf.cast(tf.transpose( tf.concat([ graphs['edge_index'], tf.scatter_nd( tf.constant([[1],[0]]), graphs['edge_index'], graphs['edge_index'].shape ) ], axis=-1) ), tf.int32) edge_index model = tf.keras.Sequential([ GGCNLayer(units=units, use_bias=True, name='GGCN_Layer') ]) model.compile(optimizer='sgd', loss='mse') model.fit(dataset) model.weights ```
github_jupyter
``` # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir( os.path.join('..', 'notebook_format') ) from formats import load_style load_style() os.chdir(path) import numpy as np import pandas as pd import matplotlib.pyplot as plt # 1. magic for inline plot # 2. magic to print version # 3. magic so that the notebook will reload external python modules %matplotlib inline %load_ext watermark %load_ext autoreload %autoreload 2 from sklearn import datasets from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression %watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn ``` # Softmax Regression **Softmax Regression** is a generalization of logistic regression that we can use for multi-class classification. If we want to assign probabilities to an object being one of several different things, softmax is the thing to do. Even later on, when we start training neural network models, the final step will be a layer of softmax. A softmax regression has two steps: first we add up the evidence of our input being in certain classes, and then we convert that evidence into probabilities. In **Softmax Regression**, we replace the sigmoid logistic function by the so-called *softmax* function $\phi(\cdot)$. $$P(y=j \mid z^{(i)}) = \phi(z^{(i)}) = \frac{e^{z^{(i)}}}{\sum_{j=1}^{k} e^{z_{j}^{(i)}}}$$ where we define the net input *z* as $$z = w_1x_1 + ... + w_mx_m + b= \sum_{l=1}^{m} w_l x_l + b= \mathbf{w}^T\mathbf{x} + b$$ (**w** is the weight vector, $\mathbf{x}$ is the feature vector of 1 training sample. Each $w$ corresponds to a feature $x$ and there're $m$ of them in total. $b$ is the bias unit. $k$ denotes the total number of classes.) Now, this softmax function computes the probability that the $i_{th}$ training sample $\mathbf{x}^{(i)}$ belongs to class $l$ given the weight and net input $z^{(i)}$. So given the obtained weight $w$, we're basically compute the probability, $p(y = j \mid \mathbf{x^{(i)}; w}_j)$, the probability of the training sample belonging to class $j$ for each class label in $j = 1, \ldots, k$. Note the normalization term in the denominator which causes these class probabilities to sum up to one. We can picture our softmax regression as looking something like the following, although with a lot more $x_s$. For each output, we compute a weighted sum of the $x_s$, add a bias, and then apply softmax. <img src='images/softmax1.png' width="60%"> If we write that out as equations, we get: <img src='images/softmax2.png' width="60%"> We can "vectorize" this procedure, turning it into a matrix multiplication and vector addition. This is helpful for computational efficiency. (It's also a useful way to think.) <img src='images/softmax3.png' width="60%"> To illustrate the concept of softmax, let us walk through a concrete example. Suppose we have a training set consisting of 4 samples from 3 different classes (0, 1, and 2) - $x_0 \rightarrow \text{class }0$ - $x_1 \rightarrow \text{class }1$ - $x_2 \rightarrow \text{class }2$ - $x_3 \rightarrow \text{class }2$ First, we apply one-hot encoding to encode the class labels into a format that we can more easily work with. ``` y = np.array([0, 1, 2, 2]) def one_hot_encode(y): n_class = np.unique(y).shape[0] y_encode = np.zeros((y.shape[0], n_class)) for idx, val in enumerate(y): y_encode[idx, val] = 1.0 return y_encode y_encode = one_hot_encode(y) y_encode ``` A sample that belongs to class 0 (the first row) has a 1 in the first cell, a sample that belongs to class 1 has a 1 in the second cell of its row, and so forth. Next, let us define the feature matrix of our 4 training samples. Here, we assume that our dataset consists of 2 features; thus, we create a 4x2 dimensional matrix of our samples and features. Similarly, we create a 2x3 dimensional weight matrix (one row per feature and one column for each class). ``` X = np.array([[0.1, 0.5], [1.1, 2.3], [-1.1, -2.3], [-1.5, -2.5]]) W = np.array([[0.1, 0.2, 0.3], [0.1, 0.2, 0.3]]) bias = np.array([0.01, 0.1, 0.1]) print('Inputs X:\n', X) print('\nWeights W:\n', W) print('\nbias:\n', bias) ``` To compute the net input, we multiply the 4x2 matrix feature matrix `X` with the 2x3 (n_features x n_classes) weight matrix `W`, which yields a 4x3 output matrix (n_samples x n_classes) to which we then add the bias unit: $$\mathbf{Z} = \mathbf{X}\mathbf{W} + \mathbf{b}$$ ``` def net_input(X, W, b): return X.dot(W) + b net_in = net_input(X, W, bias) print('net input:\n', net_in) ``` Now, it's time to compute the softmax activation that we discussed earlier: $$P(y=j \mid z^{(i)}) = \phi_{softmax}(z^{(i)}) = \frac{e^{z^{(i)}}}{\sum_{j=1}^{k} e^{z_{j}^{(i)}}}$$ ``` def softmax(z): return np.exp(z) / np.sum(np.exp(z), axis = 1, keepdims = True) smax = softmax(net_in) print('softmax:\n', smax) ``` As we can see, the values for each sample (row) nicely sum up to 1 now. E.g., we can say that the first sample `[ 0.29450637 0.34216758 0.36332605]` has a 29.45% probability to belong to class 0. Now, in order to turn these probabilities back into class labels, we could simply take the argmax-index position of each row: [[ 0.29450637 0.34216758 **0.36332605**] -> 2 [ 0.21290077 0.32728332 **0.45981591**] -> 2 [ **0.42860913** 0.33380113 0.23758974] -> 0 [ **0.44941979** 0.32962558 0.22095463]] -> 0 ``` def to_classlabel(z): return z.argmax(axis = 1) print('predicted class labels: ', to_classlabel(smax)) ``` As we can see, our predictions are terribly wrong, since the correct class labels are `[0, 1, 2, 2]`. Now, in order to train our model we need to measuring how inefficient our predictions are for describing the truth and then optimize on it. To do so we first need to define a loss/cost function $J(\cdot)$ that we want to minimize. One very common function is "cross-entropy": $$J(\mathbf{W}; \mathbf{b}) = \frac{1}{n} \sum_{i=1}^{n} H( T^{(i)}, O^{(i)} )$$ which is the average of all cross-entropies $H$ over our $n$ training samples. The cross-entropy function is defined as: $$H( T^{(i)}, O^{(i)} ) = -\sum_k T^{(i)} \cdot log(O^{(i)})$$ Where: - $T$ stands for "target" (i.e., the *true* class labels) - $O$ stands for output -- the computed *probability* via softmax; **not** the predicted class label. - $\sum_k$ denotes adding up the difference between the target and the output for all classes. ``` def cross_entropy_cost(y_target, output): return np.mean(-np.sum(y_target * np.log(output), axis = 1)) cost = cross_entropy_cost(y_target = y_encode, output = smax) print('Cross Entropy Cost:', cost) ``` ## Gradient Descent Our objective in training a neural network is to find a set of weights that gives us the lowest error when we run it against our training data. There're many ways to find these weights and simplest one is so called **gradient descent**. It does this by giving us directions (using derivatives) on how to "shift" our weights to an optimum. It tells us whether we should increase or decrease the value of a specific weight in order to lower the error function. Let's imagine we have a function $f(x) = x^4 - 3x^3 + 2$ and we want to find the minimum of this function using gradient descent. Here's a graph of that function: ``` from sympy.plotting import plot from sympy import symbols, init_printing # change default figure and font size plt.rcParams['figure.figsize'] = 6, 4 plt.rcParams['font.size'] = 12 # plotting f(x) = x^4 - 3x^3 + 2, showing -2 < x <4 init_printing() x = symbols('x') fx = x ** 4 - 3 * x ** 3 + 2 p1 = plot(fx, (x, -2, 4), ylim = (-10, 50)) ``` As you can see, there appears to be a minimum around ~2.3 or so. Gradient descent answers this question: If we were to start with a random value of x, which direction should we go if we want to get to the lowest point on this function? Let's imagine we pick a random x value, say <b>x = 4</b>, which would be somewhere way up on the right side of the graph. We obviously need to start going to the left if we want to get to the bottom. This is obvious when the function is an easily visualizable 2d plot, but when dealing with functions of multiple variables, we need to rely on the raw mathematics. Calculus tells us that the derivative of a function at a particular point is the rate of change/slope of the tangent to that part of the function. So let's use derivatives to help us get to the bottom of this function. The derivative of $f(x) = x^4 - 3x^3 + 2$ is $f'(x) = 4x^3 - 9x^2$. So if we plug in our random point from above (x=4) into the first derivative of $f(x)$ we get $f'(4) = 4(4)^3 - 9(4)^2 = 112$. So how does 112 tell us where to go? Well, first of all, it's positive. If we were to compute $f'(-1)$ we get a negative number (-13). So it looks like we can say that whenever the $f'(x)$ for a particular $x$ is positive, we should move to the left (decrease x) and whenever it's negative, we should move to the right (increase x). We'll now formalize this: When we start with a random x and compute it's deriative $f'(x)$, our <b>new x</b> should then be proportional to $x - f'(x)$. The word proportional is there because we wish to control <em>to what degree</em> we move at each step, for example when we compute $f'(4)=112$, do we really want our new $x$ to be $x - 112 = -108$? No, if we jump all the way to -108, we're even farther from the minimum than we were before. Instead, we want to take relatively <em>small</em> steps toward the minimum. Let's say that for any random $x$, we want to take a step (change $x$ a little bit) such that our <b>new $x$</b> $ = x - \alpha*f'(x)$. We'll call $\alpha$ (alpha) our <em>learning rate or step size</em> because it determines how big of a step we take. $\alpha$ is something we will just have to play around with to find a good value. Some functions might require bigger steps, others smaller steps. Suppose we've set our $\alpha$ to be 0.001. This means, if we randomly started at $f'(4)=112$ then our new $x$ will be $ = 4 - (0.001 * 112) = 3.888$. So we moved to the left a little bit, toward the optimum. Let's do it again. $x_{new} = x - \alpha*f'(3.888) = 3.888 - (0.001 * 99.0436) = 3.79$. Nice, we're indeed moving to the left, closer to the minimum of $f(x)$, little by little. And we'll keep on doing this until we've reached convergence. By convergence, we mean that if the absolute value of the difference between the updated $x$ and the old $x$ is smaller than some randomly small number that we set, denoted as $\epsilon$ (epsilon). ``` x_old = 0 x_new = 4 # The algorithm starts at x = 4 alpha = 0.01 # step size epsilon = 0.00001 def f_derivative(x): return 4 * x ** 3 - 9 * x ** 2 while abs(x_new - x_old) > epsilon: x_old = x_new x_new = x_old - alpha * f_derivative(x_old) print("Local minimum occurs at", x_new) ``` The script above says that if the absolute difference of $x$ between the two iterations is not changing by more than 0.00001, then we're probably at the bottom of the "bowl" because our slope is approaching 0, and therefore we should stop and call it a day. Now, if you remember some calculus and algebra, you could have solved for this minimum analytically, and you should get 2.25. Very close to what our gradient descent algorithm above found. ## More Gradient Descent... As you might imagine, when we use gradient descent for a neural network, things get a lot more complicated. Not because gradient descent gets more complicated, it still ends up just being a matter of taking small steps downhill, it's that we need that pesky derivative in order to use gradient descent, and the derivative of a neural network cost function (with respect to its weights) is pretty intense. It's not a matter of just analytically solving $f(x)=x^2, f'(x)=2x$ , because the output of a neural net has many nested or "inner" functions. Also unlike our toy math problem above, a neural network may have many weights. We need to find the optimal value for each individual weight to lower the cost for our entire neural net output. This requires taking the partial derivative of the cost/error function with respect to a single weight, and then running gradient descent for each individual weight. Thus, for any individual weight $W_j$, we'll compute the following: $$ W_j^{(t + 1)} = W_j^{(t)} - \alpha * \frac{\partial L}{\partial W_j}$$ Where: - $L$ denotes the loss function that we've defined. - $W_j^{(t)}$ denotes the weight of the $j_{th}$ feature at iteration $t$. And as before, we do this iteratively for each weight, many times, until the whole network's cost function is minimized. In order to learn the weight for our softmax model via gradient descent, we then need to compute the gradient of our cost function for each class $j \in \{0, 1, ..., k\}$. $$\nabla \mathbf{w}_j \, J(\mathbf{W}; \mathbf{b})$$ We won't be going through the tedious details here, but this cost's gradient turns out to be simply: $$\nabla \mathbf{w}_j \, J(\mathbf{W}; \mathbf{b}) = \frac{1}{n} \sum^{n}_{i=0} \big[\mathbf{x}^{(i)}_j\ \big( O^{(i)} - T^{(i)} \big) \big]$$ We can then use the cost derivate to update the weights in opposite direction of the cost gradient with learning rate $\eta$: $$\mathbf{w}_j := \mathbf{w}_j - \eta \nabla \mathbf{w}_j \, J(\mathbf{W}; \mathbf{b})$$ (note that $\mathbf{w}_j$ is the weight vector for the class $y=j$), and we update the bias units using: $$ \mathbf{b}_j := \mathbf{b}_j - \eta \bigg[ \frac{1}{n} \sum^{n}_{i=0} \big( O^{(i)} - T^{(i)} \big) \bigg] $$ As a penalty against complexity, an approach to reduce the variance of our model and decrease the degree of overfitting by adding additional bias, we can further add a regularization term such as the L2 term with the regularization parameter $\lambda$: $$\frac{\lambda}{2} ||\mathbf{w}||_{2}^{2}$$ where $||\mathbf{w}||_{2}^{2}$ simply means adding up the squared weights across all the features and classes. $$||\mathbf{w}||_{2}^{2} = \sum^{m}_{l=0} \sum^{k}_{j=0} w_{l, j}^2$$ so that our cost function becomes $$ J(\mathbf{W}; \mathbf{b}) = \frac{1}{n} \sum_{i=1}^{n} H( T^{(i)}, O^{(i)} ) + \frac{\lambda}{2} ||\mathbf{w}||_{2}^{2} $$ and we define the "regularized" weight update as $$ \mathbf{w}_j := \mathbf{w}_j - \eta \big[\nabla \mathbf{w}_j \, J(\mathbf{W}) + \lambda \mathbf{w}_j \big] $$ Note that we don't regularize the bias term, thus the update function for it stays the same. ## Softmax Regression Code Bringing the concepts together, we could come up with an implementation as follows: Note that for the weight and bias parameter, we'll have initialize a value for it. Here we'll simply draw the weights from a normal distribution and set the bias as zero. The code can be obtained [here](https://github.com/ethen8181/machine-learning/blob/master/deep_learning/softmax.py). ``` # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target # standardize the input features scaler = StandardScaler() X_std = scaler.fit_transform(X) from softmax import SoftmaxRegression # train the softmax using batch gradient descent, # eta: learning rate, epochs : number of iterations, minibatches, number of # training data to use for training at each iteration softmax_reg = SoftmaxRegression(eta = 0.1, epochs = 10, minibatches = y.shape[0]) softmax_reg.fit(X_std, y) # print the training accuracy y_pred = softmax_reg.predict(X_std) accuracy = np.sum(y_pred == y) / y.shape[0] print('accuracy: ', accuracy) # use a library to ensure comparable results log_reg = LogisticRegression() log_reg.fit(X_std, y) y_pred = log_reg.predict(X_std) print('accuracy library: ', accuracy_score(y_true = y, y_pred = y_pred)) ``` # Reference - [Blog: Softmax Regression](http://nbviewer.jupyter.org/github/rasbt/python-machine-learning-book/blob/master/code/bonus/softmax-regression.ipynb) - [Blog: Gradient Descent with Backpropagation](http://outlace.com/Beginner-Tutorial-Backpropagation/) - [TensorFlow Documentation: MNIST For ML Beginners](https://www.tensorflow.org/get_started/mnist/beginners)
github_jupyter
``` import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms import time import matplotlib.pyplot as plt import numpy as np dataset = datasets.ImageFolder( 'dataset', transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) ) train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - 65, 65]) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=8, shuffle=True, num_workers=0, ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=8, shuffle=True, num_workers=0, ) model = models.alexnet(pretrained=True) model.classifier[6] = torch.nn.Linear(model.classifier[6].in_features, 2) device = torch.device('cuda') model = model.to(device) import datetime today = datetime.date.today() strToday = str(today.year) + '_' + str(today.month) + '_' + str(today.day) RESNET_MODEL = 'Botline_CA_model_alexnet_' + strToday + '.pth' TRT_MODEL = 'Botline_CA_model_alexnet_trt_' + strToday + '.pth' NUM_EPOCHS = 50 best_accuracy = 0.0 optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) accuracyList = list() timeList = list() startTime = time.time() for epoch in range(NUM_EPOCHS): t0 = time.time() for images, labels in iter(train_loader): images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() test_error_count = 0.0 for images, labels in iter(test_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) elapsedTime = time.time() - t0 test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) accuracyList.append(test_accuracy) timeList.append(elapsedTime) print('[%2d] Accuracy: %f\tTime : %.2f sec' % (epoch, test_accuracy, elapsedTime)) if test_accuracy > best_accuracy: torch.save(model.state_dict(), RESNET_MODEL) best_accuracy = test_accuracy endTime = time.time() print('Time: {0:.2f}'.format(endTime - startTime)) plt.figure(figsize=(12, 3)) accX = range(len(accuracyList)) plt.subplot(121) plt.plot(accX, accuracyList) plt.ylabel('Accuracy') timeX = range(len(timeList)) plt.subplot(122) plt.plot(timeX, timeList) plt.ylabel('Time') plt.show() ```
github_jupyter
## Imports ``` %matplotlib inline import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression, Lasso, Ridge ``` ## Generate Data ``` samples = 500 np.random.seed(10) ## seed for reproducibility f1 = np.random.uniform(low=0, high=10, size=samples) ## garbage feature f2 = np.random.rand(samples) f3 = np.random.binomial(n=1, p=0.5, size=samples) f4 = None f5 = np.random.normal(1, 2.5, samples) d = {'f1':f1, 'f2':f2, 'f3':f3, 'f4':f4, 'f5':f5} df = pd.DataFrame(d) df['target'] = None df.head() # Set target values w/noise for i, _ in df.iterrows(): df.loc[i, 'target'] = df.loc[i, 'f2'] * df.loc[i, 'f3'] + df.loc[i, 'f5'] * df.loc[i, 'f3'] + np.random.rand() * 3 df.loc[i, 'f4'] = df.loc[i, 'f2'] ** 2.8 + np.random.normal(loc=0, scale=1.25, size=1) df['f4'] = df.f4.astype('float') df['target'] = df.target.astype('float') df.head() df.describe() df.corr() sns.pairplot(df); ``` ## Train/Test Split ``` X_train, X_test, y_train, y_test = train_test_split(df[['f1', 'f2', 'f3', 'f4', 'f5']], df['target'], test_size=0.2, random_state=42) ``` ## StandardScale ``` ss = StandardScaler() ss.fit(X_train) X_train_std = ss.transform(X_train) X_test_std = ss.transform(X_test) ``` ## Modeling ``` lr = LinearRegression() lasso = Lasso(alpha=0.01, random_state=42) ridge = Ridge(alpha=0.01, random_state=42) lr.fit(X_train_std, y_train) lasso.fit(X_train_std, y_train) ridge.fit(X_train_std, y_train) ``` ## Results ``` def pretty_print_coef(obj): print('intercept: {0:.4}'.format(obj.intercept_)) print('coef: {0:.3} {1:.4} {2:.4} {3:.3} {4:.3}'.format(obj.coef_[0], obj.coef_[1], obj.coef_[2], obj.coef_[3], obj.coef_[4])) models = (lr, lasso, ridge) for model in models: print(str(model)) pretty_print_coef(model) print('R^2:', model.score(X_train_std, y_train)) print('MSE:', mean_squared_error(y_test, model.predict(X_test_std))) print() np.mean(cross_val_score(lr, X_train_std, y_train, scoring='neg_mean_squared_error', cv=5, n_jobs=-1) * -1) np.mean(cross_val_score(lasso, X_train_std, y_train, scoring='neg_mean_squared_error', cv=5, n_jobs=-1) * -1) np.mean(cross_val_score(ridge, X_train_std, y_train, scoring='neg_mean_squared_error', cv=5, n_jobs=-1) * -1) ``` ## Residuals ``` fig, axes = plt.subplots(1, 3, sharex=False, sharey=False) fig.suptitle('[Residual Plots]') fig.set_size_inches(18,5) axes[0].plot(lr.predict(X_test_std), y_test-lr.predict(X_test_std), 'bo') axes[0].axhline(y=0, color='k') axes[0].grid() axes[0].set_title('Linear') axes[0].set_xlabel('predicted values') axes[0].set_ylabel('residuals') axes[1].plot(lasso.predict(X_test_std), y_test-lasso.predict(X_test_std), 'go') axes[1].axhline(y=0, color='k') axes[1].grid() axes[1].set_title('Lasso') axes[1].set_xlabel('predicted values') axes[1].set_ylabel('residuals') axes[2].plot(ridge.predict(X_test_std), y_test-ridge.predict(X_test_std), 'ro') axes[2].axhline(y=0, color='k') axes[2].grid() axes[2].set_title('Ridge') axes[2].set_xlabel('predicted values') axes[2].set_ylabel('residuals'); ``` ## Notes We can tell from the residuals that there's signal that we're not catching with our current model. The reason is obvious in this case, because we know how the data was generated. The **target** is built on interaction terms. ## Random Forest (for fun) ``` from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=10, max_depth=5, n_jobs=-1, random_state=42) rf.fit(X_train, y_train) mean_squared_error(y_test, rf.predict(X_test)) rf.feature_importances_ fig, axes = plt.subplots(1, 4, sharex=False, sharey=False) fig.suptitle('[Residual Plots]') fig.set_size_inches(18,5) axes[0].plot(lr.predict(X_test_std), y_test-lr.predict(X_test_std), 'bo') axes[0].axhline(y=0, color='k') axes[0].grid() axes[0].set_title('Linear') axes[0].set_xlabel('predicted values') axes[0].set_ylabel('residuals') axes[1].plot(lasso.predict(X_test_std), y_test-lasso.predict(X_test_std), 'go') axes[1].axhline(y=0, color='k') axes[1].grid() axes[1].set_title('Lasso') axes[1].set_xlabel('predicted values') axes[1].set_ylabel('residuals') axes[2].plot(ridge.predict(X_test_std), y_test-ridge.predict(X_test_std), 'ro') axes[2].axhline(y=0, color='k') axes[2].grid() axes[2].set_title('Ridge') axes[2].set_xlabel('predicted values') axes[2].set_ylabel('residuals'); axes[3].plot(rf.predict(X_test), y_test-rf.predict(X_test), 'ko') axes[3].axhline(y=0, color='k') axes[3].grid() axes[3].set_title('RF') axes[3].set_xlabel('predicted values') axes[3].set_ylabel('residuals'); ``` While random forest does a better job catching the interaction between variables, we still see some pattern in the residuals meaning we haven't captured all the signal. Nonetheless, random forest is signficantly better than linear regression, lasso, and ridge on the raw features. We can combat this with feature engineering, however.
github_jupyter