path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
source/2021/500Answer/content/019_can_build_horizontal_rectangle.ipynb
###Markdown 第19讲 重新认识矩形 Assignments 作业 1. 熟悉`prepare_paper`方法:导入`qianglib.py`,调用`prepare_paper`方法,修改该方法接受的参数值,使得`scale`值分别为10和50,min_x分别为0,10,min_y分别为0, 20,组合不同的这些参数值调用该方法。观察绘制出的方格值有什么变化,从中试图小结个该方法这些参数的意义。 Your Answer: 1. scale的意义: 2. min_x的意义: 3. min_y的意义: ###Code # 你需要预先从turtle和qianglib库中导入需要的方法 weight, height = 800, 600 setup(weight, height, 0, 0) prepare_paper(width, height, scale=10, min_x=0, min_y=0) prepare_paper(width, height, scale=10, min_x=0, min_y=20, max_y=25) prepare_paper(width, height, scale=10, min_x=10, min_y=0, max_y=25) prepare_paper(width, height, scale=10, min_x=10, min_y=20, max_y=25) prepare_paper(width, height, scale=50, min_x=0, min_y=0, max_y=25) prepare_paper(width, height, scale=50, min_x=0, min_y=20, max_y=25) prepare_paper(width, height, scale=50, min_x=10, min_y=0, max_y=25) prepare_paper(width, height, scale=50, min_x=10, min_y=20, max_y=25) ###Output _____no_output_____ ###Markdown 2. 使用本讲示例的代码调出绘图纸。下面以供给出了5组数据,每一组数据包括两个点的坐标。 对于每一组数据: 1. 请在绘图纸上使用`qianglib`中的`mark`方法标记这两个点, 2. 用`qianglib`方法中的`line`方法连接这两个点成一条线段。 3. 手工找到线段的中点,用`mark`方法标记该中点。 以端点坐标表示的线段 1. (0, 0)和(20, 0) 2. (0, 0)和(0,16) 3. (0, 0)和(20, 16) 4. (10, 20)和(30, 20) 5. (10, 20)和(35, 25) ###Code # A. points = [(0, 0), (20, 0)] for point in points: mark(point, info=str(point)) center = (10, 0) mark(center, info=str(center)) # B. # E. points = [(10, 20), (35, 25)] for point in points: mark(point, info=str(point)) center = (25, 22) mark(center, info=str(center)) line(points[0], center) line(center, points[1]) line(points[0], points[1]) ###Output _____no_output_____ ###Markdown 3. 以上一题为参考,编写一个方法专门计算一条线段中点的坐标,这条线段以两个点的坐标的形式给出,方法返回线段中点的坐标。该方法的定义如下,请完整的实现该方法。 ###Code def line_center(point1, point2): # point1, poit2 format of (x1, y1) # center = None # TODO: add your codes here x1, y1 = point1 x2, y2 = point2 print("x1:{}, y1:{}".format(x1, y1)) print("x2:{}, y2:{}".format(x2, y2)) center_x = (x1 + x2)/2 center_y = (y1 + y2)/2 print("center x: {}, y:{}".format(center_x, center_y)) center = (center_x, center_y) return center def line_center2(point1, point2): return ((point1[0]+point2[0])/2, (point1[1] + point2[1])/2) C = line_center(A, B) # C is center of line AB mark(C, info="C", color="blue", size=10) D = line_center2(A, B) print(D) mark(D, info="D", color="black", size=10) ###Output _____no_output_____ ###Markdown 4. find tow points on a line that divide the line into 3 equal parts. ###Code from turtle import setup, reset, pu, pd, bye, left, right, fd, bk, screensize from turtle import goto, seth, write, ht, st, home, dot, pen, speed from qianglib import prepare_paper, draw_grid, mark, lines, line, polygon, text width, height = 800, 600 setup(width, height, 0, 0) prepare_paper(width, height, scale=20, min_x=0, min_y=0, max_y=25) A = (10, 12) B = (25, 21) mark(A, info="A(10, 12)") mark(B, info="B(25, 21)") line(A, B) def three_equal_division(point1, point2): x1, y1 = point1 x2, y2 = point2 x_step = (x2 - x1)/3 y_step = (y2 - y1)/3 x3, y3 = x1 + x_step, y1 + y_step x4, y4 = x2 - x_step, y2 - y_step point3 = (x3, y3) point4 = (x4, y4) return [point3, point4] result_list = three_equal_division(A, B) E = result_list[0] F = result_list[1] mark(E) mark(F) line(A, E, color="yellow", linewidth=5) line(E, F, color="red", linewidth=5) line(F, B, color="blue", linewidth=5) # Example 2 P1 = (10, 5) P2 = (25, 5) mark(P1) mark(P2) result_list = three_equal_division(P1, P2) P3, P4 = result_list[0], result_list[1] line(P1, P3, color="yellow") line(P3, P4, color="red") line(P4, P2, color="blue") mark(P3, "P3(15, 5)") mark(P4, "P4(20, 5)") P5 = (5, 12) P6 = (5, 21) result_list = three_equal_division(P5, P6) P7, P8 = result_list[0], result_list[1] line(P5, P7, color="yellow") line(P7, P8, color="red") line(P8, P6, color="blue") mark(P5) mark(P6) mark(P7) mark(P8) ###Output _____no_output_____
notebooks/LA_Assignment5.ipynb
###Markdown Assignment 5 - (Un)supervised machine learningApplying (un)supervised machine learning to text dataEITHERTrain a text classifier on your data to predict some label found in the metadata. For example, maybe you want to use this data to see if you can predict sentiment label based on text content.ORTrain an LDA model on your data to extract structured information that can provide insight into your data. For example, maybe you are interested in seeing how different authors cluster together or how concepts change over time in this dataset.You should formulate a short research statement explaining why you have chosen this dataset and what you hope to investigate. This only needs to be a paragraph or two long and should be included as a README file along with the code. E.g.: I chose this dataset because I am interested in... I wanted to see if it was possible to predict X for this corpus.In this case, your peer reviewer will not just be looking to the quality of your code. Instead, they'll also consider the whole project including choice of data, methods, and output. Think about how you want your output to look. Should there be visualizations? CSVs?You should also include a couple of paragraphs in the README on the results, so that a reader can make sense of it all. E.g.: I wanted to study if it was possible to predict X. The most successful model I trained had a weighted accuracy of 0.6, implying that it is not possible to predict X from the text content alone. And so on.TipsThink carefully about the kind of preprocessing steps your text data may require - and document these decisions!Your choice of data will (or should) dictate the task you choose - that is to say, some data are clearly more suited to supervised than unsupervised learning and vice versa. Make sure you use an appropriate method for the data and for the question you want to answerYour peer reviewer needs to see how you came to your results - they don't strictly speaking need lots of fancy command line arguments set up using argparse(). You should still try to have well-structured code, of course, but you can focus less on having a fully-featured command line toolBonus challengesDo both tasks - either with the same or different datasetsGeneral instructionsYou should upload standalone .py script(s) which can be executed from the command lineYou must include a requirements.txt file and a bash script to set up a virtual environment for the project You can use those on worker02 as a templateYou can either upload the scripts here or push to GitHub and include a link - or both!Your code should be clearly documented in a way that allows others to easily follow the structure of your script and to use them from the command linePurposeThis assignment is designed to test that you have an understanding of:how to formulate research projects with computational elements;how to perform (un)supervised machine learning on text data;how to present results in an accessible manner. ###Code # standard library import sys,os sys.path.append(os.path.join("..")) from pprint import pprint from tqdm import tqdm # data and nlp import pandas as pd import spacy nlp = spacy.load("en_core_web_sm", disable=["ner"]) # import nltk from nltk.corpus import stopwords stop_words = stopwords.words('english') # visualisation import pyLDAvis.gensim pyLDAvis.enable_notebook() import seaborn as sns from matplotlib import rcParams # figure size in inches rcParams['figure.figsize'] = 20,10 # LDA tools import gensim import gensim.corpora as corpora from gensim.models import CoherenceModel from gensim.utils import simple_preprocess from utils import lda_utils # warnings import logging, warnings warnings.filterwarnings('ignore') logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR) data = pd.read_csv(os.path.join("..", "data", "phil_nlp (5).csv")).sample(50000) data.sample(10) bigram = gensim.models.Phrases(data["sentence_str"], min_count=5, threshold=100) # higher threshold fewer phrases. trigram = gensim.models.Phrases(bigram[data["sentence_str"]],min_count=3, threshold=100) bigram_mod = gensim.models.phrases.Phraser(bigram) trigram_mod = gensim.models.phrases.Phraser(trigram) def process_words(texts, nlp, bigram_mod, trigram_mod, stop_words=stop_words, allowed_postags=['NOUN', "ADJ", "VERB", "ADV"]): """Remove Stopwords, Form Bigrams, Trigrams and Lemmatization""" # use gensim simple preprocess texts = [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in tqdm(texts)] print("the texts have been roughly preprocessed") texts = [bigram_mod[doc] for doc in tqdm(texts)] print("bigrams have been formed") texts = [trigram_mod[bigram_mod[doc]] for doc in tqdm(texts)] print("trigrams have been formed") texts_out = [] # lemmatize and POS tag using spaCy print("lemmatizing and pos-tagging docs...") for sent in tqdm(texts): doc = nlp(" ".join(sent)) texts_out.append([f"{token.lemma_}_{token.pos_}" for token in doc if token.pos_ in allowed_postags]) return texts_out texts_out = [] data_processed = process_words(data["sentence_str"],nlp, bigram_mod, trigram_mod, allowed_postags=["ADJ", "ADV", "NOUN", "PROPN", "VERB", "NUM"]) df =pd.DataFrame(data_processed) data_processed[1] pd.DataFrame(data_processed).to_csv(os.path.join("..", "data", "assignment5", "data_preprocessed.csv")) with open(os.path.join("..", "data", "assignment5", "data_preprocessed.txt"), 'w') as file: for item in data_processed: file.write(" ".join(map(str,item))) file.write("\n") # read file in a string list with open(os.path.join("..", "data", "assignment5", "data_preprocessed.txt")) as f: lineList = f.readlines() test = [[word for word in simple_preprocess(str(doc))] for doc in tqdm(lineList)] test[0] test = open(os.path.join("..", "data", "assignment5", "data_preprocessed.txt"), 'r', sep = "\n") # Create Dictionary id2word = corpora.Dictionary(data_processed) # Create Corpus: Term Document Frequency corpus = [id2word.doc2bow(text) for text in data_processed] lda_model = gensim.models.LdaMulticore(corpus=corpus, # vectorised corpus - list of lists of tupols id2word=id2word, # gensim dictionary - mapping words to IDS num_topics=32, # number of topics random_state=100, # set for reproducability chunksize=10, # batch data for efficiency passes=10, # number of full passess over data iterations=100, # related to document rather than corpus per_word_topics=True, # define word distributions minimum_probability=0.0) # Compute Perplexity print('\nPerplexity: ', lda_model.log_perplexity(corpus)) # a measure of how good the model is. lower the better. # Compute Coherence Score coherence_model_lda = CoherenceModel(model=lda_model, texts=data_processed, dictionary=id2word, coherence='c_v') coherence_lda = coherence_model_lda.get_coherence() print('\nCoherence Score: ', coherence_lda) # Can take a long time to run. model_list, coherence_values = lda_utils.compute_coherence_values(texts=data_processed, corpus=corpus, dictionary=id2word, start=5, limit=40, step=5) df_topic_keywords = lda_utils.format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=data_processed) # Format df_dominant_topic = df_topic_keywords.reset_index() df_dominant_topic.columns = ['Chunk_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text'] df_dominant_topic.sample(10) # Display setting to show more characters in column pd.options.display.max_colwidth = 100 sent_topics_sorteddf = pd.DataFrame() sent_topics_outdf_grpd = df_topic_keywords.groupby('Dominant_Topic') for i, grp in sent_topics_outdf_grpd: sent_topics_sorteddf = pd.concat([sent_topics_sorteddf, grp.sort_values(['Perc_Contribution'], ascending=False).head(1)], axis=0) # Reset Index sent_topics_sorteddf.reset_index(drop=True, inplace=True) # Format sent_topics_sorteddf.columns = ['Topic_Num', "Topic_Perc_Contrib", "Keywords", "Representative Text"] # Show sent_topics_sorteddf.head(10) vis = pyLDAvis.gensim.prepare(lda_model, corpus, dictionary=lda_model.id2word) vis ###Output _____no_output_____
_notebooks/2021-06-23-manim_sine_curve_colab.ipynb
###Markdown Sine curve unit circle on Colab> "manim example"- toc: false- branch: master- hidden: true- categories: [manim, colab] ###Code %%capture # https://docs.manim.community/en/stable/installation/colab.html !sudo apt update !sudo apt install libcairo2-dev ffmpeg texlive texlive-latex-extra texlive-fonts-extra texlive-latex-recommended texlive-science tipa libpango1.0-dev !pip install manim !pip install IPython --upgrade from manim import * %%manim -v WARNING --disable_caching -qm SineCurveUnitCircle # https://docs.manim.community/en/stable/examples.html#sinecurveunitcircle class SineCurveUnitCircle(Scene): # contributed by heejin_park, https://infograph.tistory.com/230 def construct(self): self.show_axis() self.show_circle() self.move_dot_and_draw_curve() self.wait() def show_axis(self): x_start = np.array([-6,0,0]) x_end = np.array([6,0,0]) y_start = np.array([-4,-2,0]) y_end = np.array([-4,2,0]) x_axis = Line(x_start, x_end) y_axis = Line(y_start, y_end) self.add(x_axis, y_axis) self.add_x_labels() self.origin_point = np.array([-4,0,0]) self.curve_start = np.array([-3,0,0]) def add_x_labels(self): x_labels = [ MathTex("\pi"), MathTex("2 \pi"), MathTex("3 \pi"), MathTex("4 \pi"), ] for i in range(len(x_labels)): x_labels[i].next_to(np.array([-1 + 2*i, 0, 0]), DOWN) self.add(x_labels[i]) def show_circle(self): circle = Circle(radius=1) circle.move_to(self.origin_point) self.add(circle) self.circle = circle def move_dot_and_draw_curve(self): orbit = self.circle origin_point = self.origin_point dot = Dot(radius=0.08, color=YELLOW) dot.move_to(orbit.point_from_proportion(0)) self.t_offset = 0 rate = 0.25 def go_around_circle(mob, dt): self.t_offset += (dt * rate) # print(self.t_offset) mob.move_to(orbit.point_from_proportion(self.t_offset % 1)) def get_line_to_circle(): return Line(origin_point, dot.get_center(), color=BLUE) def get_line_to_curve(): x = self.curve_start[0] + self.t_offset * 4 y = dot.get_center()[1] return Line(dot.get_center(), np.array([x,y,0]), color=YELLOW_A, stroke_width=2 ) self.curve = VGroup() self.curve.add(Line(self.curve_start,self.curve_start)) def get_curve(): last_line = self.curve[-1] x = self.curve_start[0] + self.t_offset * 4 y = dot.get_center()[1] new_line = Line(last_line.get_end(),np.array([x,y,0]), color=YELLOW_D) self.curve.add(new_line) return self.curve dot.add_updater(go_around_circle) origin_to_circle_line = always_redraw(get_line_to_circle) dot_to_curve_line = always_redraw(get_line_to_curve) sine_curve_line = always_redraw(get_curve) self.add(dot) self.add(orbit, origin_to_circle_line, dot_to_curve_line, sine_curve_line) self.wait(8.5) dot.remove_updater(go_around_circle) ###Output
K-Meansapplicationtoimagecompression.ipynb
###Markdown K-Means clustering used for image compressionIn the following we discuss a curious application of K-Means clustering to image compression.In this notebook [this notebook](https://github.com/andreaspts/ML_KMeans_Clustering_Analyses/blob/master/simpleKmeansclusterungoncardata.ipynb), we introduced this particular algorithm and exemplified it's power on a simple example. For a reminder on K-Means clustering, we refer to https://en.wikipedia.org/wiki/K-means_clustering. In a first step, we have to load the image we would like to compress. We remind ourselves that the information encoding the image is in fact represented by an array. We then play around with this structure to gain some intuition about the dimensions of this array. We then reshape it to bring it into the appropriate form needed for the K-Means processing. In a second step, we feed it into the KMeans function and demand that the image information given in terms of numbers in the (now reshaped) array is clustered into 20 clusters. The idea is that e.g. reddish colors represented by a range of numbers are clustered around a mean color value. This is done for 20 color groups. We report these 20 cluster centers and the cluster labels, where the latter tells us which pixel belongs to which of the 20 clusters.Then these labels per pixel are associated to the cluster centers to regain the now compressed image/array which is subsequently reshaped.Finally, the image is printed and saved. ###Code #import necessary packages from skimage import io, exposure import imageio import numpy as np #load image image = io.imread("./cat2.jpg") io.imshow(image) #retrieve dimensional info of the image/array image.shape #would like to drop the transparency values (alpha channel in png files) if available #image[:, :, [0, 1, 2]] image[:, :, [0, 1, 2]].shape #some basic image manipulations to get an intuition for the dimensions #render picutre brighter image_without_alpha = image[:, :, :3] image_brighter = image_without_alpha + 40 image_brighter[image_brighter < image_without_alpha] = 255 io.imshow(image_brighter) #dimensions without alpha channel image_without_alpha.shape #bring image array into different form needed for KMeans algorithm image_reshaped = image_without_alpha.reshape(-1,3) image_without_alpha.reshape(-1,3).shape #use KMeans clustering to reduce colors of an image to 20 from sklearn.cluster import KMeans model = KMeans(n_clusters = 20, n_init = 1) #20 clusters only @ 1 attempt model.fit(image_reshaped) #print center points of the 20 clusters print(model.cluster_centers_) #print cluster label per pixel print(model.labels_) #length of the cluster labels equals (of course) that dimension of the array storing the image info len(model.labels_) #associate pixel labels to cluster centers: "giving restored image" colors = model.cluster_centers_.astype("uint8") #to convert centers values into integers representing true image information pixels = model.labels_ #save restored image np.savez_compressed("./image.npz", pixels = pixels, colors = colors) with np.load("./image.npz") as file: pixels = file["pixels"] colors = file["colors"] pixels_transformed = [] for pixel in pixels: pixels_transformed.append(colors[pixel]) #transform back into np array pixels_transformed = np.array(pixels_transformed) pixels_transformed.shape #reshaping in order to show the compressed image image_restored = pixels_transformed.reshape(878, 1600, 3) io.imshow(image_restored) #saving compressed (array as an) image imageio.imwrite('cat2_transformed.jpg', image_restored) ###Output _____no_output_____
working_notebook/TaylorDataPrep.ipynb
###Markdown Remuve duplicates*same album appears multiple times, but with different names, and it is actually a problem ###Code #Deleting the Live, Genius, Demo and stuff k=0 Not_good_words=['Live','Genius','Demo','folklore'] TODEL=[] for alb in data.album.drop_duplicates().tolist(): sp=alb.split() if len(sp)!=0: for s in sp: if s=='Live' or s=='Genius' or s=='Demo' or s=='folklore': # checkif the tile one of this target words TODEL.append(k) k=k+1 alb=np.array(data.album.drop_duplicates().tolist()) ALB=[] for a in range(len(alb)): if a not in TODEL: ALB.append(alb[a]) LIST_ALB_TITLE=[] for a in ALB: sp=a.split() LIST_ALB_TITLE.append(sp) print("ALB:",ALB) # Adding folklore ALB=ALB+['folklore'] ALB=pd.DataFrame(ALB).drop_duplicates(keep='first') ALB=ALB.drop([15,12])[0].tolist() #Taking the final good index and the choruses of these ones. IND=data[(data.album.isin(ALB)) & (data.lyric=='[Chorus]')].drop_duplicates(subset='song_title').index.tolist() #Identifying the stop (e.g. '[Chorus]') stop=[] for l in data.lyric.tolist(): if l[0]=='[': stop.append(1) else: stop.append(0) data['S']=stop #Move in the index range CHORUSES=[] for i in IND: #Pick the chorus till the following line new_d=data[i+1::] ss=new_d.S.tolist() for q in range(len(ss)): if ss[q]==1: #Stop when you see that the choruses is ended break new_d=data[i+1:i+1+q] #BOOM! You have the chorus CHORUSES.append(new_d.lyric.tolist()) print("Number of chorouses:",len(CHORUSES)) nr_verse=0 for c in CHORUSES: nr_verse=nr_verse+len(c) print("Number of verses:", nr_verse) bulk_corpus = " " for chorus in CHORUSES: for vers in chorus: bulk_corpus= bulk_corpus +"\n"+vers print(bulk_corpus) text_file = open("TaylorSwift/bulk_taylor.txt", "w") n = text_file.write(bulk_corpus) text_file.close() ###Output _____no_output_____
2_4_overfitting_underfitting/2_2_Aufgabe - Overfitting - Underfitting.ipynb
###Markdown In diesem Tutorial beschäftigen Sie sich anhand eines Spielbeispiels mit den Problemen einer Überanpassung oder Unteranpassung der linearen bzw. logistischen Regression.In der begleitenden Python-File `utils.py` befinden sich Hilfsfunktionen zum Erstellen eines zufälligen Trainings- und Testdatensatzes mit einer Beobachtung und einer kontinuierlichen Zielvariablen. (2.2.1) Lineare Regression (o) &x1F4D7;** (a) ** &x1F4D7; Erstellen Sie per `utils.get_train_data()` einen Trainingsdatensatz mit Inputvariablen $\{x^{(i)} \; | \; i = 1, ..., N\}$ und Zielvariablen $\{y_T^{(i)}\; | \; i = 1, ..., N\}$ und führen Sie darauf eine lineare Regression aus.** (b) ** &x1F4D7; Treffen Sie eine Vorhersage der Zielvariablen, $\{\hat{y}^{(i)}\; | \; i = 1, ..., N\}$, für die Beobachtungen des Trainingsdatensatzes. Beurteilen Sie die Qualität der Vorhersage, indem Sie einmal den durchschnittlichen quadratischen und einmal den durchschnittlichen absoluten Fehler der Vorhersage berechnen:(i) Quadratischer Fehler: $ \frac{1}{N} \sum_{i=1}^N (\hat{y}^{(i)} - y_T^{(i)})^2$(ii) Absoluter Fehler: $ \frac{1}{N} \sum_{i=1}^N | \hat{y}^{(i)} - y_T^{(i)} | $*(Tipp: wenn der quadratische Fehler aus Ihrer Sicht keine Aussagekraft hat, verwenden Sie stattdessen den RMSE)*** (c) ** &x1F4D7; Visualisieren Sie das Ergebnis der Regression auf eine geeignete Weise.** (d) ** &x1F4D7; Erstellen Sie nun einen Testdatensatz per `utils.get_test_data()` und treffen Sie erneut eine Vorhersage der Zielvariablen mit dem in **b)** erstellten Modell. Berechnen Sie den durchschnittlichen quadratischen und absoluten Fehler der Vorhersage auf dem Testdatensatz. Interpretieren Sie das Ergebnis. *(Tipp: wenn der quadratische Fehler aus Ihrer Sicht keine Aussagekraft hat, verwenden Sie stattdessen den RMSE)*** (e) ** &x1F4D7; Wiederholen Sie die Aufgaben **b)** bis **c)** für ein quadratisches Modell (Nutzen Sie dafür zum Beispiel `from sklearn.preprocessing import PolynomialFeatures`.). Interpretieren Sie die Ergebnisse. ###Code import utils from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline import numpy as np ###Output _____no_output_____ ###Markdown (2.2.2) Zufällige Trainingsdaten ** (oo) ** &x1F4D9; Die Hilfsfunktion `utils.get_train_data()` erzeugt bei jedem Aufruf einen neuen, zufälligen, Datensatz während die Funktion `utils.get_test_data()` einen festen Testdatensatz erzeugt. In dieser Aufgabe untersuchen Sie, welchen Einfluss die Zufälligkeit des Trainingsdatensatzes auf die Qualität des Modells hat.** (a) ** &x1F4D7; Erstellen und visualisieren Sie exemplarisch zwei verschiedene Trainingsdatensätze.** (b) ** &x1F4D9; Wiederholen Sie die Aufgaben **1a)**, **1b)** und **1d)** für $10-20$ zufällig generierte Trainingsdatensätze. Entscheiden Sie sich dabei für eine der Fehlermetriken (zum Beispiel RMSE). Speichern Sie sich die Fehler für jede der $10-20$ Wiederholungen des Experiments.Berechnen Sie dann folgende Größe: Für jeden Trainingsdatensatz haben Sie ein separates Modell trainiert und evaluiert. Daraus resultiert jeweils ein Trainingsfehler und ein Testfehler. Berechnen Sie nun den durchschnittlichen Trainingsfehler und Testfehler und die Standardabweichung dieser Fehler über alle Trainingsdatensätze hinweg (*Hinweis: der Trainings- und Testfehler sind für sich genommen schon Durchschnittswerte - nämlich über die Datenpunkte hinweg. Hier aber ist gemeint, die Durchschnittswerte dieser Fehler für die Widerholungen des Experiments zu berechnen - in einem gewissen Sinne also Durchschnittswerte der Durchschnittswerte*)** (c) ** &x1F4D9; Visualisieren Sie die Ergebnisse aus **c)** indem Sie die $10-20$ verschiedenen linearen Modelle in einem einzigen Plot darstellen.** (d) ** &x1F4D9; Wiederholen Sie nun die vorherigen Aufgabenteile während Sie anstelle eines linearen Modells ein quadratisches Modell oder sogar ein Modell höheren Grades verwenden (siehe Aufgabe **1d)**).** (e) ** &x1F4D9; Interpretieren Sie Ihre Ergebnisse. (2.2.3) Bias-Variance-Tradeoff (ooo) &x1F4D8; In der vorherigen Aufgabe haben Sie eine Reihe von Modellen auf der Basis zufälliger Trainingsdaten erstellt und für jedes Modell den Testfehler berechnet. Daraufhin ließ sich der durchschnittliche Testfehler sowie die Varianz des Testfehlers schätzen. Sie haben das lineare Modell mit dem quadratischen Modell verglichen.Nun wollen wir die Komplexität des Modells systematisch erhöhen.Als Maß für die Komplexität des Modells nehmen wir den Grad der polynomischen Expansion an. Der Parameter `'degree'` kann von $1$ (lineares Modell) systematisch erhöht werden. Für jede Komplexitätsstufe lassen sich dann eine Reihe Modelle auf Basis zufälliger Trainingsdaten erstellen. Der Testdatensatz bleibt stets derselbe.Wiederholen Sie für jeden Grad (`degree`) der polynomischen Expansion die folgenden Schritte:*(i)* Trainieren Sie $10-20$ verschiedene Modelle jeweils auf einem zufällig generierten Trainingsdatensatz. Um die gewünschten Ergebnisse sichtbar zu machen, bietet es sich an, die Menge an Beobachtungen noch weiter zu reduzieren. Nutzen Sie dafür das Argument `n_samples` der Funktion `utils.get_train_data()`.*(ii)* Berechnen Sie die durchschnittliche Vorhersage zwischen diesen Modellen und plotten Sie diese etwa für $x \in [0, 10]$.*(iii)* Berechnen Sie die Standardabweichung zwischen den verschiedenen Vorhersagen und visualisieren Sie diese auf eine geeignete Weise für $x \in [0, 10]$.*(iv)* Benutzen Sie `utils.true_function` um die den Daten tatsächlich zu Grunde liegende Funktion zu plotten. Versuchen Sie, die Plots aus *(ii)*-*(iv)* für jeden Grad der polynomischen Expansion in einem einzigen Plot darzustellen. Interpretieren Sie ihre Ergebnisse. (2.2.4) Regularisierung (o) - (oo) &x1F4D7; Um das Risiko einer Überanpassung zu verhindern, kann die lineare/polynomiale Regression regularisiert werden. Dazu wird der Verlustfunktion ein zusätzlicher Regularisierungsterm hinzugefügt, der dafür sorgt, dass Koeffizienten kleiner Magnitude gegenüber Koeffizienten großer Magnitude bevorzugt werden.Scikit-Learn stellt die lineare Regression mit Regularisierung in den Klassen `Ridge`, `ElasticNet` und `Lasso` zur Verfügung.** (a) ** &x1F4D7; Beschäftigen Sie sich zunächst der Dokumentation aller drei Klassen. Was ist der wesentliche Unterschied zwischen den Klassen? Benutzen Sie im Folgenden nur die Klasse `Ridge` für eine lineare Regression mit L2-Regularisierung. Setzen Sie in jedem Fall `normalize=True` für alle weiteren Experimente.** (b) ** &x1F4D7; Wählen Sie ein Regressionsmodell mit einem mittleren Grad der polynomischen Expansion, etwa 6-8. Generieren Sie zunächst einen Trainingsdatensatz wie in den vorherigen Aufgaben und fitten Sie das Modell. Vergleichen Sie die Ergebnisse einer Regression mit `alpha=0.0`, `alpha=1.0` und `alpha=10.0`, indem Sie den Fit wie in den vorherigen Aufgaben auf eine geeignete Weise visualisieren und die Trainings- und Testfehler der Verfahren miteinander vergleichen. Interpretieren Sie.** (c) ** &x1F4D9; Varieren Sie nun den Hyperparameter `alpha` der Regression systematisch, z.B. logarithmisch: $\alpha = 0, 10^{-3}, 5 \cdot 10^{-3}, 10^{-2}, ..., 10$ (Tipp: `np.logspace`). Trainieren Sie nun für jeden Wert des Hyperparameters $20-50$ verschiedene Modelle auf jeweils zufällig generierten Trainingsdaten und berechnen Sie jedesmal den Trainingsfehler sowie den Testfehler. Plotten Sie dann den durchschnittlichen Trainings- sowie Testfehler (über die zufälligen Trainingsdatensätze hinweg) sowie, in einem separaten Plot, deren Standardabweichung, gegen den Wert des Hyperparameters. Um das Ergebnis sichtbar zu machen, können Sie die Menge an Beobachtungen für die Trainingsdaten reduzieren, indem Sie das Argument `n_samples` der Funktion `utils.get_train_data()` verwenden. Interpretieren Sie das Ergebnis. ###Code from sklearn.linear_model import Ridge, ElasticNet, Lasso ###Output _____no_output_____
notebooks/data-owner_GTEx-regression.ipynb
###Markdown Federated Learning - GTEx_V8 Example Import dependencies ###Code #dependencies for helper functions/classes import pandas as pd import pyarrow.parquet as pq from typing import NamedTuple import os.path as path import os import progressbar import requests import numpy as np import random #keras for ML import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Dropout, Input, Dense from tensorflow.keras.models import Sequential, load_model, Model from tensorflow.keras.utils import plot_model, normalize from tensorflow.keras import regularizers from tensorflow.keras.optimizers import SGD, Adam, Nadam, Adadelta from tensorflow.keras.activations import relu, elu, sigmoid #sklearn for preprocessing the data and train-test split from sklearn.utils import class_weight from sklearn.model_selection import train_test_split, cross_val_score, KFold from sklearn.preprocessing import OneHotEncoder, MinMaxScaler, LabelEncoder, StandardScaler from sklearn.pipeline import Pipeline from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error, accuracy_score, classification_report from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score, r2_score, mean_squared_error, mean_absolute_error #for plots import matplotlib import matplotlib.pyplot as plt #%matplotlib inline import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import SGD from tensorflow.keras import backend as K ###Output _____no_output_____ ###Markdown Parameter cell --> ###Code seed = 7 _test_size = 0.2 comms_round = 50 local_epochs = 100 CLIENTS = 2 local_batch_size = 256 VERBOSE = 1 class Labels(NamedTuple): ''' One-hot labeled data ''' tissue: np.ndarray sex: np.ndarray age: np.ndarray death: np.ndarray class Genes: ''' Class to load GTEX samples and gene expressions data ''' def __init__(self, samples_path: str = '', expressions_path: str = '', problem_type: str = "classification"): self.__set_samples(samples_path) self.__set_labels(problem_type) if expressions_path != '': self.expressions = self.get_expressions(expressions_path) def __set_samples(self, sample_path: str) -> pd.DataFrame: self.samples: pd.DataFrame = pq.read_table(sample_path).to_pandas() self.samples["Death"].fillna(-1.0, inplace = True) self.samples: pd.DataFrame = self.samples.set_index("Name") self.samples["Sex"].replace([1, 2], ['male', 'female'], inplace=True) self.samples["Death"].replace([-1,0,1,2,3,4], ['alive/NA', 'ventilator case', '<10 min.', '<1 hr', '1-24 hr.', '>1 day'], inplace=True) self.samples = self.samples[~self.samples['Death'].isin(['>1 day'])] return self.samples def __set_labels(self, problem_type: str = "classification") -> Labels: self.labels_list = ["Tissue", "Sex", "Age", "Death"] self.labels: pd.DataFrame = self.samples[self.labels_list] self.drop_list = self.labels_list + ["Subtissue", "Avg_age"] if problem_type == "classification": dummies_df = pd.get_dummies(self.labels["Age"]) print(dummies_df.columns.tolist()) self.Y = dummies_df.values if problem_type == "regression": self.Y = self.samples["Avg_age"].values return self.Y def sex_output(self, model): return Dense(units=self.Y.sex.shape[1], activation='softmax', name='sex_output')(model) def tissue_output(self, model): return Dense(units=self.Y.tissue.shape[1], activation='softmax', name='tissue_output')(model) def death_output(self, model): return Dense(units=self.Y.death.shape[1], activation='softmax', name='death_output')(model) def age_output(self, model): ''' Created an output layer for the keras mode :param model: keras model :return: keras Dense layer ''' return Dense(units=self.Y.age.shape[1], activation='softmax', name='age_output')(model) def get_expressions(self, expressions_path: str)->pd.DataFrame: ''' load gene expressions DataFrame :param expressions_path: path to file with expressions :return: pandas dataframe with expression ''' if expressions_path.endswith(".parquet"): return pq.read_table(expressions_path).to_pandas().set_index("Name") else: separator = "," if expressions_path.endswith(".csv") else "\t" return pd.read_csv(expressions_path, sep=separator).set_index("Name") def prepare_data(self, normalize_expressions: bool = True)-> np.ndarray: ''' :param normalize_expressions: if keras should normalize gene expressions :return: X array to be used as input data by keras ''' data = self.samples.join(self.expressions, on = "Name", how="inner") ji = data.columns.drop(self.drop_list) x = data[ji] # adding one-hot-encoded tissues and sex #x = pd.concat([x,pd.get_dummies(data['Tissue'], prefix='tissue'), pd.get_dummies(data['Sex'], prefix='sex')],axis=1) steps = [('standardization', StandardScaler()), ('normalization', MinMaxScaler())] pre_processing_pipeline = Pipeline(steps) transformed_data = pre_processing_pipeline.fit_transform(x) x = transformed_data print('Data length', len(x)) return x #normalize(x, axis=0) if normalize_expressions else x def get_features_dataframe(self, add_tissues=False): data = self.samples.join(self.expressions, on = "Name", how="inner") ji = data.columns.drop(self.drop_list) df = data[ji] if add_tissues: df = pd.concat([df,pd.get_dummies(data['Tissue'], prefix='tissue'), pd.get_dummies(data['Sex'], prefix='sex')],axis=1) x = df.values min_max_scaler = MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) df_normalized = pd.DataFrame(x_scaled, columns=df.columns, index=df.index) return df_normalized samples_path = '../data/gtex/v8_samples.parquet' expressions_path = '../data/gtex/v8_expressions.parquet' genes = Genes(samples_path, expressions_path, problem_type="regression") X = genes.prepare_data(True) Y = genes.Y #split data into training and test set X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=_test_size, random_state=seed) def create_clients(image_list, label_list, num_clients=10, initial='clients'): ''' return: a dictionary with keys clients' names and value as data shards - tuple of images and label lists. args: image_list: a list of numpy arrays of training images label_list:a list of binarized labels for each image num_client: number of fedrated members (clients) initials: the clients'name prefix, e.g, clients_1 ''' #create a list of client names client_names = ['{}_{}'.format(initial, i+1) for i in range(num_clients)] #randomize the data data = list(zip(image_list, label_list)) random.shuffle(data) #shard data and place at each client size = len(data)//num_clients shards = [data[i:i + size] for i in range(0, size*num_clients, size)] #number of clients must equal number of shards assert(len(shards) == len(client_names)) return {client_names[i] : shards[i] for i in range(len(client_names))} #create clients clients = create_clients(X_train, y_train, num_clients=CLIENTS, initial='client') clients.keys(), clients['client_1'][0][0].shape def batch_data(data_shard, bs=256): '''Takes in a clients data shard and create a tfds object off it args: shard: a data, label constituting a client's data shard bs:batch size return: tfds object''' #seperate shard into data and labels lists data, label = zip(*data_shard) dataset = tf.data.Dataset.from_tensor_slices((list(data), list(label))) return dataset.shuffle(len(label)).batch(bs) #process and batch the training data for each client clients_batched = dict() for (client_name, data) in clients.items(): clients_batched[client_name] = batch_data(data, bs = local_batch_size) #process and batch the test set test_batched = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(len(y_test)) clients_batched.keys(),clients_batched['client_1'] from keras import backend as K def coeff_determination(y_true, y_pred): SS_res = K.sum(K.square( y_true-y_pred )) SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) ) return ( 1 - SS_res/(SS_tot + K.epsilon()) ) def optimized_age_model_regression(): # optimized_age_model(x_train, x_val, y_train, y_val, params: dict): input_layer = Input(shape=(clients['client_1'][0][0].shape[0],)) reg = keras.regularizers.l1_l2(l1=0.3, l2=0.3) mod = Dense(1024, activation=relu)(input_layer) # 196 mod = Dropout(0.1)(mod) mod = Dense(512, activation=relu)(mod) # 196 mod = Dropout(0.1)(mod) mod = Dense(64, activation=relu)(mod) #64 mod = Dropout(0.1)(mod) outputs = [Dense(1, name='age_output')(mod)] #let's try to make it simple and start with age #outputs = [Dense(y_train.shape[1], activation='sigmoid', name='age_output')(mod)] #let's try to make it simple and start with age loss = {'age_output': 'mse'} weights={'age_output': 1.0} metrics = {'age_output': ['mae', coeff_determination]} model = Model(inputs=input_layer, outputs=outputs) model.summary() model.compile(optimizer='adam', loss=loss, loss_weights=weights, metrics=metrics, ) return model # class SimpleRegression: # @staticmethod # def build(shape = clients['client_1'][0][0].shape[0]): # model = Sequential() # model.add(Dense(1024, input_shape=(shape,))) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(512)) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(64)) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(1)) # return model # def global_model_init(): # model = Sequential() # model.add(Dense(1024, input_shape=(clients['client_1'][0][0].shape[0],))) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(512)) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(64)) # model.add(Activation("relu")) # model.add(Dropout(0.1)) # model.add(Dense(1)) # return model def Huber(yHat, y, delta=1.): return np.where(np.abs(y-yHat) < delta,.5*(y-yHat)**2 , delta*(np.abs(y-yHat)-0.5*delta)) def transform_to_probas(age_intervals): class_names = ['20-29', '30-39', '40-49', '50-59', '60-69', '70-79'] res = [] for a in age_intervals: non_zero_index = class_names.index(a) res.append([0 if i != non_zero_index else 1 for i in range(len(class_names))]) return np.array(res) def transform_to_interval(age_probas): class_names = ['20-29', '30-39', '40-49', '50-59', '60-69', '70-79'] return np.array(list(map(lambda p: class_names[np.argmax(p)], age_probas))) def weight_scalling_factor(clients_trn_data, client_name): client_names = list(clients_trn_data.keys()) #get the bs bs = list(clients_trn_data[client_name])[0][0].shape[0] #first calculate the total training data points across clinets global_count = sum([tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy() for client_name in client_names])*bs # get the total number of data points held by a client local_count = tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy()*bs return local_count/global_count def scale_model_weights(weight, scalar): '''function for scaling a models weights''' weight_final = [] steps = len(weight) for i in range(steps): weight_final.append(scalar * weight[i]) return weight_final def sum_scaled_weights(scaled_weight_list): '''Return the sum of the listed scaled weights. The is equivalent to scaled avg of the weights''' avg_grad = list() #get the average grad accross all client gradients for grad_list_tuple in zip(*scaled_weight_list): layer_mean = tf.math.reduce_sum(grad_list_tuple, axis=0) avg_grad.append(layer_mean) return avg_grad rmse = [] mae = [] r2 = [] huber_loss = [] # loss = 'mse' # metrics = ['mae', coeff_determination] # loss = {'age_output': 'mse'} # weights={'age_output': 1.0} # metrics = {'age_output': ['mae', coeff_determination]} #initialize global model global_model = optimized_age_model_regression() # smlp_global = SimpleRegression() # global_model = smlp_global.build() #commence global training loop for comm_round in range(comms_round): print('='*62) print('---------<STARTING TRAINING FOR ROUND {}>-----------'.format(comm_round)) # get the global model's weights - will serve as the initial weights for all local models global_weights = global_model.get_weights() #initial list to collect local model weights after scalling scaled_local_weight_list = list() #randomize client data - using keys client_names= list(clients_batched.keys()) random.shuffle(client_names) #loop through each client and create new local model for client in client_names: print('---------<STARTING TRAINING FOR CLIENT {}>-----------'.format(client)) local_model = optimized_age_model_regression() # smlp_local = SimpleRegression() # local_model = smlp_local.build() # local_model.compile(loss=loss, # optimizer='adam', # metrics=metrics) #set local model weight to the weight of the global model local_model.set_weights(global_weights) local_model.fit(clients_batched[client], epochs=local_epochs, verbose=VERBOSE) predictions = local_model.predict(X_test) test_y = y_test print('---------<TEST RESULTS FOR CLIENT {} ; USING LOCAL MODEL>-----------'.format(client)) print("R^2", r2_score(test_y, predictions)) print("Mean squared error", mean_squared_error(test_y, predictions)) print("Mean absolute error", mean_absolute_error(test_y, predictions)) print('Huber loss', np.mean(Huber(test_y, predictions))) #scale the model weights and add to list scaling_factor = weight_scalling_factor(clients_batched, client) print("SCALING FACTOR : {0}".format(scaling_factor)) scaled_weights = scale_model_weights(local_model.get_weights(), scaling_factor) scaled_local_weight_list.append(scaled_weights) #clear session to free memory after each communication round K.clear_session() #to get the average over all the local model, we simply take the sum of the scaled weights average_weights = sum_scaled_weights(scaled_local_weight_list) #update global model global_model.set_weights(average_weights) predictions = global_model.predict(X_test) test_y = y_test print('--------<TEST RESULTS AFTER ROUND {} ; USING GLOBAL MODEL>---------'.format(comm_round)) print("R^2", round(r2_score(test_y, predictions), 3)) print("Mean squared error", round(mean_squared_error(test_y, predictions), 3)) print("Mean absolute error", round(mean_absolute_error(test_y, predictions), 3)) print('Huber loss', round(np.mean(Huber(test_y, predictions)), 3)) rmse.append(mean_squared_error(test_y, predictions)) mae.append(mean_absolute_error(test_y, predictions)) r2.append(r2_score(test_y, predictions)) huber_loss.append(np.mean(Huber(test_y, predictions))) print('='*62) ###Output Model: "model_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_5 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense_12 (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout_12 (Dropout) (None, 1024) 0 _________________________________________________________________ dense_13 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_13 (Dropout) (None, 512) 0 _________________________________________________________________ dense_14 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_14 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ ============================================================== ---------<STARTING TRAINING FOR ROUND 0>----------- ---------<STARTING TRAINING FOR CLIENT client_2>----------- Model: "model_5" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_6 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense_15 (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout_15 (Dropout) (None, 1024) 0 _________________________________________________________________ dense_16 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_16 (Dropout) (None, 512) 0 _________________________________________________________________ dense_17 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_17 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 22s 900ms/step - loss: 711.8218 - mae: 21.4210 - coeff_determination: -3.4491 Epoch 2/100 24/24 [==============================] - 14s 578ms/step - loss: 330.9977 - mae: 14.4150 - coeff_determination: -1.0234 Epoch 3/100 24/24 [==============================] - 14s 585ms/step - loss: 276.4013 - mae: 13.2223 - coeff_determination: -0.6958 Epoch 4/100 24/24 [==============================] - 14s 589ms/step - loss: 235.7928 - mae: 12.2932 - coeff_determination: -0.4533 Epoch 5/100 24/24 [==============================] - 15s 633ms/step - loss: 214.9347 - mae: 11.7453 - coeff_determination: -0.3183 Epoch 6/100 24/24 [==============================] - 18s 736ms/step - loss: 197.0365 - mae: 11.2304 - coeff_determination: -0.2024 Epoch 7/100 24/24 [==============================] - 24s 1s/step - loss: 176.7989 - mae: 10.6877 - coeff_determination: -0.0827 Epoch 8/100 24/24 [==============================] - 16s 659ms/step - loss: 167.7708 - mae: 10.4220 - coeff_determination: -0.0316 Epoch 9/100 24/24 [==============================] - 14s 573ms/step - loss: 158.8795 - mae: 10.1070 - coeff_determination: 0.0283 Epoch 10/100 24/24 [==============================] - 13s 557ms/step - loss: 161.9794 - mae: 10.2786 - coeff_determination: 0.0089 Epoch 11/100 24/24 [==============================] - 14s 567ms/step - loss: 155.8361 - mae: 10.0048 - coeff_determination: 0.0434 Epoch 12/100 24/24 [==============================] - 13s 553ms/step - loss: 133.2294 - mae: 9.2436 - coeff_determination: 0.1842 Epoch 13/100 24/24 [==============================] - 13s 556ms/step - loss: 128.0723 - mae: 9.0768 - coeff_determination: 0.2196 Epoch 14/100 24/24 [==============================] - 13s 557ms/step - loss: 130.5900 - mae: 9.2220 - coeff_determination: 0.1978 Epoch 15/100 24/24 [==============================] - 13s 551ms/step - loss: 117.0472 - mae: 8.6489 - coeff_determination: 0.2818 Epoch 16/100 24/24 [==============================] - 14s 567ms/step - loss: 130.2188 - mae: 9.1692 - coeff_determination: 0.2010 Epoch 17/100 24/24 [==============================] - 13s 556ms/step - loss: 113.5172 - mae: 8.5855 - coeff_determination: 0.2932 Epoch 18/100 24/24 [==============================] - 13s 551ms/step - loss: 112.0882 - mae: 8.4862 - coeff_determination: 0.3082 Epoch 19/100 24/24 [==============================] - 13s 560ms/step - loss: 103.5279 - mae: 8.1372 - coeff_determination: 0.3624 Epoch 20/100 24/24 [==============================] - 14s 577ms/step - loss: 114.1549 - mae: 8.6251 - coeff_determination: 0.2850 Epoch 21/100 24/24 [==============================] - 14s 577ms/step - loss: 101.5476 - mae: 8.0213 - coeff_determination: 0.3835 Epoch 22/100 24/24 [==============================] - 14s 570ms/step - loss: 105.2950 - mae: 8.2293 - coeff_determination: 0.3547 Epoch 23/100 24/24 [==============================] - 13s 562ms/step - loss: 100.1649 - mae: 7.9865 - coeff_determination: 0.3783 Epoch 24/100 24/24 [==============================] - 13s 559ms/step - loss: 104.9791 - mae: 8.1861 - coeff_determination: 0.3567 Epoch 25/100 24/24 [==============================] - 14s 568ms/step - loss: 95.4008 - mae: 7.8091 - coeff_determination: 0.4128 Epoch 26/100 24/24 [==============================] - 13s 560ms/step - loss: 111.8253 - mae: 8.4757 - coeff_determination: 0.3233 Epoch 27/100 24/24 [==============================] - 14s 563ms/step - loss: 91.1053 - mae: 7.5975 - coeff_determination: 0.4379 Epoch 28/100 24/24 [==============================] - 14s 569ms/step - loss: 85.2423 - mae: 7.4103 - coeff_determination: 0.4723 Epoch 29/100 24/24 [==============================] - 13s 559ms/step - loss: 89.5538 - mae: 7.5504 - coeff_determination: 0.4520 Epoch 30/100 24/24 [==============================] - 14s 572ms/step - loss: 82.1167 - mae: 7.1936 - coeff_determination: 0.4989 Epoch 31/100 24/24 [==============================] - 15s 613ms/step - loss: 78.5589 - mae: 7.0683 - coeff_determination: 0.5173 Epoch 32/100 24/24 [==============================] - 13s 562ms/step - loss: 86.0092 - mae: 7.4139 - coeff_determination: 0.4701 Epoch 33/100 24/24 [==============================] - 13s 556ms/step - loss: 75.6967 - mae: 6.9227 - coeff_determination: 0.5358 Epoch 34/100 24/24 [==============================] - 14s 563ms/step - loss: 91.3069 - mae: 7.6531 - coeff_determination: 0.4386 Epoch 35/100 24/24 [==============================] - 13s 558ms/step - loss: 90.4786 - mae: 7.6718 - coeff_determination: 0.4424 Epoch 36/100 24/24 [==============================] - 13s 561ms/step - loss: 95.2333 - mae: 7.7981 - coeff_determination: 0.4196 Epoch 37/100 24/24 [==============================] - 13s 556ms/step - loss: 76.7806 - mae: 6.9583 - coeff_determination: 0.5318 Epoch 38/100 24/24 [==============================] - 13s 558ms/step - loss: 70.5146 - mae: 6.6443 - coeff_determination: 0.5680 Epoch 39/100 24/24 [==============================] - 14s 568ms/step - loss: 69.7687 - mae: 6.6130 - coeff_determination: 0.5737 Epoch 40/100 24/24 [==============================] - 13s 557ms/step - loss: 70.1452 - mae: 6.6319 - coeff_determination: 0.5696 Epoch 41/100 24/24 [==============================] - 14s 563ms/step - loss: 116.7408 - mae: 8.7470 - coeff_determination: 0.2746 Epoch 42/100 24/24 [==============================] - 13s 558ms/step - loss: 83.0586 - mae: 7.2809 - coeff_determination: 0.4836 Epoch 43/100 24/24 [==============================] - 13s 559ms/step - loss: 67.2713 - mae: 6.5226 - coeff_determination: 0.5830 Epoch 44/100 24/24 [==============================] - 14s 567ms/step - loss: 65.2352 - mae: 6.4024 - coeff_determination: 0.5995 Epoch 45/100 24/24 [==============================] - 13s 559ms/step - loss: 67.8142 - mae: 6.5167 - coeff_determination: 0.5811 Epoch 46/100 24/24 [==============================] - 13s 555ms/step - loss: 71.7981 - mae: 6.7153 - coeff_determination: 0.5610 Epoch 47/100 24/24 [==============================] - 13s 558ms/step - loss: 68.7351 - mae: 6.6475 - coeff_determination: 0.5664 Epoch 48/100 24/24 [==============================] - 14s 572ms/step - loss: 90.1364 - mae: 7.5820 - coeff_determination: 0.4523 Epoch 49/100 24/24 [==============================] - 14s 567ms/step - loss: 69.4793 - mae: 6.6106 - coeff_determination: 0.5750 Epoch 50/100 24/24 [==============================] - 14s 581ms/step - loss: 61.3960 - mae: 6.1966 - coeff_determination: 0.6206 Epoch 51/100 24/24 [==============================] - 14s 566ms/step - loss: 68.7231 - mae: 6.5611 - coeff_determination: 0.5783 Epoch 52/100 24/24 [==============================] - 13s 557ms/step - loss: 59.4956 - mae: 6.1222 - coeff_determination: 0.6344 Epoch 53/100 24/24 [==============================] - 14s 565ms/step - loss: 58.8928 - mae: 6.0806 - coeff_determination: 0.6385 Epoch 54/100 24/24 [==============================] - 13s 557ms/step - loss: 64.8401 - mae: 6.3740 - coeff_determination: 0.6043 Epoch 55/100 24/24 [==============================] - 13s 559ms/step - loss: 66.3404 - mae: 6.4920 - coeff_determination: 0.5918 Epoch 56/100 24/24 [==============================] - 13s 559ms/step - loss: 62.3591 - mae: 6.2478 - coeff_determination: 0.6179 Epoch 57/100 24/24 [==============================] - 13s 558ms/step - loss: 58.6166 - mae: 6.0465 - coeff_determination: 0.6408 Epoch 58/100 24/24 [==============================] - 14s 568ms/step - loss: 56.0955 - mae: 5.9443 - coeff_determination: 0.6548 Epoch 59/100 24/24 [==============================] - 13s 558ms/step - loss: 65.2508 - mae: 6.4151 - coeff_determination: 0.6031 Epoch 60/100 24/24 [==============================] - 13s 561ms/step - loss: 60.7987 - mae: 6.1865 - coeff_determination: 0.6244 Epoch 61/100 24/24 [==============================] - 13s 559ms/step - loss: 56.5023 - mae: 5.9721 - coeff_determination: 0.6500 Epoch 62/100 24/24 [==============================] - 14s 571ms/step - loss: 63.3025 - mae: 6.2890 - coeff_determination: 0.6123 Epoch 63/100 24/24 [==============================] - 13s 556ms/step - loss: 60.7650 - mae: 6.2591 - coeff_determination: 0.6153 Epoch 64/100 24/24 [==============================] - 13s 554ms/step - loss: 66.5197 - mae: 6.4951 - coeff_determination: 0.5896 Epoch 65/100 24/24 [==============================] - 14s 567ms/step - loss: 57.7542 - mae: 6.0692 - coeff_determination: 0.6421 Epoch 66/100 24/24 [==============================] - 13s 559ms/step - loss: 51.9207 - mae: 5.6892 - coeff_determination: 0.6790 Epoch 67/100 24/24 [==============================] - 14s 566ms/step - loss: 56.2244 - mae: 5.9350 - coeff_determination: 0.6562 Epoch 68/100 24/24 [==============================] - 13s 557ms/step - loss: 67.5080 - mae: 6.4815 - coeff_determination: 0.5858 Epoch 69/100 24/24 [==============================] - 13s 562ms/step - loss: 54.3223 - mae: 5.8546 - coeff_determination: 0.6656 Epoch 70/100 24/24 [==============================] - 13s 556ms/step - loss: 49.2176 - mae: 5.5483 - coeff_determination: 0.6968 Epoch 71/100 24/24 [==============================] - 14s 567ms/step - loss: 49.6234 - mae: 5.6467 - coeff_determination: 0.6865 Epoch 72/100 24/24 [==============================] - 14s 567ms/step - loss: 58.6433 - mae: 6.0596 - coeff_determination: 0.6442 Epoch 73/100 24/24 [==============================] - 13s 554ms/step - loss: 54.9162 - mae: 5.8795 - coeff_determination: 0.6648 Epoch 74/100 24/24 [==============================] - 13s 557ms/step - loss: 51.3651 - mae: 5.7289 - coeff_determination: 0.6791 Epoch 75/100 24/24 [==============================] - 13s 554ms/step - loss: 47.3033 - mae: 5.4892 - coeff_determination: 0.7049 Epoch 76/100 24/24 [==============================] - 14s 573ms/step - loss: 46.8704 - mae: 5.3867 - coeff_determination: 0.7111 Epoch 77/100 24/24 [==============================] - 13s 557ms/step - loss: 73.5117 - mae: 6.9758 - coeff_determination: 0.5412 Epoch 78/100 24/24 [==============================] - 13s 558ms/step - loss: 58.5556 - mae: 6.0767 - coeff_determination: 0.6415 Epoch 79/100 24/24 [==============================] - 13s 555ms/step - loss: 55.1858 - mae: 5.9063 - coeff_determination: 0.6619 Epoch 80/100 24/24 [==============================] - 14s 563ms/step - loss: 51.9686 - mae: 5.6948 - coeff_determination: 0.6816 Epoch 81/100 24/24 [==============================] - 14s 564ms/step - loss: 51.9255 - mae: 5.7185 - coeff_determination: 0.6833 Epoch 82/100 24/24 [==============================] - 13s 557ms/step - loss: 49.3878 - mae: 5.5627 - coeff_determination: 0.6950 Epoch 83/100 24/24 [==============================] - 13s 556ms/step - loss: 58.8007 - mae: 6.0525 - coeff_determination: 0.6469 Epoch 84/100 24/24 [==============================] - 13s 553ms/step - loss: 47.4369 - mae: 5.4238 - coeff_determination: 0.7108 Epoch 85/100 24/24 [==============================] - 13s 560ms/step - loss: 46.7652 - mae: 5.4130 - coeff_determination: 0.7081 Epoch 86/100 24/24 [==============================] - 14s 565ms/step - loss: 41.1738 - mae: 5.0609 - coeff_determination: 0.7461 Epoch 87/100 24/24 [==============================] - 13s 557ms/step - loss: 44.2818 - mae: 5.2721 - coeff_determination: 0.7254 Epoch 88/100 24/24 [==============================] - 13s 559ms/step - loss: 49.5031 - mae: 5.5655 - coeff_determination: 0.6980 Epoch 89/100 24/24 [==============================] - 13s 551ms/step - loss: 48.2639 - mae: 5.4574 - coeff_determination: 0.7042 Epoch 90/100 24/24 [==============================] - 13s 558ms/step - loss: 40.7611 - mae: 5.0543 - coeff_determination: 0.7473 Epoch 91/100 24/24 [==============================] - 14s 574ms/step - loss: 41.0846 - mae: 5.0488 - coeff_determination: 0.7472 Epoch 92/100 24/24 [==============================] - 13s 556ms/step - loss: 39.1620 - mae: 4.9758 - coeff_determination: 0.7588 Epoch 93/100 24/24 [==============================] - 14s 563ms/step - loss: 45.5177 - mae: 5.3946 - coeff_determination: 0.7178 Epoch 94/100 24/24 [==============================] - 13s 561ms/step - loss: 61.7304 - mae: 6.3221 - coeff_determination: 0.6193 Epoch 95/100 24/24 [==============================] - 14s 567ms/step - loss: 43.4926 - mae: 5.2049 - coeff_determination: 0.7328 Epoch 96/100 24/24 [==============================] - 13s 556ms/step - loss: 46.5659 - mae: 5.4080 - coeff_determination: 0.7120 Epoch 97/100 24/24 [==============================] - 14s 573ms/step - loss: 45.1703 - mae: 5.2954 - coeff_determination: 0.7261 Epoch 98/100 24/24 [==============================] - 13s 562ms/step - loss: 44.2005 - mae: 5.2717 - coeff_determination: 0.7241 Epoch 99/100 24/24 [==============================] - 13s 561ms/step - loss: 46.1151 - mae: 5.3460 - coeff_determination: 0.7166 Epoch 100/100 24/24 [==============================] - 14s 563ms/step - loss: 50.9457 - mae: 5.6311 - coeff_determination: 0.6888 ---------<TEST RESULTS FOR CLIENT client_2 ; USING LOCAL MODEL>----------- R^2 0.45038552601184345 Mean squared error 89.2555474094023 Mean absolute error 7.376016518004596 Huber loss 12.433490193488687 SCALING FACTOR : 0.5 ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 18s 765ms/step - loss: 699.8377 - mae: 21.3000 - coeff_determination: -3.2201 Epoch 2/100 24/24 [==============================] - 13s 562ms/step - loss: 346.2864 - mae: 14.8558 - coeff_determination: -1.1155 Epoch 3/100 24/24 [==============================] - 13s 555ms/step - loss: 279.2757 - mae: 13.3528 - coeff_determination: -0.7223 Epoch 4/100 24/24 [==============================] - 14s 564ms/step - loss: 246.8430 - mae: 12.5409 - coeff_determination: -0.5188 Epoch 5/100 24/24 [==============================] - 13s 555ms/step - loss: 220.1531 - mae: 11.9045 - coeff_determination: -0.3486 Epoch 6/100 24/24 [==============================] - 13s 556ms/step - loss: 201.9059 - mae: 11.4694 - coeff_determination: -0.2517 Epoch 7/100 24/24 [==============================] - 13s 554ms/step - loss: 194.3162 - mae: 11.1995 - coeff_determination: -0.1953 Epoch 8/100 24/24 [==============================] - 13s 557ms/step - loss: 167.2331 - mae: 10.4263 - coeff_determination: -0.0286 Epoch 9/100 24/24 [==============================] - 14s 563ms/step - loss: 161.0272 - mae: 10.1876 - coeff_determination: 0.0113 Epoch 10/100 24/24 [==============================] - 13s 562ms/step - loss: 153.6948 - mae: 10.0337 - coeff_determination: 0.0460 Epoch 11/100 24/24 [==============================] - 14s 565ms/step - loss: 139.8444 - mae: 9.5116 - coeff_determination: 0.1410 Epoch 12/100 24/24 [==============================] - 13s 560ms/step - loss: 134.0726 - mae: 9.3932 - coeff_determination: 0.1589 Epoch 13/100 24/24 [==============================] - 14s 577ms/step - loss: 132.0951 - mae: 9.2048 - coeff_determination: 0.1909 Epoch 14/100 24/24 [==============================] - 13s 557ms/step - loss: 125.7268 - mae: 9.0600 - coeff_determination: 0.2169 Epoch 15/100 24/24 [==============================] - 14s 603ms/step - loss: 115.0094 - mae: 8.6540 - coeff_determination: 0.2834 Epoch 16/100 24/24 [==============================] - 13s 560ms/step - loss: 110.6596 - mae: 8.4345 - coeff_determination: 0.3171 Epoch 17/100 24/24 [==============================] - 13s 555ms/step - loss: 111.0611 - mae: 8.4476 - coeff_determination: 0.3171 Epoch 18/100 24/24 [==============================] - 14s 567ms/step - loss: 113.3457 - mae: 8.5543 - coeff_determination: 0.3015 Epoch 19/100 24/24 [==============================] - 14s 565ms/step - loss: 119.6151 - mae: 8.8404 - coeff_determination: 0.2595 Epoch 20/100 24/24 [==============================] - 14s 565ms/step - loss: 108.2603 - mae: 8.3687 - coeff_determination: 0.3322 Epoch 21/100 24/24 [==============================] - 13s 558ms/step - loss: 126.8991 - mae: 9.0666 - coeff_determination: 0.2178 Epoch 22/100 24/24 [==============================] - 13s 561ms/step - loss: 129.7868 - mae: 9.1379 - coeff_determination: 0.2063 Epoch 23/100 24/24 [==============================] - 13s 557ms/step - loss: 99.8798 - mae: 7.9689 - coeff_determination: 0.3890 Epoch 24/100 24/24 [==============================] - 13s 555ms/step - loss: 94.2041 - mae: 7.7857 - coeff_determination: 0.4222 Epoch 25/100 24/24 [==============================] - 13s 557ms/step - loss: 91.1295 - mae: 7.6208 - coeff_determination: 0.4399 Epoch 26/100 24/24 [==============================] - 14s 563ms/step - loss: 83.6288 - mae: 7.3027 - coeff_determination: 0.4839 Epoch 27/100 24/24 [==============================] - 13s 562ms/step - loss: 92.4648 - mae: 7.7800 - coeff_determination: 0.4200 Epoch 28/100 24/24 [==============================] - 13s 558ms/step - loss: 86.7600 - mae: 7.4108 - coeff_determination: 0.4694 Epoch 29/100 24/24 [==============================] - 13s 560ms/step - loss: 82.0953 - mae: 7.2449 - coeff_determination: 0.4905 Epoch 30/100 24/24 [==============================] - 13s 560ms/step - loss: 84.9045 - mae: 7.3336 - coeff_determination: 0.4831 Epoch 31/100 24/24 [==============================] - 13s 557ms/step - loss: 84.0527 - mae: 7.3686 - coeff_determination: 0.4817 Epoch 32/100 24/24 [==============================] - 14s 568ms/step - loss: 82.0975 - mae: 7.2692 - coeff_determination: 0.4921 Epoch 33/100 24/24 [==============================] - 13s 562ms/step - loss: 78.1414 - mae: 7.0197 - coeff_determination: 0.5188 Epoch 34/100 24/24 [==============================] - 13s 555ms/step - loss: 75.9149 - mae: 7.0073 - coeff_determination: 0.5337 Epoch 35/100 24/24 [==============================] - 13s 562ms/step - loss: 77.9862 - mae: 7.1193 - coeff_determination: 0.5137 Epoch 36/100 24/24 [==============================] - 14s 567ms/step - loss: 75.4096 - mae: 6.9360 - coeff_determination: 0.5393 Epoch 37/100 24/24 [==============================] - 14s 572ms/step - loss: 75.0134 - mae: 6.9164 - coeff_determination: 0.5389 Epoch 38/100 24/24 [==============================] - 14s 568ms/step - loss: 71.9818 - mae: 6.7784 - coeff_determination: 0.5565 Epoch 39/100 24/24 [==============================] - 13s 562ms/step - loss: 99.1934 - mae: 7.9884 - coeff_determination: 0.3932 Epoch 40/100 24/24 [==============================] - 13s 561ms/step - loss: 86.0637 - mae: 7.4720 - coeff_determination: 0.4706 Epoch 41/100 24/24 [==============================] - 14s 567ms/step - loss: 70.0507 - mae: 6.6958 - coeff_determination: 0.5657 Epoch 42/100 24/24 [==============================] - 13s 559ms/step - loss: 66.2854 - mae: 6.5676 - coeff_determination: 0.5821 Epoch 43/100 24/24 [==============================] - 14s 564ms/step - loss: 67.1188 - mae: 6.5566 - coeff_determination: 0.5862 Epoch 44/100 24/24 [==============================] - 13s 561ms/step - loss: 67.0474 - mae: 6.5448 - coeff_determination: 0.5838 Epoch 45/100 24/24 [==============================] - 13s 557ms/step - loss: 80.9741 - mae: 7.3465 - coeff_determination: 0.4784 Epoch 46/100 24/24 [==============================] - 14s 566ms/step - loss: 72.2880 - mae: 6.8070 - coeff_determination: 0.5535 Epoch 47/100 24/24 [==============================] - 13s 562ms/step - loss: 66.9639 - mae: 6.5849 - coeff_determination: 0.5855 Epoch 48/100 24/24 [==============================] - 13s 559ms/step - loss: 58.7379 - mae: 6.1181 - coeff_determination: 0.6383 Epoch 49/100 24/24 [==============================] - 13s 561ms/step - loss: 57.4229 - mae: 6.0369 - coeff_determination: 0.6477 Epoch 50/100 24/24 [==============================] - 13s 559ms/step - loss: 76.6898 - mae: 6.9965 - coeff_determination: 0.5297 Epoch 51/100 24/24 [==============================] - 14s 565ms/step - loss: 72.7064 - mae: 6.8072 - coeff_determination: 0.5565 Epoch 52/100 24/24 [==============================] - 13s 559ms/step - loss: 62.1031 - mae: 6.2586 - coeff_determination: 0.6178 Epoch 53/100 24/24 [==============================] - 14s 566ms/step - loss: 74.7076 - mae: 6.9352 - coeff_determination: 0.5354 Epoch 54/100 24/24 [==============================] - 13s 559ms/step - loss: 63.4820 - mae: 6.3159 - coeff_determination: 0.6083 Epoch 55/100 24/24 [==============================] - 14s 573ms/step - loss: 58.4122 - mae: 6.0567 - coeff_determination: 0.6386 Epoch 56/100 24/24 [==============================] - 14s 567ms/step - loss: 55.5519 - mae: 5.9556 - coeff_determination: 0.6560 Epoch 57/100 24/24 [==============================] - 13s 561ms/step - loss: 62.9743 - mae: 6.3226 - coeff_determination: 0.6133 Epoch 58/100 24/24 [==============================] - 13s 559ms/step - loss: 57.9091 - mae: 6.0516 - coeff_determination: 0.6442 Epoch 59/100 24/24 [==============================] - 14s 573ms/step - loss: 53.5871 - mae: 5.8147 - coeff_determination: 0.6707 Epoch 60/100 24/24 [==============================] - 14s 573ms/step - loss: 50.8520 - mae: 5.6517 - coeff_determination: 0.6844 Epoch 61/100 24/24 [==============================] - 13s 562ms/step - loss: 54.6315 - mae: 5.8883 - coeff_determination: 0.6630 Epoch 62/100 24/24 [==============================] - 14s 563ms/step - loss: 57.2338 - mae: 6.0196 - coeff_determination: 0.6464 Epoch 63/100 24/24 [==============================] - 14s 577ms/step - loss: 51.3617 - mae: 5.6944 - coeff_determination: 0.6847 Epoch 64/100 24/24 [==============================] - 14s 572ms/step - loss: 51.6126 - mae: 5.7220 - coeff_determination: 0.6809 Epoch 65/100 24/24 [==============================] - 13s 557ms/step - loss: 55.5970 - mae: 5.9508 - coeff_determination: 0.6554 Epoch 66/100 24/24 [==============================] - 13s 559ms/step - loss: 52.2611 - mae: 5.7694 - coeff_determination: 0.6757 Epoch 67/100 24/24 [==============================] - 13s 561ms/step - loss: 47.2018 - mae: 5.4381 - coeff_determination: 0.7075 Epoch 68/100 24/24 [==============================] - 13s 558ms/step - loss: 53.1889 - mae: 5.7641 - coeff_determination: 0.6720 Epoch 69/100 24/24 [==============================] - 14s 564ms/step - loss: 61.6170 - mae: 6.2547 - coeff_determination: 0.6218 Epoch 70/100 24/24 [==============================] - 13s 556ms/step - loss: 48.2338 - mae: 5.5102 - coeff_determination: 0.7014 Epoch 71/100 24/24 [==============================] - 13s 558ms/step - loss: 46.2073 - mae: 5.4454 - coeff_determination: 0.7124 Epoch 72/100 24/24 [==============================] - 13s 556ms/step - loss: 54.6752 - mae: 5.9138 - coeff_determination: 0.6552 Epoch 73/100 24/24 [==============================] - 14s 568ms/step - loss: 76.4114 - mae: 6.9817 - coeff_determination: 0.5265 Epoch 74/100 24/24 [==============================] - 14s 566ms/step - loss: 49.2928 - mae: 5.5434 - coeff_determination: 0.6972 Epoch 75/100 24/24 [==============================] - 13s 561ms/step - loss: 74.3165 - mae: 6.9844 - coeff_determination: 0.5398 Epoch 76/100 24/24 [==============================] - 14s 574ms/step - loss: 67.5699 - mae: 6.6087 - coeff_determination: 0.5839 Epoch 77/100 24/24 [==============================] - 13s 559ms/step - loss: 46.7596 - mae: 5.4532 - coeff_determination: 0.7079 Epoch 78/100 24/24 [==============================] - 14s 566ms/step - loss: 61.4404 - mae: 6.2910 - coeff_determination: 0.6199 Epoch 79/100 24/24 [==============================] - 14s 567ms/step - loss: 66.6403 - mae: 6.4684 - coeff_determination: 0.5935 Epoch 80/100 24/24 [==============================] - 14s 563ms/step - loss: 64.0176 - mae: 6.3767 - coeff_determination: 0.6059 Epoch 81/100 24/24 [==============================] - 14s 571ms/step - loss: 45.5800 - mae: 5.3345 - coeff_determination: 0.7192 Epoch 82/100 24/24 [==============================] - 14s 569ms/step - loss: 42.2491 - mae: 5.1673 - coeff_determination: 0.7379 Epoch 83/100 24/24 [==============================] - 14s 566ms/step - loss: 43.0121 - mae: 5.2194 - coeff_determination: 0.7363 Epoch 84/100 24/24 [==============================] - 13s 559ms/step - loss: 40.6901 - mae: 5.0535 - coeff_determination: 0.7497 Epoch 85/100 24/24 [==============================] - 14s 566ms/step - loss: 49.3637 - mae: 5.5591 - coeff_determination: 0.6952 Epoch 86/100 24/24 [==============================] - 14s 564ms/step - loss: 43.4568 - mae: 5.2247 - coeff_determination: 0.7321 Epoch 87/100 24/24 [==============================] - 14s 575ms/step - loss: 44.6758 - mae: 5.2645 - coeff_determination: 0.7262 Epoch 88/100 24/24 [==============================] - 14s 569ms/step - loss: 45.4618 - mae: 5.3270 - coeff_determination: 0.7215 Epoch 89/100 24/24 [==============================] - 13s 558ms/step - loss: 42.7576 - mae: 5.1559 - coeff_determination: 0.7369 Epoch 90/100 24/24 [==============================] - 14s 565ms/step - loss: 40.8059 - mae: 5.0443 - coeff_determination: 0.7480 Epoch 91/100 24/24 [==============================] - 14s 572ms/step - loss: 46.3766 - mae: 5.4431 - coeff_determination: 0.7115 Epoch 92/100 24/24 [==============================] - 14s 568ms/step - loss: 41.4182 - mae: 5.0834 - coeff_determination: 0.7432 Epoch 93/100 24/24 [==============================] - 13s 560ms/step - loss: 48.2857 - mae: 5.5344 - coeff_determination: 0.7014 Epoch 94/100 24/24 [==============================] - 13s 558ms/step - loss: 62.7329 - mae: 6.3113 - coeff_determination: 0.6131 Epoch 95/100 24/24 [==============================] - 13s 558ms/step - loss: 56.6203 - mae: 5.9459 - coeff_determination: 0.6560 Epoch 96/100 24/24 [==============================] - 13s 558ms/step - loss: 41.6108 - mae: 5.1382 - coeff_determination: 0.7421 Epoch 97/100 24/24 [==============================] - 14s 580ms/step - loss: 43.8006 - mae: 5.2312 - coeff_determination: 0.7307 Epoch 98/100 24/24 [==============================] - 13s 560ms/step - loss: 48.9174 - mae: 5.5606 - coeff_determination: 0.6984 Epoch 99/100 24/24 [==============================] - 13s 562ms/step - loss: 47.1173 - mae: 5.4283 - coeff_determination: 0.7127 Epoch 100/100 24/24 [==============================] - 14s 568ms/step - loss: 42.6673 - mae: 5.1619 - coeff_determination: 0.7384 ---------<TEST RESULTS FOR CLIENT client_1 ; USING LOCAL MODEL>----------- R^2 0.406362364589821 Mean squared error 96.40476118993271 Mean absolute error 7.66770565521449 Huber loss 12.724429100888916 SCALING FACTOR : 0.5 --------<TEST RESULTS AFTER ROUND 0 ; USING GLOBAL MODEL>--------- R^2 -1.714 Mean squared error 440.672 Mean absolute error 18.943 Huber loss 20.111 ============================================================== ============================================================== ---------<STARTING TRAINING FOR ROUND 1>----------- ---------<STARTING TRAINING FOR CLIENT client_2>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 16s 656ms/step - loss: 537.4771 - mae: 17.9297 - coeff_determination: -2.3635 Epoch 2/100 24/24 [==============================] - 14s 583ms/step - loss: 136.2800 - mae: 9.4214 - coeff_determination: 0.1640 Epoch 3/100 24/24 [==============================] - 14s 584ms/step - loss: 104.9561 - mae: 8.2436 - coeff_determination: 0.3518 Epoch 4/100 24/24 [==============================] - 14s 574ms/step - loss: 90.8756 - mae: 7.5710 - coeff_determination: 0.4442 Epoch 5/100 24/24 [==============================] - 14s 568ms/step - loss: 87.7680 - mae: 7.5262 - coeff_determination: 0.4645 Epoch 6/100 24/24 [==============================] - 14s 572ms/step - loss: 75.1600 - mae: 6.9360 - coeff_determination: 0.5380 Epoch 7/100 24/24 [==============================] - 14s 566ms/step - loss: 71.1198 - mae: 6.7723 - coeff_determination: 0.5639 Epoch 8/100 24/24 [==============================] - 13s 561ms/step - loss: 67.4269 - mae: 6.5766 - coeff_determination: 0.5825 Epoch 9/100 24/24 [==============================] - 14s 572ms/step - loss: 65.3083 - mae: 6.4562 - coeff_determination: 0.5930 Epoch 10/100 24/24 [==============================] - 14s 569ms/step - loss: 60.7811 - mae: 6.2109 - coeff_determination: 0.6260 Epoch 11/100 24/24 [==============================] - 13s 562ms/step - loss: 61.8680 - mae: 6.2703 - coeff_determination: 0.6207 Epoch 12/100 24/24 [==============================] - 13s 561ms/step - loss: 58.2057 - mae: 6.0421 - coeff_determination: 0.6436 Epoch 13/100 24/24 [==============================] - 13s 560ms/step - loss: 61.1608 - mae: 6.2428 - coeff_determination: 0.6235 Epoch 14/100 24/24 [==============================] - 14s 580ms/step - loss: 62.4358 - mae: 6.3293 - coeff_determination: 0.6158 Epoch 15/100 24/24 [==============================] - 13s 560ms/step - loss: 58.0028 - mae: 6.0838 - coeff_determination: 0.6422 Epoch 16/100 24/24 [==============================] - 14s 568ms/step - loss: 57.9846 - mae: 6.0854 - coeff_determination: 0.6395 Epoch 17/100 24/24 [==============================] - 13s 561ms/step - loss: 57.4747 - mae: 6.0142 - coeff_determination: 0.6510 Epoch 18/100 24/24 [==============================] - 14s 563ms/step - loss: 66.9797 - mae: 6.5195 - coeff_determination: 0.5896 Epoch 19/100 24/24 [==============================] - 14s 573ms/step - loss: 54.9632 - mae: 5.8923 - coeff_determination: 0.6654 Epoch 20/100 24/24 [==============================] - 14s 563ms/step - loss: 55.7292 - mae: 5.9047 - coeff_determination: 0.6572 Epoch 21/100 24/24 [==============================] - 14s 565ms/step - loss: 55.3862 - mae: 5.8930 - coeff_determination: 0.6615 Epoch 22/100 24/24 [==============================] - 14s 573ms/step - loss: 54.2379 - mae: 5.8049 - coeff_determination: 0.6671 Epoch 23/100 24/24 [==============================] - 14s 563ms/step - loss: 50.2729 - mae: 5.6270 - coeff_determination: 0.6908 Epoch 24/100 24/24 [==============================] - 14s 571ms/step - loss: 49.3548 - mae: 5.6025 - coeff_determination: 0.6952 Epoch 25/100 24/24 [==============================] - 14s 566ms/step - loss: 50.2880 - mae: 5.6133 - coeff_determination: 0.6902 Epoch 26/100 24/24 [==============================] - 14s 576ms/step - loss: 73.1999 - mae: 6.8347 - coeff_determination: 0.5496 Epoch 27/100 24/24 [==============================] - 14s 563ms/step - loss: 56.6209 - mae: 5.9368 - coeff_determination: 0.6550 Epoch 28/100 24/24 [==============================] - 14s 589ms/step - loss: 50.4019 - mae: 5.6147 - coeff_determination: 0.6927 Epoch 29/100 24/24 [==============================] - 14s 568ms/step - loss: 51.3893 - mae: 5.6870 - coeff_determination: 0.6851 Epoch 30/100 24/24 [==============================] - 13s 561ms/step - loss: 53.1564 - mae: 5.8913 - coeff_determination: 0.6645 Epoch 31/100 24/24 [==============================] - 14s 566ms/step - loss: 65.1074 - mae: 6.3650 - coeff_determination: 0.6057 Epoch 32/100 24/24 [==============================] - 14s 571ms/step - loss: 47.8692 - mae: 5.4751 - coeff_determination: 0.7066 Epoch 33/100 24/24 [==============================] - 14s 569ms/step - loss: 56.9134 - mae: 6.0410 - coeff_determination: 0.6518 Epoch 34/100 24/24 [==============================] - 14s 565ms/step - loss: 45.3325 - mae: 5.3477 - coeff_determination: 0.7205 Epoch 35/100 24/24 [==============================] - 14s 564ms/step - loss: 55.5724 - mae: 5.9444 - coeff_determination: 0.6588 Epoch 36/100 24/24 [==============================] - 14s 563ms/step - loss: 49.8616 - mae: 5.6304 - coeff_determination: 0.6961 Epoch 37/100 24/24 [==============================] - 14s 572ms/step - loss: 62.4263 - mae: 6.3316 - coeff_determination: 0.6170 Epoch 38/100 24/24 [==============================] - 14s 567ms/step - loss: 47.3218 - mae: 5.4359 - coeff_determination: 0.7116 Epoch 39/100 24/24 [==============================] - 14s 563ms/step - loss: 42.6007 - mae: 5.1817 - coeff_determination: 0.7370 Epoch 40/100 24/24 [==============================] - 14s 564ms/step - loss: 49.6426 - mae: 5.5135 - coeff_determination: 0.6977 Epoch 41/100 24/24 [==============================] - 14s 568ms/step - loss: 43.9769 - mae: 5.2838 - coeff_determination: 0.7321 Epoch 42/100 24/24 [==============================] - 14s 578ms/step - loss: 39.2311 - mae: 4.9695 - coeff_determination: 0.7567 Epoch 43/100 24/24 [==============================] - 14s 569ms/step - loss: 42.4253 - mae: 5.1299 - coeff_determination: 0.7409 Epoch 44/100 24/24 [==============================] - 14s 564ms/step - loss: 44.4676 - mae: 5.2866 - coeff_determination: 0.7235 Epoch 45/100 24/24 [==============================] - 14s 566ms/step - loss: 49.0922 - mae: 5.4876 - coeff_determination: 0.7016 Epoch 46/100 24/24 [==============================] - 14s 578ms/step - loss: 46.5204 - mae: 5.4404 - coeff_determination: 0.7091 Epoch 47/100 24/24 [==============================] - 14s 570ms/step - loss: 52.3367 - mae: 5.8119 - coeff_determination: 0.6756 Epoch 48/100 24/24 [==============================] - 14s 565ms/step - loss: 55.8746 - mae: 5.9817 - coeff_determination: 0.6537 Epoch 49/100 24/24 [==============================] - 14s 573ms/step - loss: 40.1482 - mae: 5.0415 - coeff_determination: 0.7523 Epoch 50/100 24/24 [==============================] - 14s 565ms/step - loss: 40.8935 - mae: 5.0307 - coeff_determination: 0.7505 Epoch 51/100 24/24 [==============================] - 14s 572ms/step - loss: 35.7164 - mae: 4.7083 - coeff_determination: 0.7802 Epoch 52/100 24/24 [==============================] - 14s 574ms/step - loss: 36.9060 - mae: 4.7898 - coeff_determination: 0.7744 Epoch 53/100 24/24 [==============================] - 13s 562ms/step - loss: 41.1888 - mae: 5.0998 - coeff_determination: 0.7474 Epoch 54/100 24/24 [==============================] - 14s 564ms/step - loss: 54.6324 - mae: 5.8378 - coeff_determination: 0.6674 Epoch 55/100 24/24 [==============================] - 14s 565ms/step - loss: 59.6346 - mae: 6.1893 - coeff_determination: 0.6344 Epoch 56/100 24/24 [==============================] - 14s 569ms/step - loss: 51.3169 - mae: 5.7196 - coeff_determination: 0.6871 Epoch 57/100 24/24 [==============================] - 14s 573ms/step - loss: 43.6510 - mae: 5.2162 - coeff_determination: 0.7318 Epoch 58/100 24/24 [==============================] - 13s 560ms/step - loss: 39.1219 - mae: 4.9174 - coeff_determination: 0.7597 Epoch 59/100 24/24 [==============================] - 14s 569ms/step - loss: 36.0779 - mae: 4.7111 - coeff_determination: 0.7795 Epoch 60/100 24/24 [==============================] - 14s 573ms/step - loss: 36.3587 - mae: 4.7845 - coeff_determination: 0.7745 Epoch 61/100 24/24 [==============================] - 14s 569ms/step - loss: 42.3346 - mae: 5.1691 - coeff_determination: 0.7401 Epoch 62/100 24/24 [==============================] - 14s 564ms/step - loss: 53.7700 - mae: 5.8370 - coeff_determination: 0.6603 Epoch 63/100 24/24 [==============================] - 14s 564ms/step - loss: 44.1751 - mae: 5.2740 - coeff_determination: 0.7293 Epoch 64/100 24/24 [==============================] - 14s 564ms/step - loss: 40.4511 - mae: 5.0435 - coeff_determination: 0.7540 Epoch 65/100 24/24 [==============================] - 14s 570ms/step - loss: 42.2555 - mae: 5.2265 - coeff_determination: 0.7301 Epoch 66/100 24/24 [==============================] - 14s 564ms/step - loss: 42.2233 - mae: 5.1071 - coeff_determination: 0.7418 Epoch 67/100 24/24 [==============================] - 14s 563ms/step - loss: 52.3242 - mae: 5.7934 - coeff_determination: 0.6784 Epoch 68/100 24/24 [==============================] - 14s 580ms/step - loss: 48.5072 - mae: 5.5029 - coeff_determination: 0.7045 Epoch 69/100 24/24 [==============================] - 14s 570ms/step - loss: 38.4143 - mae: 4.8911 - coeff_determination: 0.7642 Epoch 70/100 24/24 [==============================] - 14s 574ms/step - loss: 55.9277 - mae: 5.8966 - coeff_determination: 0.6574 Epoch 71/100 24/24 [==============================] - 14s 578ms/step - loss: 45.8047 - mae: 5.3688 - coeff_determination: 0.7185 Epoch 72/100 24/24 [==============================] - 14s 566ms/step - loss: 39.9531 - mae: 5.0245 - coeff_determination: 0.7535 Epoch 73/100 24/24 [==============================] - 14s 568ms/step - loss: 42.9223 - mae: 5.2805 - coeff_determination: 0.7287 Epoch 74/100 24/24 [==============================] - 14s 567ms/step - loss: 63.9085 - mae: 6.4293 - coeff_determination: 0.6086 Epoch 75/100 24/24 [==============================] - 14s 569ms/step - loss: 56.6572 - mae: 5.9593 - coeff_determination: 0.6548 Epoch 76/100 24/24 [==============================] - 13s 562ms/step - loss: 37.0824 - mae: 4.8175 - coeff_determination: 0.7709 Epoch 77/100 24/24 [==============================] - 14s 565ms/step - loss: 41.8014 - mae: 5.2241 - coeff_determination: 0.7323 Epoch 78/100 24/24 [==============================] - 14s 566ms/step - loss: 52.3047 - mae: 5.7544 - coeff_determination: 0.6815 Epoch 79/100 24/24 [==============================] - 14s 574ms/step - loss: 37.2337 - mae: 4.8187 - coeff_determination: 0.7713 Epoch 80/100 24/24 [==============================] - 14s 563ms/step - loss: 32.4823 - mae: 4.4788 - coeff_determination: 0.8007 Epoch 81/100 24/24 [==============================] - 14s 564ms/step - loss: 33.6569 - mae: 4.5692 - coeff_determination: 0.7926 Epoch 82/100 24/24 [==============================] - 14s 565ms/step - loss: 31.1727 - mae: 4.4392 - coeff_determination: 0.8054 Epoch 83/100 24/24 [==============================] - 13s 561ms/step - loss: 34.8724 - mae: 4.7187 - coeff_determination: 0.7813 Epoch 84/100 24/24 [==============================] - 14s 569ms/step - loss: 39.2713 - mae: 4.9842 - coeff_determination: 0.7591 Epoch 85/100 24/24 [==============================] - 14s 565ms/step - loss: 39.8905 - mae: 5.0425 - coeff_determination: 0.7511 Epoch 86/100 24/24 [==============================] - 14s 563ms/step - loss: 55.0361 - mae: 6.0333 - coeff_determination: 0.6575 Epoch 87/100 24/24 [==============================] - 14s 566ms/step - loss: 45.1727 - mae: 5.3718 - coeff_determination: 0.7208 Epoch 88/100 24/24 [==============================] - 14s 571ms/step - loss: 35.6896 - mae: 4.7487 - coeff_determination: 0.7766 Epoch 89/100 24/24 [==============================] - 14s 565ms/step - loss: 34.1873 - mae: 4.6322 - coeff_determination: 0.7872 Epoch 90/100 24/24 [==============================] - 14s 570ms/step - loss: 31.9717 - mae: 4.4698 - coeff_determination: 0.8032 Epoch 91/100 24/24 [==============================] - 14s 569ms/step - loss: 34.1630 - mae: 4.6074 - coeff_determination: 0.7901 Epoch 92/100 24/24 [==============================] - 14s 566ms/step - loss: 33.9865 - mae: 4.6173 - coeff_determination: 0.7896 Epoch 93/100 24/24 [==============================] - 14s 579ms/step - loss: 38.8151 - mae: 4.9584 - coeff_determination: 0.7620 Epoch 94/100 24/24 [==============================] - 14s 596ms/step - loss: 37.0256 - mae: 4.8404 - coeff_determination: 0.7721 Epoch 95/100 24/24 [==============================] - 14s 570ms/step - loss: 36.0704 - mae: 4.7818 - coeff_determination: 0.7790 Epoch 96/100 24/24 [==============================] - 14s 568ms/step - loss: 41.8156 - mae: 5.1079 - coeff_determination: 0.7418 Epoch 97/100 24/24 [==============================] - 14s 563ms/step - loss: 50.2939 - mae: 5.6273 - coeff_determination: 0.6964 Epoch 98/100 24/24 [==============================] - 14s 570ms/step - loss: 39.2196 - mae: 5.0426 - coeff_determination: 0.7583 Epoch 99/100 24/24 [==============================] - 14s 566ms/step - loss: 34.3815 - mae: 4.6108 - coeff_determination: 0.7917 Epoch 100/100 24/24 [==============================] - 14s 566ms/step - loss: 33.7560 - mae: 4.5570 - coeff_determination: 0.7943 ---------<TEST RESULTS FOR CLIENT client_2 ; USING LOCAL MODEL>----------- R^2 0.482545568216178 Mean squared error 84.03286440611731 Mean absolute error 7.025532622724218 Huber loss 12.555097339318015 SCALING FACTOR : 0.5 ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 15s 618ms/step - loss: 545.9411 - mae: 18.4728 - coeff_determination: -2.4000 Epoch 2/100 24/24 [==============================] - 14s 572ms/step - loss: 145.6075 - mae: 9.7342 - coeff_determination: 0.1079 Epoch 3/100 24/24 [==============================] - 13s 562ms/step - loss: 108.0071 - mae: 8.4323 - coeff_determination: 0.3341 Epoch 4/100 24/24 [==============================] - 14s 564ms/step - loss: 87.6495 - mae: 7.5284 - coeff_determination: 0.4651 Epoch 5/100 24/24 [==============================] - 14s 564ms/step - loss: 77.0831 - mae: 7.0558 - coeff_determination: 0.5280 Epoch 6/100 24/24 [==============================] - 14s 564ms/step - loss: 67.7602 - mae: 6.6091 - coeff_determination: 0.5825 Epoch 7/100 24/24 [==============================] - 14s 567ms/step - loss: 62.9761 - mae: 6.3311 - coeff_determination: 0.6130 Epoch 8/100 24/24 [==============================] - 14s 563ms/step - loss: 60.5960 - mae: 6.1984 - coeff_determination: 0.6272 Epoch 9/100 24/24 [==============================] - 14s 563ms/step - loss: 62.9866 - mae: 6.3451 - coeff_determination: 0.6130 Epoch 10/100 24/24 [==============================] - 14s 565ms/step - loss: 61.7320 - mae: 6.2082 - coeff_determination: 0.6218 Epoch 11/100 24/24 [==============================] - 14s 570ms/step - loss: 57.8789 - mae: 6.0904 - coeff_determination: 0.6414 Epoch 12/100 24/24 [==============================] - 14s 575ms/step - loss: 76.1949 - mae: 6.9457 - coeff_determination: 0.5354 Epoch 13/100 24/24 [==============================] - 14s 572ms/step - loss: 58.8784 - mae: 6.1337 - coeff_determination: 0.6323 Epoch 14/100 24/24 [==============================] - 13s 561ms/step - loss: 56.5429 - mae: 5.9941 - coeff_determination: 0.6522 Epoch 15/100 24/24 [==============================] - 14s 567ms/step - loss: 56.8999 - mae: 5.9856 - coeff_determination: 0.6530 Epoch 16/100 24/24 [==============================] - 14s 587ms/step - loss: 46.2366 - mae: 5.4037 - coeff_determination: 0.7159 Epoch 17/100 24/24 [==============================] - 14s 568ms/step - loss: 54.8861 - mae: 5.8763 - coeff_determination: 0.6617 Epoch 18/100 24/24 [==============================] - 13s 562ms/step - loss: 62.9320 - mae: 6.4555 - coeff_determination: 0.6011 Epoch 19/100 24/24 [==============================] - 14s 571ms/step - loss: 60.6822 - mae: 6.1755 - coeff_determination: 0.6291 Epoch 20/100 24/24 [==============================] - 14s 567ms/step - loss: 48.9590 - mae: 5.5854 - coeff_determination: 0.6982 Epoch 21/100 24/24 [==============================] - 14s 567ms/step - loss: 51.2277 - mae: 5.6986 - coeff_determination: 0.6813 Epoch 22/100 24/24 [==============================] - 14s 567ms/step - loss: 63.4048 - mae: 6.4105 - coeff_determination: 0.6118 Epoch 23/100 24/24 [==============================] - 13s 561ms/step - loss: 53.0428 - mae: 5.7385 - coeff_determination: 0.6769 Epoch 24/100 24/24 [==============================] - 14s 566ms/step - loss: 45.8776 - mae: 5.4074 - coeff_determination: 0.7133 Epoch 25/100 24/24 [==============================] - 14s 571ms/step - loss: 48.4214 - mae: 5.5447 - coeff_determination: 0.7014 Epoch 26/100 24/24 [==============================] - 13s 562ms/step - loss: 52.5228 - mae: 5.7577 - coeff_determination: 0.6754 Epoch 27/100 24/24 [==============================] - 14s 568ms/step - loss: 43.7590 - mae: 5.2551 - coeff_determination: 0.7266 Epoch 28/100 24/24 [==============================] - 13s 560ms/step - loss: 45.9565 - mae: 5.3743 - coeff_determination: 0.7120 Epoch 29/100 24/24 [==============================] - 14s 568ms/step - loss: 46.2375 - mae: 5.3572 - coeff_determination: 0.7147 Epoch 30/100 24/24 [==============================] - 14s 584ms/step - loss: 43.0914 - mae: 5.1928 - coeff_determination: 0.7326 Epoch 31/100 24/24 [==============================] - 14s 591ms/step - loss: 50.4859 - mae: 5.6878 - coeff_determination: 0.6852 Epoch 32/100 24/24 [==============================] - 15s 606ms/step - loss: 65.9775 - mae: 6.5842 - coeff_determination: 0.5850 Epoch 33/100 24/24 [==============================] - 18s 733ms/step - loss: 46.0747 - mae: 5.3473 - coeff_determination: 0.7179 Epoch 34/100 24/24 [==============================] - 16s 687ms/step - loss: 43.6432 - mae: 5.2580 - coeff_determination: 0.7303 Epoch 35/100 24/24 [==============================] - 17s 695ms/step - loss: 53.3566 - mae: 5.8291 - coeff_determination: 0.6716 Epoch 36/100 24/24 [==============================] - 16s 653ms/step - loss: 45.4892 - mae: 5.3596 - coeff_determination: 0.7193 Epoch 37/100 24/24 [==============================] - 15s 644ms/step - loss: 40.1841 - mae: 5.0197 - coeff_determination: 0.7521 Epoch 38/100 24/24 [==============================] - 15s 622ms/step - loss: 38.4629 - mae: 4.9182 - coeff_determination: 0.7621 Epoch 39/100 24/24 [==============================] - 14s 594ms/step - loss: 41.2194 - mae: 5.0803 - coeff_determination: 0.7451 Epoch 40/100 24/24 [==============================] - 19s 791ms/step - loss: 52.1095 - mae: 5.7356 - coeff_determination: 0.6836 Epoch 41/100 24/24 [==============================] - 19s 798ms/step - loss: 41.2715 - mae: 5.1171 - coeff_determination: 0.7464 Epoch 42/100 24/24 [==============================] - 17s 697ms/step - loss: 52.0261 - mae: 5.7564 - coeff_determination: 0.6820 Epoch 43/100 24/24 [==============================] - 17s 708ms/step - loss: 47.3917 - mae: 5.4577 - coeff_determination: 0.7102 Epoch 44/100 24/24 [==============================] - 17s 722ms/step - loss: 40.6865 - mae: 5.0774 - coeff_determination: 0.7482 Epoch 45/100 24/24 [==============================] - 16s 662ms/step - loss: 38.9236 - mae: 4.9436 - coeff_determination: 0.7583 Epoch 46/100 24/24 [==============================] - 14s 588ms/step - loss: 40.0867 - mae: 4.9893 - coeff_determination: 0.7552 Epoch 47/100 24/24 [==============================] - 14s 564ms/step - loss: 56.8062 - mae: 6.0145 - coeff_determination: 0.6532 Epoch 48/100 24/24 [==============================] - 14s 595ms/step - loss: 47.8062 - mae: 5.4270 - coeff_determination: 0.7066 Epoch 49/100 24/24 [==============================] - 16s 671ms/step - loss: 40.4778 - mae: 5.0677 - coeff_determination: 0.7465 Epoch 50/100 24/24 [==============================] - 17s 719ms/step - loss: 43.8355 - mae: 5.2317 - coeff_determination: 0.7297 Epoch 51/100 24/24 [==============================] - 14s 585ms/step - loss: 39.2834 - mae: 4.9627 - coeff_determination: 0.7579 Epoch 52/100 24/24 [==============================] - 14s 595ms/step - loss: 34.3782 - mae: 4.6384 - coeff_determination: 0.7868 Epoch 53/100 24/24 [==============================] - 14s 595ms/step - loss: 34.9788 - mae: 4.6813 - coeff_determination: 0.7819 Epoch 54/100 24/24 [==============================] - 17s 695ms/step - loss: 43.9222 - mae: 5.2921 - coeff_determination: 0.7280 Epoch 55/100 24/24 [==============================] - 15s 622ms/step - loss: 61.0561 - mae: 6.2363 - coeff_determination: 0.6267 Epoch 56/100 24/24 [==============================] - 19s 783ms/step - loss: 42.6011 - mae: 5.1899 - coeff_determination: 0.7391 Epoch 57/100 24/24 [==============================] - 18s 746ms/step - loss: 40.2439 - mae: 5.0699 - coeff_determination: 0.7483 Epoch 58/100 24/24 [==============================] - 14s 603ms/step - loss: 37.7077 - mae: 4.8809 - coeff_determination: 0.7659 Epoch 59/100 24/24 [==============================] - 16s 683ms/step - loss: 36.6920 - mae: 4.8190 - coeff_determination: 0.7724 Epoch 60/100 24/24 [==============================] - 14s 574ms/step - loss: 37.4427 - mae: 4.8621 - coeff_determination: 0.7704 Epoch 61/100 24/24 [==============================] - 15s 610ms/step - loss: 35.8232 - mae: 4.7498 - coeff_determination: 0.7754 Epoch 62/100 24/24 [==============================] - 14s 586ms/step - loss: 35.9207 - mae: 4.7554 - coeff_determination: 0.7787 Epoch 63/100 24/24 [==============================] - 14s 582ms/step - loss: 37.4438 - mae: 4.8297 - coeff_determination: 0.7683 Epoch 64/100 24/24 [==============================] - 13s 546ms/step - loss: 36.3515 - mae: 4.8090 - coeff_determination: 0.7707 Epoch 65/100 24/24 [==============================] - 13s 544ms/step - loss: 39.2431 - mae: 4.9387 - coeff_determination: 0.7587 Epoch 66/100 24/24 [==============================] - 13s 540ms/step - loss: 43.5379 - mae: 5.2521 - coeff_determination: 0.7309 Epoch 67/100 24/24 [==============================] - 13s 545ms/step - loss: 42.9499 - mae: 5.2162 - coeff_determination: 0.7370 Epoch 68/100 24/24 [==============================] - 13s 546ms/step - loss: 33.7855 - mae: 4.6249 - coeff_determination: 0.7923 Epoch 69/100 24/24 [==============================] - 16s 659ms/step - loss: 35.6318 - mae: 4.7271 - coeff_determination: 0.7794 Epoch 70/100 24/24 [==============================] - 15s 614ms/step - loss: 50.1619 - mae: 5.6150 - coeff_determination: 0.6937 Epoch 71/100 24/24 [==============================] - 14s 600ms/step - loss: 38.2332 - mae: 4.9455 - coeff_determination: 0.7633 Epoch 72/100 24/24 [==============================] - 14s 580ms/step - loss: 32.8553 - mae: 4.5091 - coeff_determination: 0.7985 Epoch 73/100 24/24 [==============================] - 15s 621ms/step - loss: 36.3326 - mae: 4.7647 - coeff_determination: 0.7769 Epoch 74/100 24/24 [==============================] - 15s 622ms/step - loss: 46.1152 - mae: 5.3731 - coeff_determination: 0.7186 Epoch 75/100 24/24 [==============================] - 15s 616ms/step - loss: 37.3895 - mae: 4.8529 - coeff_determination: 0.7671 Epoch 76/100 24/24 [==============================] - 14s 600ms/step - loss: 33.8630 - mae: 4.5653 - coeff_determination: 0.7921 Epoch 77/100 24/24 [==============================] - 15s 613ms/step - loss: 40.5823 - mae: 5.0621 - coeff_determination: 0.7484 Epoch 78/100 24/24 [==============================] - 14s 584ms/step - loss: 39.6204 - mae: 4.9652 - coeff_determination: 0.7578 Epoch 79/100 24/24 [==============================] - 15s 605ms/step - loss: 33.9230 - mae: 4.6145 - coeff_determination: 0.7895 Epoch 80/100 24/24 [==============================] - 14s 604ms/step - loss: 36.7407 - mae: 4.7832 - coeff_determination: 0.7745 Epoch 81/100 24/24 [==============================] - 13s 540ms/step - loss: 39.1562 - mae: 5.0212 - coeff_determination: 0.7569 Epoch 82/100 24/24 [==============================] - 13s 554ms/step - loss: 33.9642 - mae: 4.6426 - coeff_determination: 0.7880 Epoch 83/100 24/24 [==============================] - 14s 577ms/step - loss: 34.7475 - mae: 4.6973 - coeff_determination: 0.7814 Epoch 84/100 24/24 [==============================] - 13s 541ms/step - loss: 39.9146 - mae: 5.0274 - coeff_determination: 0.7524 Epoch 85/100 24/24 [==============================] - 14s 584ms/step - loss: 44.1041 - mae: 5.3263 - coeff_determination: 0.7258 Epoch 86/100 24/24 [==============================] - 16s 660ms/step - loss: 50.3346 - mae: 5.6976 - coeff_determination: 0.6800 Epoch 87/100 24/24 [==============================] - 16s 654ms/step - loss: 42.7625 - mae: 5.1689 - coeff_determination: 0.7369 Epoch 88/100 24/24 [==============================] - 16s 651ms/step - loss: 33.6605 - mae: 4.6098 - coeff_determination: 0.7897 Epoch 89/100 24/24 [==============================] - 14s 600ms/step - loss: 45.1377 - mae: 5.4625 - coeff_determination: 0.7107 Epoch 90/100 24/24 [==============================] - 14s 589ms/step - loss: 68.5184 - mae: 6.7087 - coeff_determination: 0.5771 Epoch 91/100 24/24 [==============================] - 14s 570ms/step - loss: 37.4705 - mae: 4.8327 - coeff_determination: 0.7707 Epoch 92/100 24/24 [==============================] - 14s 573ms/step - loss: 42.7464 - mae: 5.2068 - coeff_determination: 0.7390 Epoch 93/100 24/24 [==============================] - 14s 573ms/step - loss: 41.9122 - mae: 5.1457 - coeff_determination: 0.7428 Epoch 94/100 24/24 [==============================] - 14s 583ms/step - loss: 32.8664 - mae: 4.5285 - coeff_determination: 0.7952 Epoch 95/100 24/24 [==============================] - 14s 577ms/step - loss: 45.2379 - mae: 5.3470 - coeff_determination: 0.7256 Epoch 96/100 24/24 [==============================] - 14s 565ms/step - loss: 32.5724 - mae: 4.5392 - coeff_determination: 0.7993 Epoch 97/100 24/24 [==============================] - 14s 580ms/step - loss: 38.2933 - mae: 4.9151 - coeff_determination: 0.7647 Epoch 98/100 24/24 [==============================] - 14s 571ms/step - loss: 31.8788 - mae: 4.4872 - coeff_determination: 0.8031 Epoch 99/100 24/24 [==============================] - 14s 574ms/step - loss: 37.3455 - mae: 4.8572 - coeff_determination: 0.7670 Epoch 100/100 24/24 [==============================] - 14s 571ms/step - loss: 33.9425 - mae: 4.5805 - coeff_determination: 0.7922 ---------<TEST RESULTS FOR CLIENT client_1 ; USING LOCAL MODEL>----------- R^2 0.3444732880346729 Mean squared error 106.45533967362668 Mean absolute error 8.01487638927819 Huber loss 13.245920631346657 SCALING FACTOR : 0.5 --------<TEST RESULTS AFTER ROUND 1 ; USING GLOBAL MODEL>--------- R^2 0.288 Mean squared error 115.678 Mean absolute error 8.746 Huber loss 13.345 ============================================================== ============================================================== ---------<STARTING TRAINING FOR ROUND 2>----------- ---------<STARTING TRAINING FOR CLIENT client_2>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 19s 798ms/step - loss: 1174.4077 - mae: 27.0728 - coeff_determination: -6.3737 Epoch 2/100 24/24 [==============================] - 15s 618ms/step - loss: 148.8867 - mae: 9.8263 - coeff_determination: 0.0825 Epoch 3/100 24/24 [==============================] - 16s 655ms/step - loss: 119.2245 - mae: 8.7649 - coeff_determination: 0.2687 Epoch 4/100 24/24 [==============================] - 15s 639ms/step - loss: 108.1891 - mae: 8.3972 - coeff_determination: 0.3320 Epoch 5/100 24/24 [==============================] - 14s 568ms/step - loss: 98.6630 - mae: 7.9696 - coeff_determination: 0.3937 Epoch 6/100 24/24 [==============================] - 16s 686ms/step - loss: 86.3969 - mae: 7.4170 - coeff_determination: 0.4704 Epoch 7/100 24/24 [==============================] - 14s 602ms/step - loss: 79.2152 - mae: 7.1932 - coeff_determination: 0.5116 Epoch 8/100 24/24 [==============================] - 17s 698ms/step - loss: 69.7429 - mae: 6.6637 - coeff_determination: 0.5698 Epoch 9/100 24/24 [==============================] - 16s 649ms/step - loss: 69.0966 - mae: 6.6641 - coeff_determination: 0.5746 Epoch 10/100 24/24 [==============================] - 14s 572ms/step - loss: 66.2579 - mae: 6.5664 - coeff_determination: 0.5867 Epoch 11/100 24/24 [==============================] - 16s 676ms/step - loss: 61.0535 - mae: 6.2978 - coeff_determination: 0.6129 Epoch 12/100 24/24 [==============================] - 14s 584ms/step - loss: 60.7027 - mae: 6.2600 - coeff_determination: 0.6216 Epoch 13/100 24/24 [==============================] - 15s 605ms/step - loss: 58.8285 - mae: 6.1289 - coeff_determination: 0.6381 Epoch 14/100 24/24 [==============================] - 14s 595ms/step - loss: 71.5050 - mae: 6.7400 - coeff_determination: 0.5611 Epoch 15/100 24/24 [==============================] - 14s 563ms/step - loss: 56.5920 - mae: 5.9774 - coeff_determination: 0.6519 Epoch 16/100 24/24 [==============================] - 13s 550ms/step - loss: 52.1846 - mae: 5.7616 - coeff_determination: 0.6758 Epoch 17/100 24/24 [==============================] - 14s 571ms/step - loss: 50.3746 - mae: 5.6165 - coeff_determination: 0.6917 Epoch 18/100 24/24 [==============================] - 14s 603ms/step - loss: 78.5968 - mae: 7.0518 - coeff_determination: 0.5199 Epoch 19/100 24/24 [==============================] - 14s 583ms/step - loss: 60.6540 - mae: 6.1444 - coeff_determination: 0.6329 Epoch 20/100 24/24 [==============================] - 14s 603ms/step - loss: 54.4609 - mae: 5.8617 - coeff_determination: 0.6664 Epoch 21/100 24/24 [==============================] - 16s 648ms/step - loss: 55.7908 - mae: 5.9842 - coeff_determination: 0.6540 Epoch 22/100 24/24 [==============================] - 14s 565ms/step - loss: 50.1740 - mae: 5.6224 - coeff_determination: 0.6901 Epoch 23/100 24/24 [==============================] - 14s 594ms/step - loss: 46.7167 - mae: 5.4213 - coeff_determination: 0.7131 Epoch 24/100 24/24 [==============================] - 14s 567ms/step - loss: 44.5747 - mae: 5.2884 - coeff_determination: 0.7254 Epoch 25/100 24/24 [==============================] - 13s 551ms/step - loss: 52.4337 - mae: 5.7151 - coeff_determination: 0.6771 Epoch 26/100 24/24 [==============================] - 13s 543ms/step - loss: 48.6880 - mae: 5.5465 - coeff_determination: 0.7007 Epoch 27/100 24/24 [==============================] - 13s 549ms/step - loss: 50.3802 - mae: 5.7141 - coeff_determination: 0.6790 Epoch 28/100 24/24 [==============================] - 13s 545ms/step - loss: 48.3335 - mae: 5.5020 - coeff_determination: 0.7038 Epoch 29/100 24/24 [==============================] - 13s 541ms/step - loss: 43.2643 - mae: 5.2046 - coeff_determination: 0.7343 Epoch 30/100 24/24 [==============================] - 13s 547ms/step - loss: 40.8621 - mae: 5.0708 - coeff_determination: 0.7488 Epoch 31/100 24/24 [==============================] - 13s 541ms/step - loss: 44.9081 - mae: 5.3248 - coeff_determination: 0.7234 Epoch 32/100 24/24 [==============================] - 13s 543ms/step - loss: 47.1914 - mae: 5.4522 - coeff_determination: 0.7128 Epoch 33/100 24/24 [==============================] - 13s 545ms/step - loss: 40.5209 - mae: 5.0653 - coeff_determination: 0.7471 Epoch 34/100 24/24 [==============================] - 13s 543ms/step - loss: 43.6116 - mae: 5.2285 - coeff_determination: 0.7305 Epoch 35/100 24/24 [==============================] - 14s 567ms/step - loss: 45.2657 - mae: 5.4618 - coeff_determination: 0.7073 Epoch 36/100 24/24 [==============================] - 13s 549ms/step - loss: 79.4435 - mae: 7.1014 - coeff_determination: 0.5193 Epoch 37/100 24/24 [==============================] - 13s 555ms/step - loss: 50.5312 - mae: 5.6466 - coeff_determination: 0.6888 Epoch 38/100 24/24 [==============================] - 14s 601ms/step - loss: 41.8824 - mae: 5.1242 - coeff_determination: 0.7431 Epoch 39/100 24/24 [==============================] - 13s 547ms/step - loss: 41.0010 - mae: 5.0446 - coeff_determination: 0.7497 Epoch 40/100 24/24 [==============================] - 13s 557ms/step - loss: 42.0472 - mae: 5.1872 - coeff_determination: 0.7379 Epoch 41/100 24/24 [==============================] - 13s 539ms/step - loss: 44.5904 - mae: 5.3014 - coeff_determination: 0.7254 Epoch 42/100 24/24 [==============================] - 13s 545ms/step - loss: 38.1725 - mae: 4.9218 - coeff_determination: 0.7643 Epoch 43/100 24/24 [==============================] - 13s 554ms/step - loss: 38.6398 - mae: 4.9012 - coeff_determination: 0.7627 Epoch 44/100 24/24 [==============================] - 13s 561ms/step - loss: 52.4668 - mae: 5.7417 - coeff_determination: 0.6758 Epoch 45/100 24/24 [==============================] - 13s 546ms/step - loss: 42.3481 - mae: 5.1668 - coeff_determination: 0.7393 Epoch 46/100 24/24 [==============================] - 13s 548ms/step - loss: 42.1631 - mae: 5.1849 - coeff_determination: 0.7396 Epoch 47/100 24/24 [==============================] - 13s 541ms/step - loss: 37.5658 - mae: 4.8617 - coeff_determination: 0.7685 Epoch 48/100 24/24 [==============================] - 13s 545ms/step - loss: 36.7717 - mae: 4.7939 - coeff_determination: 0.7730 Epoch 49/100 24/24 [==============================] - 13s 545ms/step - loss: 35.2387 - mae: 4.7174 - coeff_determination: 0.7810 Epoch 50/100 24/24 [==============================] - 13s 544ms/step - loss: 36.2900 - mae: 4.7955 - coeff_determination: 0.7751 Epoch 51/100 24/24 [==============================] - 13s 544ms/step - loss: 35.2685 - mae: 4.6960 - coeff_determination: 0.7831 Epoch 52/100 24/24 [==============================] - 13s 550ms/step - loss: 59.7703 - mae: 6.1332 - coeff_determination: 0.6308 Epoch 53/100 24/24 [==============================] - 13s 547ms/step - loss: 54.8909 - mae: 5.8632 - coeff_determination: 0.6654 Epoch 54/100 24/24 [==============================] - 13s 547ms/step - loss: 39.0674 - mae: 4.9258 - coeff_determination: 0.7618 Epoch 55/100 24/24 [==============================] - 13s 558ms/step - loss: 41.3913 - mae: 5.1988 - coeff_determination: 0.7326 Epoch 56/100 24/24 [==============================] - 13s 542ms/step - loss: 42.2893 - mae: 5.1692 - coeff_determination: 0.7383 Epoch 57/100 24/24 [==============================] - 13s 547ms/step - loss: 35.9434 - mae: 4.7181 - coeff_determination: 0.7798 Epoch 58/100 24/24 [==============================] - 13s 552ms/step - loss: 32.4031 - mae: 4.4907 - coeff_determination: 0.7991 Epoch 59/100 24/24 [==============================] - 13s 554ms/step - loss: 40.7075 - mae: 5.1921 - coeff_determination: 0.7328 Epoch 60/100 24/24 [==============================] - 13s 547ms/step - loss: 54.8588 - mae: 5.9242 - coeff_determination: 0.6602 Epoch 61/100 24/24 [==============================] - 13s 545ms/step - loss: 50.6277 - mae: 5.6247 - coeff_determination: 0.6900 Epoch 62/100 24/24 [==============================] - 13s 560ms/step - loss: 36.4156 - mae: 4.8120 - coeff_determination: 0.7734 Epoch 63/100 24/24 [==============================] - 13s 547ms/step - loss: 41.0081 - mae: 5.0555 - coeff_determination: 0.7482 Epoch 64/100 24/24 [==============================] - 13s 550ms/step - loss: 35.0756 - mae: 4.6926 - coeff_determination: 0.7859 Epoch 65/100 24/24 [==============================] - 13s 541ms/step - loss: 68.6810 - mae: 6.5738 - coeff_determination: 0.5888 Epoch 66/100 24/24 [==============================] - 13s 552ms/step - loss: 47.3895 - mae: 5.5233 - coeff_determination: 0.7051 Epoch 67/100 24/24 [==============================] - 13s 543ms/step - loss: 39.2661 - mae: 4.9560 - coeff_determination: 0.7579 Epoch 68/100 24/24 [==============================] - 13s 553ms/step - loss: 49.1859 - mae: 5.6210 - coeff_determination: 0.6961 Epoch 69/100 24/24 [==============================] - 13s 547ms/step - loss: 46.0070 - mae: 5.3809 - coeff_determination: 0.7184 Epoch 70/100 24/24 [==============================] - 13s 545ms/step - loss: 33.8239 - mae: 4.5802 - coeff_determination: 0.7917 Epoch 71/100 24/24 [==============================] - 13s 549ms/step - loss: 39.1629 - mae: 4.9541 - coeff_determination: 0.7602 Epoch 72/100 24/24 [==============================] - 13s 544ms/step - loss: 35.6393 - mae: 4.7290 - coeff_determination: 0.7819 Epoch 73/100 24/24 [==============================] - 13s 547ms/step - loss: 34.8496 - mae: 4.6976 - coeff_determination: 0.7840 Epoch 74/100 24/24 [==============================] - 13s 550ms/step - loss: 35.2743 - mae: 4.6924 - coeff_determination: 0.7838 Epoch 75/100 24/24 [==============================] - 13s 546ms/step - loss: 38.7579 - mae: 4.9083 - coeff_determination: 0.7642 Epoch 76/100 24/24 [==============================] - 13s 545ms/step - loss: 29.4470 - mae: 4.2627 - coeff_determination: 0.8174 Epoch 77/100 24/24 [==============================] - 13s 548ms/step - loss: 30.8307 - mae: 4.3793 - coeff_determination: 0.8098 Epoch 78/100 24/24 [==============================] - 13s 546ms/step - loss: 42.4887 - mae: 5.1624 - coeff_determination: 0.7362 Epoch 79/100 24/24 [==============================] - 13s 546ms/step - loss: 37.8681 - mae: 4.8590 - coeff_determination: 0.7703 Epoch 80/100 24/24 [==============================] - 13s 551ms/step - loss: 36.1088 - mae: 4.7351 - coeff_determination: 0.7786 Epoch 81/100 24/24 [==============================] - 13s 546ms/step - loss: 43.3007 - mae: 5.2097 - coeff_determination: 0.7322 Epoch 82/100 24/24 [==============================] - 13s 548ms/step - loss: 38.3661 - mae: 4.8978 - coeff_determination: 0.7648 Epoch 83/100 24/24 [==============================] - 15s 613ms/step - loss: 35.9656 - mae: 4.7638 - coeff_determination: 0.7782 Epoch 84/100 24/24 [==============================] - 14s 596ms/step - loss: 36.0389 - mae: 4.7723 - coeff_determination: 0.7745 Epoch 85/100 24/24 [==============================] - 14s 603ms/step - loss: 40.1839 - mae: 5.0341 - coeff_determination: 0.7554 Epoch 86/100 24/24 [==============================] - 14s 580ms/step - loss: 45.5318 - mae: 5.4461 - coeff_determination: 0.7182 Epoch 87/100 24/24 [==============================] - 14s 578ms/step - loss: 34.6397 - mae: 4.6606 - coeff_determination: 0.7892 Epoch 88/100 24/24 [==============================] - 14s 576ms/step - loss: 31.9764 - mae: 4.4969 - coeff_determination: 0.8029 Epoch 89/100 24/24 [==============================] - 14s 574ms/step - loss: 33.3526 - mae: 4.5576 - coeff_determination: 0.7937 Epoch 90/100 24/24 [==============================] - 14s 573ms/step - loss: 29.9725 - mae: 4.3085 - coeff_determination: 0.8150 Epoch 91/100 24/24 [==============================] - 14s 598ms/step - loss: 31.2265 - mae: 4.3795 - coeff_determination: 0.8079 Epoch 92/100 24/24 [==============================] - 14s 570ms/step - loss: 31.1116 - mae: 4.4121 - coeff_determination: 0.8095 Epoch 93/100 24/24 [==============================] - 14s 574ms/step - loss: 33.2310 - mae: 4.5329 - coeff_determination: 0.7965 Epoch 94/100 24/24 [==============================] - 14s 585ms/step - loss: 28.5876 - mae: 4.2096 - coeff_determination: 0.8245 Epoch 95/100 24/24 [==============================] - 14s 572ms/step - loss: 31.4475 - mae: 4.4596 - coeff_determination: 0.8047 Epoch 96/100 24/24 [==============================] - 14s 584ms/step - loss: 40.2228 - mae: 5.0898 - coeff_determination: 0.7455 Epoch 97/100 24/24 [==============================] - 14s 577ms/step - loss: 65.1875 - mae: 6.4942 - coeff_determination: 0.5983 Epoch 98/100 24/24 [==============================] - 14s 575ms/step - loss: 34.2815 - mae: 4.6734 - coeff_determination: 0.7856 Epoch 99/100 24/24 [==============================] - 14s 575ms/step - loss: 33.5146 - mae: 4.5596 - coeff_determination: 0.7945 Epoch 100/100 24/24 [==============================] - 14s 584ms/step - loss: 36.9996 - mae: 4.8964 - coeff_determination: 0.7627 ---------<TEST RESULTS FOR CLIENT client_2 ; USING LOCAL MODEL>----------- R^2 0.4855842596234714 Mean squared error 83.53939111201325 Mean absolute error 7.166759803575582 Huber loss 12.811988372425846 SCALING FACTOR : 0.5 ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 16s 670ms/step - loss: 1141.5711 - mae: 26.4209 - coeff_determination: -6.1255 Epoch 2/100 24/24 [==============================] - 14s 579ms/step - loss: 152.8567 - mae: 10.0136 - coeff_determination: 0.0568 Epoch 3/100 24/24 [==============================] - 14s 575ms/step - loss: 124.1517 - mae: 9.0166 - coeff_determination: 0.2316 Epoch 4/100 24/24 [==============================] - 14s 584ms/step - loss: 104.1374 - mae: 8.1772 - coeff_determination: 0.3615 Epoch 5/100 24/24 [==============================] - 14s 577ms/step - loss: 99.4276 - mae: 8.0553 - coeff_determination: 0.3866 Epoch 6/100 24/24 [==============================] - 14s 578ms/step - loss: 87.6220 - mae: 7.4871 - coeff_determination: 0.4632 Epoch 7/100 24/24 [==============================] - 14s 574ms/step - loss: 82.6900 - mae: 7.2835 - coeff_determination: 0.4888 Epoch 8/100 24/24 [==============================] - 14s 577ms/step - loss: 70.7269 - mae: 6.6759 - coeff_determination: 0.5656 Epoch 9/100 24/24 [==============================] - 14s 581ms/step - loss: 79.1898 - mae: 7.0817 - coeff_determination: 0.5147 Epoch 10/100 24/24 [==============================] - 14s 576ms/step - loss: 68.8601 - mae: 6.6645 - coeff_determination: 0.5710 Epoch 11/100 24/24 [==============================] - 14s 573ms/step - loss: 72.3992 - mae: 6.8385 - coeff_determination: 0.5534 Epoch 12/100 24/24 [==============================] - 14s 580ms/step - loss: 75.2127 - mae: 6.9623 - coeff_determination: 0.5414 Epoch 13/100 24/24 [==============================] - 14s 576ms/step - loss: 56.5393 - mae: 6.0092 - coeff_determination: 0.6509 Epoch 14/100 24/24 [==============================] - 13s 528ms/step - loss: 52.6820 - mae: 5.7920 - coeff_determination: 0.6746 Epoch 15/100 24/24 [==============================] - 13s 534ms/step - loss: 53.4076 - mae: 5.8180 - coeff_determination: 0.6691 Epoch 16/100 24/24 [==============================] - 14s 579ms/step - loss: 50.5588 - mae: 5.6710 - coeff_determination: 0.6898 Epoch 17/100 24/24 [==============================] - 14s 574ms/step - loss: 55.4182 - mae: 5.9867 - coeff_determination: 0.6516 Epoch 18/100 24/24 [==============================] - 14s 576ms/step - loss: 52.5030 - mae: 5.7410 - coeff_determination: 0.6782 Epoch 19/100 24/24 [==============================] - 14s 575ms/step - loss: 55.6697 - mae: 5.9356 - coeff_determination: 0.6566 Epoch 20/100 24/24 [==============================] - 14s 576ms/step - loss: 57.5836 - mae: 6.0625 - coeff_determination: 0.6445 Epoch 21/100 24/24 [==============================] - 14s 572ms/step - loss: 46.6851 - mae: 5.4169 - coeff_determination: 0.7108 Epoch 22/100 24/24 [==============================] - 14s 577ms/step - loss: 60.0677 - mae: 6.1720 - coeff_determination: 0.6369 Epoch 23/100 24/24 [==============================] - 14s 600ms/step - loss: 44.9119 - mae: 5.3483 - coeff_determination: 0.7221 Epoch 24/100 24/24 [==============================] - 14s 575ms/step - loss: 49.8125 - mae: 5.6069 - coeff_determination: 0.6955 Epoch 25/100 24/24 [==============================] - 14s 588ms/step - loss: 52.1567 - mae: 5.7469 - coeff_determination: 0.6781 Epoch 26/100 24/24 [==============================] - 14s 582ms/step - loss: 42.7896 - mae: 5.1730 - coeff_determination: 0.7352 Epoch 27/100 24/24 [==============================] - 14s 582ms/step - loss: 42.5707 - mae: 5.1862 - coeff_determination: 0.7371 Epoch 28/100 24/24 [==============================] - 14s 584ms/step - loss: 51.6433 - mae: 5.7339 - coeff_determination: 0.6788 Epoch 29/100 24/24 [==============================] - 14s 589ms/step - loss: 47.4561 - mae: 5.4626 - coeff_determination: 0.7065 Epoch 30/100 24/24 [==============================] - 14s 574ms/step - loss: 40.3901 - mae: 5.0555 - coeff_determination: 0.7509 Epoch 31/100 24/24 [==============================] - 14s 577ms/step - loss: 56.4542 - mae: 6.0345 - coeff_determination: 0.6518 Epoch 32/100 24/24 [==============================] - 14s 577ms/step - loss: 48.7929 - mae: 5.5343 - coeff_determination: 0.6972 Epoch 33/100 24/24 [==============================] - 14s 578ms/step - loss: 42.0081 - mae: 5.1625 - coeff_determination: 0.7419 Epoch 34/100 24/24 [==============================] - 14s 587ms/step - loss: 40.0510 - mae: 5.0500 - coeff_determination: 0.7492 Epoch 35/100 24/24 [==============================] - 14s 587ms/step - loss: 38.7021 - mae: 4.9186 - coeff_determination: 0.7600 Epoch 36/100 24/24 [==============================] - 14s 577ms/step - loss: 51.2331 - mae: 5.6978 - coeff_determination: 0.6842 Epoch 37/100 24/24 [==============================] - 14s 577ms/step - loss: 41.8790 - mae: 5.1669 - coeff_determination: 0.7407 Epoch 38/100 24/24 [==============================] - 14s 579ms/step - loss: 42.4045 - mae: 5.1965 - coeff_determination: 0.7363 Epoch 39/100 24/24 [==============================] - 14s 573ms/step - loss: 36.5002 - mae: 4.8098 - coeff_determination: 0.7725 Epoch 40/100 24/24 [==============================] - 14s 578ms/step - loss: 37.4473 - mae: 4.8746 - coeff_determination: 0.7666 Epoch 41/100 24/24 [==============================] - 14s 577ms/step - loss: 39.0919 - mae: 4.9473 - coeff_determination: 0.7598 Epoch 42/100 24/24 [==============================] - 14s 582ms/step - loss: 36.9057 - mae: 4.8198 - coeff_determination: 0.7703 Epoch 43/100 24/24 [==============================] - 14s 583ms/step - loss: 42.4705 - mae: 5.1666 - coeff_determination: 0.7371 Epoch 44/100 24/24 [==============================] - 14s 575ms/step - loss: 54.2301 - mae: 5.8843 - coeff_determination: 0.6635 Epoch 45/100 24/24 [==============================] - 14s 580ms/step - loss: 47.9779 - mae: 5.5399 - coeff_determination: 0.6977 Epoch 46/100 24/24 [==============================] - 14s 578ms/step - loss: 40.4867 - mae: 5.0962 - coeff_determination: 0.7440 Epoch 47/100 24/24 [==============================] - 14s 579ms/step - loss: 43.7501 - mae: 5.2146 - coeff_determination: 0.7326 Epoch 48/100 24/24 [==============================] - 14s 579ms/step - loss: 35.9673 - mae: 4.7420 - coeff_determination: 0.7788 Epoch 49/100 24/24 [==============================] - 18s 739ms/step - loss: 46.2015 - mae: 5.4458 - coeff_determination: 0.7085 Epoch 50/100 24/24 [==============================] - 14s 603ms/step - loss: 49.5634 - mae: 5.6395 - coeff_determination: 0.6918 Epoch 51/100 24/24 [==============================] - 15s 638ms/step - loss: 51.3972 - mae: 5.6585 - coeff_determination: 0.6823 Epoch 52/100 24/24 [==============================] - 15s 633ms/step - loss: 40.3427 - mae: 5.0128 - coeff_determination: 0.7532 Epoch 53/100 24/24 [==============================] - 13s 544ms/step - loss: 39.1933 - mae: 4.9519 - coeff_determination: 0.7612 Epoch 54/100 24/24 [==============================] - 17s 702ms/step - loss: 35.0141 - mae: 4.7013 - coeff_determination: 0.7802 Epoch 55/100 24/24 [==============================] - 14s 598ms/step - loss: 33.0745 - mae: 4.5662 - coeff_determination: 0.7953 Epoch 56/100 24/24 [==============================] - 17s 688ms/step - loss: 36.8873 - mae: 4.8620 - coeff_determination: 0.7719 Epoch 57/100 24/24 [==============================] - 17s 705ms/step - loss: 39.8476 - mae: 5.0527 - coeff_determination: 0.7492 Epoch 58/100 24/24 [==============================] - 17s 714ms/step - loss: 54.8125 - mae: 5.9266 - coeff_determination: 0.6637 Epoch 59/100 24/24 [==============================] - 15s 630ms/step - loss: 35.2315 - mae: 4.6927 - coeff_determination: 0.7799 Epoch 60/100 24/24 [==============================] - 14s 581ms/step - loss: 36.7938 - mae: 4.8262 - coeff_determination: 0.7729 Epoch 61/100 24/24 [==============================] - 14s 598ms/step - loss: 40.9202 - mae: 5.1409 - coeff_determination: 0.7424 Epoch 62/100 24/24 [==============================] - 14s 590ms/step - loss: 47.6010 - mae: 5.5060 - coeff_determination: 0.7054 Epoch 63/100 24/24 [==============================] - 17s 726ms/step - loss: 32.0861 - mae: 4.4874 - coeff_determination: 0.8017 Epoch 64/100 24/24 [==============================] - 16s 683ms/step - loss: 46.7470 - mae: 5.4235 - coeff_determination: 0.7170 Epoch 65/100 24/24 [==============================] - 13s 546ms/step - loss: 38.6596 - mae: 4.9225 - coeff_determination: 0.7631 Epoch 66/100 24/24 [==============================] - 15s 607ms/step - loss: 39.3497 - mae: 4.9802 - coeff_determination: 0.7555 Epoch 67/100 24/24 [==============================] - 18s 760ms/step - loss: 35.9601 - mae: 4.7624 - coeff_determination: 0.7744 Epoch 68/100 24/24 [==============================] - 14s 588ms/step - loss: 36.8186 - mae: 4.7642 - coeff_determination: 0.7752 Epoch 69/100 24/24 [==============================] - 15s 622ms/step - loss: 32.4865 - mae: 4.5050 - coeff_determination: 0.7999 Epoch 70/100 24/24 [==============================] - 13s 556ms/step - loss: 30.5051 - mae: 4.3644 - coeff_determination: 0.8110 Epoch 71/100 24/24 [==============================] - 14s 582ms/step - loss: 34.1785 - mae: 4.6512 - coeff_determination: 0.7883 Epoch 72/100 24/24 [==============================] - 24s 983ms/step - loss: 43.6993 - mae: 5.2011 - coeff_determination: 0.7331 Epoch 73/100 24/24 [==============================] - 23s 966ms/step - loss: 48.9992 - mae: 5.5405 - coeff_determination: 0.7031 Epoch 74/100 24/24 [==============================] - 17s 705ms/step - loss: 36.2409 - mae: 4.7846 - coeff_determination: 0.7777 Epoch 75/100 24/24 [==============================] - 16s 657ms/step - loss: 37.2511 - mae: 4.8438 - coeff_determination: 0.7707 Epoch 76/100 24/24 [==============================] - 17s 715ms/step - loss: 32.6323 - mae: 4.5339 - coeff_determination: 0.7954 Epoch 77/100 24/24 [==============================] - 16s 650ms/step - loss: 35.6714 - mae: 4.7688 - coeff_determination: 0.7756 Epoch 78/100 24/24 [==============================] - 15s 620ms/step - loss: 36.7774 - mae: 4.8165 - coeff_determination: 0.7732 Epoch 79/100 24/24 [==============================] - 16s 667ms/step - loss: 33.2150 - mae: 4.5490 - coeff_determination: 0.7955 Epoch 80/100 24/24 [==============================] - 16s 665ms/step - loss: 30.6302 - mae: 4.4031 - coeff_determination: 0.8117 Epoch 81/100 24/24 [==============================] - 17s 699ms/step - loss: 30.2946 - mae: 4.3357 - coeff_determination: 0.8123 Epoch 82/100 24/24 [==============================] - 14s 602ms/step - loss: 31.4617 - mae: 4.5006 - coeff_determination: 0.8010 Epoch 83/100 24/24 [==============================] - 13s 558ms/step - loss: 37.2033 - mae: 4.9019 - coeff_determination: 0.7650 Epoch 84/100 24/24 [==============================] - 18s 743ms/step - loss: 31.2802 - mae: 4.4123 - coeff_determination: 0.8081 Epoch 85/100 24/24 [==============================] - 17s 697ms/step - loss: 34.3818 - mae: 4.5931 - coeff_determination: 0.7903 Epoch 86/100 24/24 [==============================] - 15s 627ms/step - loss: 44.2251 - mae: 5.2733 - coeff_determination: 0.7305 Epoch 87/100 24/24 [==============================] - 15s 639ms/step - loss: 35.1733 - mae: 4.6774 - coeff_determination: 0.7830 Epoch 88/100 24/24 [==============================] - 13s 553ms/step - loss: 44.5560 - mae: 5.2967 - coeff_determination: 0.7286 Epoch 89/100 24/24 [==============================] - 13s 551ms/step - loss: 28.2234 - mae: 4.1867 - coeff_determination: 0.8243 Epoch 90/100 24/24 [==============================] - 13s 543ms/step - loss: 31.0560 - mae: 4.4144 - coeff_determination: 0.8089 Epoch 91/100 24/24 [==============================] - 14s 567ms/step - loss: 30.0287 - mae: 4.3561 - coeff_determination: 0.8139 Epoch 92/100 24/24 [==============================] - 13s 553ms/step - loss: 32.3961 - mae: 4.5145 - coeff_determination: 0.7980 Epoch 93/100 24/24 [==============================] - 13s 553ms/step - loss: 29.7120 - mae: 4.2794 - coeff_determination: 0.8181 Epoch 94/100 24/24 [==============================] - 13s 549ms/step - loss: 31.7320 - mae: 4.4373 - coeff_determination: 0.8034 Epoch 95/100 24/24 [==============================] - 15s 613ms/step - loss: 35.1161 - mae: 4.7122 - coeff_determination: 0.7842 Epoch 96/100 24/24 [==============================] - 16s 648ms/step - loss: 40.6502 - mae: 5.0100 - coeff_determination: 0.7517 Epoch 97/100 24/24 [==============================] - 14s 578ms/step - loss: 30.9931 - mae: 4.3869 - coeff_determination: 0.8100 Epoch 98/100 24/24 [==============================] - 16s 677ms/step - loss: 37.4913 - mae: 4.8725 - coeff_determination: 0.7703 Epoch 99/100 24/24 [==============================] - 14s 576ms/step - loss: 30.3058 - mae: 4.3163 - coeff_determination: 0.8146 Epoch 100/100 24/24 [==============================] - 17s 710ms/step - loss: 29.1149 - mae: 4.2909 - coeff_determination: 0.8205 ---------<TEST RESULTS FOR CLIENT client_1 ; USING LOCAL MODEL>----------- R^2 0.4186883990860364 Mean squared error 94.40305452386956 Mean absolute error 7.493844823442635 Huber loss 12.762769329916468 SCALING FACTOR : 0.5 --------<TEST RESULTS AFTER ROUND 2 ; USING GLOBAL MODEL>--------- R^2 -0.306 Mean squared error 212.104 Mean absolute error 12.374 Huber loss 15.609 ============================================================== ============================================================== ---------<STARTING TRAINING FOR ROUND 3>----------- ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 19s 774ms/step - loss: 632.6967 - mae: 19.4913 - coeff_determination: -2.8320 Epoch 2/100 24/24 [==============================] - 17s 722ms/step - loss: 111.4825 - mae: 8.4696 - coeff_determination: 0.3185 Epoch 3/100 24/24 [==============================] - 15s 640ms/step - loss: 81.9352 - mae: 7.2510 - coeff_determination: 0.4949 Epoch 4/100 24/24 [==============================] - 18s 747ms/step - loss: 70.8381 - mae: 6.7660 - coeff_determination: 0.5619 Epoch 5/100 24/24 [==============================] - 19s 798ms/step - loss: 66.1571 - mae: 6.5005 - coeff_determination: 0.5921 Epoch 6/100 24/24 [==============================] - 20s 819ms/step - loss: 60.2343 - mae: 6.2095 - coeff_determination: 0.6301 Epoch 7/100 24/24 [==============================] - 21s 896ms/step - loss: 51.6445 - mae: 5.7496 - coeff_determination: 0.6815 Epoch 8/100 24/24 [==============================] - 18s 765ms/step - loss: 53.6499 - mae: 5.8839 - coeff_determination: 0.6699 Epoch 9/100 24/24 [==============================] - 19s 805ms/step - loss: 52.1568 - mae: 5.7529 - coeff_determination: 0.6806 Epoch 10/100 24/24 [==============================] - 16s 670ms/step - loss: 46.5788 - mae: 5.4675 - coeff_determination: 0.7120 Epoch 11/100 24/24 [==============================] - 15s 618ms/step - loss: 51.7581 - mae: 5.7432 - coeff_determination: 0.6813 Epoch 12/100 24/24 [==============================] - 13s 544ms/step - loss: 40.6814 - mae: 5.0861 - coeff_determination: 0.7477 Epoch 13/100 24/24 [==============================] - 13s 538ms/step - loss: 41.9212 - mae: 5.1118 - coeff_determination: 0.7411 Epoch 14/100 24/24 [==============================] - 13s 552ms/step - loss: 40.7585 - mae: 5.0945 - coeff_determination: 0.7485 Epoch 15/100 24/24 [==============================] - 13s 541ms/step - loss: 48.3691 - mae: 5.4962 - coeff_determination: 0.7043 Epoch 16/100 24/24 [==============================] - 15s 630ms/step - loss: 43.4038 - mae: 5.2440 - coeff_determination: 0.7331 Epoch 17/100 24/24 [==============================] - 13s 546ms/step - loss: 38.9099 - mae: 4.9317 - coeff_determination: 0.7591 Epoch 18/100 24/24 [==============================] - 13s 541ms/step - loss: 53.7405 - mae: 5.8496 - coeff_determination: 0.6635 Epoch 19/100 24/24 [==============================] - 13s 552ms/step - loss: 49.9997 - mae: 5.6577 - coeff_determination: 0.6917 Epoch 20/100 24/24 [==============================] - 13s 541ms/step - loss: 40.9847 - mae: 5.0330 - coeff_determination: 0.7483 Epoch 21/100 24/24 [==============================] - 13s 554ms/step - loss: 35.5748 - mae: 4.7282 - coeff_determination: 0.7809 Epoch 22/100 24/24 [==============================] - 13s 541ms/step - loss: 34.8924 - mae: 4.6937 - coeff_determination: 0.7846 Epoch 23/100 24/24 [==============================] - 13s 539ms/step - loss: 36.0906 - mae: 4.7634 - coeff_determination: 0.7764 Epoch 24/100 24/24 [==============================] - 13s 538ms/step - loss: 40.3454 - mae: 5.0128 - coeff_determination: 0.7528 Epoch 25/100 24/24 [==============================] - 13s 543ms/step - loss: 38.0510 - mae: 4.9037 - coeff_determination: 0.7641 Epoch 26/100 24/24 [==============================] - 13s 560ms/step - loss: 37.2085 - mae: 4.8198 - coeff_determination: 0.7717 Epoch 27/100 24/24 [==============================] - 13s 537ms/step - loss: 48.6653 - mae: 5.5431 - coeff_determination: 0.6979 Epoch 28/100 24/24 [==============================] - 13s 547ms/step - loss: 42.5553 - mae: 5.1536 - coeff_determination: 0.7386 Epoch 29/100 24/24 [==============================] - 13s 540ms/step - loss: 50.5618 - mae: 5.6491 - coeff_determination: 0.6870 Epoch 30/100 24/24 [==============================] - 13s 541ms/step - loss: 48.1158 - mae: 5.5115 - coeff_determination: 0.7046 Epoch 31/100 24/24 [==============================] - 13s 547ms/step - loss: 34.8502 - mae: 4.6799 - coeff_determination: 0.7848 Epoch 32/100 24/24 [==============================] - 13s 538ms/step - loss: 35.5195 - mae: 4.7188 - coeff_determination: 0.7783 Epoch 33/100 24/24 [==============================] - 13s 542ms/step - loss: 32.7103 - mae: 4.5299 - coeff_determination: 0.7992 Epoch 34/100 24/24 [==============================] - 13s 544ms/step - loss: 34.4470 - mae: 4.6501 - coeff_determination: 0.7884 Epoch 35/100 24/24 [==============================] - 13s 546ms/step - loss: 33.0590 - mae: 4.5372 - coeff_determination: 0.7959 Epoch 36/100 24/24 [==============================] - 13s 537ms/step - loss: 33.0691 - mae: 4.5670 - coeff_determination: 0.7945 Epoch 37/100 24/24 [==============================] - 13s 541ms/step - loss: 37.0733 - mae: 4.8438 - coeff_determination: 0.7706 Epoch 38/100 24/24 [==============================] - 13s 545ms/step - loss: 46.4016 - mae: 5.4598 - coeff_determination: 0.7116 Epoch 39/100 24/24 [==============================] - 13s 542ms/step - loss: 36.6257 - mae: 4.7828 - coeff_determination: 0.7750 Epoch 40/100 24/24 [==============================] - 13s 539ms/step - loss: 35.5179 - mae: 4.7043 - coeff_determination: 0.7816 Epoch 41/100 24/24 [==============================] - 13s 538ms/step - loss: 36.4719 - mae: 4.7705 - coeff_determination: 0.7760 Epoch 42/100 24/24 [==============================] - 13s 544ms/step - loss: 33.3787 - mae: 4.5787 - coeff_determination: 0.7917 Epoch 43/100 24/24 [==============================] - 13s 542ms/step - loss: 33.6391 - mae: 4.5845 - coeff_determination: 0.7949 Epoch 44/100 24/24 [==============================] - 13s 557ms/step - loss: 33.5517 - mae: 4.5529 - coeff_determination: 0.7938 Epoch 45/100 24/24 [==============================] - 13s 541ms/step - loss: 35.6865 - mae: 4.7235 - coeff_determination: 0.7799 Epoch 46/100 24/24 [==============================] - 13s 539ms/step - loss: 34.7768 - mae: 4.6547 - coeff_determination: 0.7864 Epoch 47/100 24/24 [==============================] - 13s 546ms/step - loss: 43.4844 - mae: 5.2591 - coeff_determination: 0.7305 Epoch 48/100 24/24 [==============================] - 13s 547ms/step - loss: 36.3535 - mae: 4.7661 - coeff_determination: 0.7743 Epoch 49/100 24/24 [==============================] - 13s 545ms/step - loss: 47.7528 - mae: 5.5483 - coeff_determination: 0.6981 Epoch 50/100 24/24 [==============================] - 13s 541ms/step - loss: 40.6652 - mae: 5.0190 - coeff_determination: 0.7514 Epoch 51/100 24/24 [==============================] - 13s 540ms/step - loss: 31.3619 - mae: 4.4644 - coeff_determination: 0.8041 Epoch 52/100 24/24 [==============================] - 13s 546ms/step - loss: 37.2328 - mae: 4.8520 - coeff_determination: 0.7666 Epoch 53/100 24/24 [==============================] - 13s 540ms/step - loss: 35.6866 - mae: 4.7229 - coeff_determination: 0.7815 Epoch 54/100 24/24 [==============================] - 13s 538ms/step - loss: 30.3305 - mae: 4.3266 - coeff_determination: 0.8127 Epoch 55/100 24/24 [==============================] - 13s 544ms/step - loss: 45.9147 - mae: 5.4922 - coeff_determination: 0.7096 Epoch 56/100 24/24 [==============================] - 13s 542ms/step - loss: 71.8968 - mae: 6.8403 - coeff_determination: 0.5571 Epoch 57/100 24/24 [==============================] - 13s 549ms/step - loss: 43.8732 - mae: 5.2333 - coeff_determination: 0.7321 Epoch 58/100 24/24 [==============================] - 13s 539ms/step - loss: 31.7591 - mae: 4.4675 - coeff_determination: 0.8025 Epoch 59/100 24/24 [==============================] - 13s 539ms/step - loss: 37.0297 - mae: 4.8719 - coeff_determination: 0.7682 Epoch 60/100 24/24 [==============================] - 14s 576ms/step - loss: 30.3143 - mae: 4.3400 - coeff_determination: 0.8132 Epoch 61/100 24/24 [==============================] - 15s 616ms/step - loss: 31.4195 - mae: 4.4659 - coeff_determination: 0.8024 Epoch 62/100 24/24 [==============================] - 16s 651ms/step - loss: 38.3951 - mae: 4.9292 - coeff_determination: 0.7625 Epoch 63/100 24/24 [==============================] - 26s 1s/step - loss: 34.0109 - mae: 4.6167 - coeff_determination: 0.7888 Epoch 64/100 24/24 [==============================] - 19s 797ms/step - loss: 32.2508 - mae: 4.4581 - coeff_determination: 0.8033 Epoch 65/100 24/24 [==============================] - 13s 544ms/step - loss: 31.7706 - mae: 4.4971 - coeff_determination: 0.8006 Epoch 66/100 24/24 [==============================] - 13s 557ms/step - loss: 40.4330 - mae: 5.0511 - coeff_determination: 0.7509 Epoch 67/100 24/24 [==============================] - 16s 685ms/step - loss: 32.8441 - mae: 4.5402 - coeff_determination: 0.7986 Epoch 68/100 24/24 [==============================] - 15s 613ms/step - loss: 32.0159 - mae: 4.4357 - coeff_determination: 0.8044 Epoch 69/100 24/24 [==============================] - 15s 606ms/step - loss: 29.1881 - mae: 4.2990 - coeff_determination: 0.8169 Epoch 70/100 24/24 [==============================] - 14s 575ms/step - loss: 29.7508 - mae: 4.3384 - coeff_determination: 0.8157 Epoch 71/100 24/24 [==============================] - 15s 614ms/step - loss: 30.1321 - mae: 4.3422 - coeff_determination: 0.8132 Epoch 72/100 24/24 [==============================] - 14s 599ms/step - loss: 44.8803 - mae: 5.3611 - coeff_determination: 0.7244 Epoch 73/100 24/24 [==============================] - 15s 609ms/step - loss: 41.4342 - mae: 5.1898 - coeff_determination: 0.7384 Epoch 74/100 24/24 [==============================] - 15s 616ms/step - loss: 37.5555 - mae: 4.8258 - coeff_determination: 0.7700 Epoch 75/100 24/24 [==============================] - 14s 583ms/step - loss: 31.6825 - mae: 4.4398 - coeff_determination: 0.8048 Epoch 76/100 24/24 [==============================] - 14s 563ms/step - loss: 29.6231 - mae: 4.3235 - coeff_determination: 0.8150 Epoch 77/100 24/24 [==============================] - 13s 539ms/step - loss: 38.0054 - mae: 4.9101 - coeff_determination: 0.7615 Epoch 78/100 24/24 [==============================] - 13s 543ms/step - loss: 29.2914 - mae: 4.2570 - coeff_determination: 0.8173 Epoch 79/100 24/24 [==============================] - 13s 545ms/step - loss: 29.3603 - mae: 4.2687 - coeff_determination: 0.8202 Epoch 80/100 24/24 [==============================] - 13s 542ms/step - loss: 34.9191 - mae: 4.6960 - coeff_determination: 0.7829 Epoch 81/100 24/24 [==============================] - 14s 573ms/step - loss: 29.4405 - mae: 4.2465 - coeff_determination: 0.8208 Epoch 82/100 24/24 [==============================] - 14s 576ms/step - loss: 39.1546 - mae: 4.9690 - coeff_determination: 0.7608 Epoch 83/100 24/24 [==============================] - 13s 539ms/step - loss: 29.2735 - mae: 4.2912 - coeff_determination: 0.8177 Epoch 84/100 24/24 [==============================] - 14s 572ms/step - loss: 30.7059 - mae: 4.3999 - coeff_determination: 0.8081 Epoch 85/100 24/24 [==============================] - 13s 541ms/step - loss: 36.9898 - mae: 4.8712 - coeff_determination: 0.7690 Epoch 86/100 24/24 [==============================] - 14s 599ms/step - loss: 27.2188 - mae: 4.1305 - coeff_determination: 0.8321 Epoch 87/100 24/24 [==============================] - 16s 649ms/step - loss: 35.9500 - mae: 4.6899 - coeff_determination: 0.7804 Epoch 88/100 24/24 [==============================] - 14s 598ms/step - loss: 31.0481 - mae: 4.4137 - coeff_determination: 0.8084 Epoch 89/100 24/24 [==============================] - 14s 591ms/step - loss: 29.5415 - mae: 4.2772 - coeff_determination: 0.8184 Epoch 90/100 24/24 [==============================] - 14s 585ms/step - loss: 26.3064 - mae: 4.0285 - coeff_determination: 0.8369 Epoch 91/100 24/24 [==============================] - 14s 598ms/step - loss: 35.2868 - mae: 4.7243 - coeff_determination: 0.7804 Epoch 92/100 24/24 [==============================] - 16s 653ms/step - loss: 29.2936 - mae: 4.2795 - coeff_determination: 0.8188 Epoch 93/100 24/24 [==============================] - 13s 556ms/step - loss: 43.6324 - mae: 5.2297 - coeff_determination: 0.7318 Epoch 94/100 24/24 [==============================] - 13s 538ms/step - loss: 31.7996 - mae: 4.4558 - coeff_determination: 0.8033 Epoch 95/100 24/24 [==============================] - 13s 538ms/step - loss: 41.0148 - mae: 5.0630 - coeff_determination: 0.7496 Epoch 96/100 24/24 [==============================] - 13s 546ms/step - loss: 28.7464 - mae: 4.2359 - coeff_determination: 0.8221 Epoch 97/100 24/24 [==============================] - 14s 581ms/step - loss: 24.6877 - mae: 3.9248 - coeff_determination: 0.8469 Epoch 98/100 24/24 [==============================] - 13s 545ms/step - loss: 25.6757 - mae: 4.0040 - coeff_determination: 0.8428 Epoch 99/100 24/24 [==============================] - 14s 566ms/step - loss: 38.0524 - mae: 4.9388 - coeff_determination: 0.7617 Epoch 100/100 24/24 [==============================] - 13s 545ms/step - loss: 30.2674 - mae: 4.3359 - coeff_determination: 0.8145 ---------<TEST RESULTS FOR CLIENT client_1 ; USING LOCAL MODEL>----------- R^2 0.5032949233687738 Mean squared error 80.66323871358699 Mean absolute error 6.814059883657128 Huber loss 12.810701904219174 SCALING FACTOR : 0.5 ---------<STARTING TRAINING FOR CLIENT client_2>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 19s 789ms/step - loss: 668.0346 - mae: 20.0541 - coeff_determination: -3.0394 Epoch 2/100 24/24 [==============================] - 15s 636ms/step - loss: 108.6632 - mae: 8.3106 - coeff_determination: 0.3407 Epoch 3/100 24/24 [==============================] - 16s 664ms/step - loss: 89.8321 - mae: 7.6551 - coeff_determination: 0.4498 Epoch 4/100 24/24 [==============================] - 14s 574ms/step - loss: 71.2844 - mae: 6.7745 - coeff_determination: 0.5647 Epoch 5/100 24/24 [==============================] - 14s 565ms/step - loss: 60.8778 - mae: 6.2313 - coeff_determination: 0.6285 Epoch 6/100 24/24 [==============================] - 16s 658ms/step - loss: 58.5745 - mae: 6.0911 - coeff_determination: 0.6446 Epoch 7/100 24/24 [==============================] - 14s 570ms/step - loss: 58.5439 - mae: 6.1109 - coeff_determination: 0.6392 Epoch 8/100 24/24 [==============================] - 14s 569ms/step - loss: 58.9473 - mae: 6.1730 - coeff_determination: 0.6381 Epoch 9/100 24/24 [==============================] - 14s 563ms/step - loss: 59.7279 - mae: 6.1763 - coeff_determination: 0.6347 Epoch 10/100 24/24 [==============================] - 13s 540ms/step - loss: 52.8676 - mae: 5.8472 - coeff_determination: 0.6704 Epoch 11/100 24/24 [==============================] - 13s 542ms/step - loss: 50.3546 - mae: 5.6600 - coeff_determination: 0.6924 Epoch 12/100 24/24 [==============================] - 13s 545ms/step - loss: 42.8542 - mae: 5.1776 - coeff_determination: 0.7382 Epoch 13/100 24/24 [==============================] - 13s 548ms/step - loss: 42.2026 - mae: 5.1532 - coeff_determination: 0.7415 Epoch 14/100 24/24 [==============================] - 13s 541ms/step - loss: 42.8295 - mae: 5.1942 - coeff_determination: 0.7390 Epoch 15/100 24/24 [==============================] - 13s 555ms/step - loss: 45.5356 - mae: 5.3343 - coeff_determination: 0.7218 Epoch 16/100 24/24 [==============================] - 13s 545ms/step - loss: 44.6095 - mae: 5.2895 - coeff_determination: 0.7274 Epoch 17/100 24/24 [==============================] - 13s 543ms/step - loss: 38.8354 - mae: 4.9454 - coeff_determination: 0.7622 Epoch 18/100 24/24 [==============================] - 13s 544ms/step - loss: 42.1253 - mae: 5.1379 - coeff_determination: 0.7413 Epoch 19/100 24/24 [==============================] - 13s 542ms/step - loss: 41.7088 - mae: 5.0955 - coeff_determination: 0.7443 Epoch 20/100 24/24 [==============================] - 13s 542ms/step - loss: 35.8496 - mae: 4.7476 - coeff_determination: 0.7791 Epoch 21/100 24/24 [==============================] - 13s 548ms/step - loss: 39.2296 - mae: 5.0065 - coeff_determination: 0.7558 Epoch 22/100 24/24 [==============================] - 13s 542ms/step - loss: 40.7932 - mae: 5.0630 - coeff_determination: 0.7478 Epoch 23/100 24/24 [==============================] - 13s 556ms/step - loss: 36.8419 - mae: 4.8206 - coeff_determination: 0.7728 Epoch 24/100 24/24 [==============================] - 15s 637ms/step - loss: 48.4674 - mae: 5.5872 - coeff_determination: 0.6937 Epoch 25/100 24/24 [==============================] - 14s 604ms/step - loss: 43.6223 - mae: 5.1944 - coeff_determination: 0.7335 Epoch 26/100 24/24 [==============================] - 15s 638ms/step - loss: 47.2014 - mae: 5.4426 - coeff_determination: 0.7095 Epoch 27/100 24/24 [==============================] - 16s 665ms/step - loss: 39.2335 - mae: 4.9552 - coeff_determination: 0.7578 Epoch 28/100 24/24 [==============================] - 15s 612ms/step - loss: 34.1115 - mae: 4.6079 - coeff_determination: 0.7902 Epoch 29/100 24/24 [==============================] - 16s 658ms/step - loss: 36.8874 - mae: 4.8213 - coeff_determination: 0.7726 Epoch 30/100 24/24 [==============================] - 14s 599ms/step - loss: 35.6842 - mae: 4.7323 - coeff_determination: 0.7800 Epoch 31/100 24/24 [==============================] - 15s 632ms/step - loss: 35.7944 - mae: 4.7177 - coeff_determination: 0.7804 Epoch 32/100 24/24 [==============================] - 13s 554ms/step - loss: 34.8597 - mae: 4.6373 - coeff_determination: 0.7854 Epoch 33/100 24/24 [==============================] - 14s 597ms/step - loss: 39.5588 - mae: 4.9823 - coeff_determination: 0.7587 Epoch 34/100 24/24 [==============================] - 15s 618ms/step - loss: 34.3567 - mae: 4.6668 - coeff_determination: 0.7885 Epoch 35/100 24/24 [==============================] - 14s 599ms/step - loss: 38.4747 - mae: 4.9355 - coeff_determination: 0.7624 Epoch 36/100 24/24 [==============================] - 14s 585ms/step - loss: 36.1648 - mae: 4.7463 - coeff_determination: 0.7752 Epoch 37/100 24/24 [==============================] - 14s 587ms/step - loss: 35.8854 - mae: 4.7627 - coeff_determination: 0.7799 Epoch 38/100 24/24 [==============================] - 14s 592ms/step - loss: 32.5338 - mae: 4.4860 - coeff_determination: 0.8008 Epoch 39/100 24/24 [==============================] - 14s 584ms/step - loss: 60.3886 - mae: 6.1868 - coeff_determination: 0.6292 Epoch 40/100 24/24 [==============================] - 14s 584ms/step - loss: 40.8877 - mae: 5.0726 - coeff_determination: 0.7490 Epoch 41/100 24/24 [==============================] - 14s 600ms/step - loss: 36.0714 - mae: 4.8096 - coeff_determination: 0.7727 Epoch 42/100 24/24 [==============================] - 14s 587ms/step - loss: 32.6446 - mae: 4.5304 - coeff_determination: 0.7966 Epoch 43/100 24/24 [==============================] - 14s 594ms/step - loss: 38.7304 - mae: 4.9683 - coeff_determination: 0.7596 Epoch 44/100 24/24 [==============================] - 14s 585ms/step - loss: 34.6333 - mae: 4.6569 - coeff_determination: 0.7868 Epoch 45/100 24/24 [==============================] - 14s 584ms/step - loss: 36.1751 - mae: 4.7532 - coeff_determination: 0.7768 Epoch 46/100 24/24 [==============================] - 14s 591ms/step - loss: 38.5431 - mae: 4.9451 - coeff_determination: 0.7618 Epoch 47/100 24/24 [==============================] - 14s 600ms/step - loss: 39.6571 - mae: 4.9664 - coeff_determination: 0.7563 Epoch 48/100 24/24 [==============================] - 15s 605ms/step - loss: 35.7118 - mae: 4.8633 - coeff_determination: 0.7707 Epoch 49/100 24/24 [==============================] - 15s 607ms/step - loss: 45.5627 - mae: 5.3611 - coeff_determination: 0.7221 Epoch 50/100 24/24 [==============================] - 14s 598ms/step - loss: 32.5951 - mae: 4.5271 - coeff_determination: 0.7984 Epoch 51/100 24/24 [==============================] - 14s 585ms/step - loss: 64.4558 - mae: 6.4162 - coeff_determination: 0.6070 Epoch 52/100 24/24 [==============================] - 14s 598ms/step - loss: 57.5130 - mae: 5.9636 - coeff_determination: 0.6538 Epoch 53/100 24/24 [==============================] - 14s 586ms/step - loss: 33.9630 - mae: 4.6141 - coeff_determination: 0.7920 Epoch 54/100 24/24 [==============================] - 14s 584ms/step - loss: 31.0774 - mae: 4.3929 - coeff_determination: 0.8083 Epoch 55/100 24/24 [==============================] - 14s 588ms/step - loss: 32.2660 - mae: 4.4983 - coeff_determination: 0.8014 Epoch 56/100 24/24 [==============================] - 14s 592ms/step - loss: 33.1396 - mae: 4.5564 - coeff_determination: 0.7953 Epoch 57/100 24/24 [==============================] - 14s 591ms/step - loss: 31.2062 - mae: 4.4033 - coeff_determination: 0.8089 Epoch 58/100 24/24 [==============================] - 14s 594ms/step - loss: 33.0961 - mae: 4.5323 - coeff_determination: 0.7978 Epoch 59/100 24/24 [==============================] - 15s 624ms/step - loss: 32.2997 - mae: 4.5117 - coeff_determination: 0.7968 Epoch 60/100 24/24 [==============================] - 17s 704ms/step - loss: 35.2523 - mae: 4.7187 - coeff_determination: 0.7790 Epoch 61/100 24/24 [==============================] - 17s 717ms/step - loss: 41.3406 - mae: 5.0516 - coeff_determination: 0.7480 Epoch 62/100 24/24 [==============================] - 17s 716ms/step - loss: 31.4312 - mae: 4.4444 - coeff_determination: 0.8043 Epoch 63/100 24/24 [==============================] - 18s 755ms/step - loss: 34.8482 - mae: 4.6490 - coeff_determination: 0.7872 Epoch 64/100 24/24 [==============================] - 17s 706ms/step - loss: 29.0550 - mae: 4.2401 - coeff_determination: 0.8208 Epoch 65/100 24/24 [==============================] - 16s 661ms/step - loss: 28.5786 - mae: 4.2407 - coeff_determination: 0.8234 Epoch 66/100 24/24 [==============================] - 16s 652ms/step - loss: 29.4019 - mae: 4.2420 - coeff_determination: 0.8187 Epoch 67/100 24/24 [==============================] - 16s 676ms/step - loss: 30.5329 - mae: 4.3676 - coeff_determination: 0.8106 Epoch 68/100 24/24 [==============================] - 17s 693ms/step - loss: 34.0045 - mae: 4.5901 - coeff_determination: 0.7912 Epoch 69/100 24/24 [==============================] - 16s 675ms/step - loss: 29.6445 - mae: 4.2796 - coeff_determination: 0.8163 Epoch 70/100 24/24 [==============================] - 17s 717ms/step - loss: 38.3720 - mae: 4.8813 - coeff_determination: 0.7676 Epoch 71/100 24/24 [==============================] - 16s 660ms/step - loss: 31.0481 - mae: 4.4172 - coeff_determination: 0.8087 Epoch 72/100 24/24 [==============================] - 17s 700ms/step - loss: 57.8036 - mae: 6.1670 - coeff_determination: 0.6382 Epoch 73/100 24/24 [==============================] - 16s 666ms/step - loss: 37.5641 - mae: 4.8452 - coeff_determination: 0.7713 Epoch 74/100 24/24 [==============================] - 16s 672ms/step - loss: 33.9289 - mae: 4.6206 - coeff_determination: 0.7899 Epoch 75/100 24/24 [==============================] - 17s 699ms/step - loss: 40.3743 - mae: 5.0730 - coeff_determination: 0.7488 Epoch 76/100 24/24 [==============================] - 16s 682ms/step - loss: 33.4562 - mae: 4.5746 - coeff_determination: 0.7960 Epoch 77/100 24/24 [==============================] - 16s 665ms/step - loss: 32.0642 - mae: 4.4667 - coeff_determination: 0.7992 Epoch 78/100 24/24 [==============================] - 16s 651ms/step - loss: 30.0128 - mae: 4.3519 - coeff_determination: 0.8147 Epoch 79/100 24/24 [==============================] - 18s 770ms/step - loss: 50.3979 - mae: 5.6446 - coeff_determination: 0.6947 Epoch 80/100 24/24 [==============================] - 16s 686ms/step - loss: 48.3741 - mae: 5.5776 - coeff_determination: 0.6998 Epoch 81/100 24/24 [==============================] - 16s 653ms/step - loss: 32.9098 - mae: 4.5715 - coeff_determination: 0.7978 Epoch 82/100 24/24 [==============================] - 16s 654ms/step - loss: 26.9584 - mae: 4.1311 - coeff_determination: 0.8328 Epoch 83/100 24/24 [==============================] - 18s 760ms/step - loss: 31.8625 - mae: 4.4463 - coeff_determination: 0.8046 Epoch 84/100 24/24 [==============================] - 17s 724ms/step - loss: 27.7408 - mae: 4.1910 - coeff_determination: 0.8274 Epoch 85/100 24/24 [==============================] - 15s 632ms/step - loss: 31.5194 - mae: 4.4128 - coeff_determination: 0.8064 Epoch 86/100 24/24 [==============================] - 16s 649ms/step - loss: 26.9652 - mae: 4.1043 - coeff_determination: 0.8336 Epoch 87/100 24/24 [==============================] - 18s 750ms/step - loss: 29.9430 - mae: 4.3444 - coeff_determination: 0.8128 Epoch 88/100 24/24 [==============================] - 15s 627ms/step - loss: 30.9870 - mae: 4.3933 - coeff_determination: 0.8098 Epoch 89/100 24/24 [==============================] - 15s 623ms/step - loss: 36.2213 - mae: 4.7989 - coeff_determination: 0.7747 Epoch 90/100 24/24 [==============================] - 15s 627ms/step - loss: 31.7383 - mae: 4.4464 - coeff_determination: 0.8055 Epoch 91/100 24/24 [==============================] - 15s 617ms/step - loss: 31.6661 - mae: 4.4172 - coeff_determination: 0.8050 Epoch 92/100 24/24 [==============================] - 16s 668ms/step - loss: 35.0071 - mae: 4.6617 - coeff_determination: 0.7817 Epoch 93/100 24/24 [==============================] - 19s 807ms/step - loss: 29.0152 - mae: 4.2270 - coeff_determination: 0.8221 Epoch 94/100 24/24 [==============================] - 18s 761ms/step - loss: 27.3161 - mae: 4.0909 - coeff_determination: 0.8333 Epoch 95/100 24/24 [==============================] - 16s 668ms/step - loss: 29.8845 - mae: 4.2939 - coeff_determination: 0.8175 Epoch 96/100 24/24 [==============================] - 16s 665ms/step - loss: 40.9775 - mae: 5.1339 - coeff_determination: 0.7480 Epoch 97/100 24/24 [==============================] - 16s 659ms/step - loss: 39.3695 - mae: 5.0160 - coeff_determination: 0.7585 Epoch 98/100 24/24 [==============================] - 16s 681ms/step - loss: 35.7855 - mae: 4.7236 - coeff_determination: 0.7804 Epoch 99/100 24/24 [==============================] - 16s 676ms/step - loss: 29.4064 - mae: 4.3035 - coeff_determination: 0.8201 Epoch 100/100 24/24 [==============================] - 16s 670ms/step - loss: 31.3741 - mae: 4.4003 - coeff_determination: 0.8085 ---------<TEST RESULTS FOR CLIENT client_2 ; USING LOCAL MODEL>----------- R^2 0.5002819042801693 Mean squared error 81.15254290922971 Mean absolute error 6.950336584946976 Huber loss 12.92009920759122 SCALING FACTOR : 0.5 --------<TEST RESULTS AFTER ROUND 3 ; USING GLOBAL MODEL>--------- R^2 -0.69 Mean squared error 274.474 Mean absolute error 14.613 Huber loss 16.872 ============================================================== ============================================================== ---------<STARTING TRAINING FOR ROUND 4>----------- ---------<STARTING TRAINING FOR CLIENT client_2>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 19s 806ms/step - loss: 329.7290 - mae: 13.6651 - coeff_determination: -0.9642 Epoch 2/100 24/24 [==============================] - 16s 664ms/step - loss: 83.1808 - mae: 7.3575 - coeff_determination: 0.4821 Epoch 3/100 24/24 [==============================] - 16s 655ms/step - loss: 69.2709 - mae: 6.6262 - coeff_determination: 0.5771 Epoch 4/100 24/24 [==============================] - 16s 669ms/step - loss: 54.4393 - mae: 5.8700 - coeff_determination: 0.6654 Epoch 5/100 24/24 [==============================] - 19s 792ms/step - loss: 46.6744 - mae: 5.4269 - coeff_determination: 0.7149 Epoch 6/100 24/24 [==============================] - 17s 705ms/step - loss: 42.9987 - mae: 5.2176 - coeff_determination: 0.7379 Epoch 7/100 24/24 [==============================] - 20s 813ms/step - loss: 46.7490 - mae: 5.4519 - coeff_determination: 0.7138 Epoch 8/100 24/24 [==============================] - 19s 784ms/step - loss: 40.8657 - mae: 5.0984 - coeff_determination: 0.7478 Epoch 9/100 24/24 [==============================] - 18s 740ms/step - loss: 40.6271 - mae: 5.0541 - coeff_determination: 0.7499 Epoch 10/100 24/24 [==============================] - 20s 813ms/step - loss: 41.6847 - mae: 5.1044 - coeff_determination: 0.7450 Epoch 11/100 24/24 [==============================] - 21s 860ms/step - loss: 37.0312 - mae: 4.8106 - coeff_determination: 0.7720 Epoch 12/100 24/24 [==============================] - 18s 745ms/step - loss: 37.2120 - mae: 4.8306 - coeff_determination: 0.7718 Epoch 13/100 24/24 [==============================] - 16s 677ms/step - loss: 48.0432 - mae: 5.4923 - coeff_determination: 0.7076 Epoch 14/100 24/24 [==============================] - 15s 634ms/step - loss: 41.4519 - mae: 5.0602 - coeff_determination: 0.7483 Epoch 15/100 24/24 [==============================] - 16s 680ms/step - loss: 37.8686 - mae: 4.8532 - coeff_determination: 0.7676 Epoch 16/100 24/24 [==============================] - 20s 850ms/step - loss: 45.5534 - mae: 5.4091 - coeff_determination: 0.7099 Epoch 17/100 24/24 [==============================] - 22s 908ms/step - loss: 49.5060 - mae: 5.5436 - coeff_determination: 0.6977 Epoch 18/100 24/24 [==============================] - 19s 783ms/step - loss: 37.8406 - mae: 4.9530 - coeff_determination: 0.7608 Epoch 19/100 24/24 [==============================] - 17s 717ms/step - loss: 42.2553 - mae: 5.1224 - coeff_determination: 0.7428 Epoch 20/100 24/24 [==============================] - 16s 682ms/step - loss: 37.4627 - mae: 4.8265 - coeff_determination: 0.7722 Epoch 21/100 24/24 [==============================] - 16s 667ms/step - loss: 33.1315 - mae: 4.5278 - coeff_determination: 0.7963 Epoch 22/100 24/24 [==============================] - 18s 750ms/step - loss: 39.9652 - mae: 5.0043 - coeff_determination: 0.7558 Epoch 23/100 24/24 [==============================] - 16s 684ms/step - loss: 34.4822 - mae: 4.6549 - coeff_determination: 0.7883 Epoch 24/100 24/24 [==============================] - 19s 774ms/step - loss: 31.4696 - mae: 4.4209 - coeff_determination: 0.8054 Epoch 25/100 24/24 [==============================] - 17s 721ms/step - loss: 30.4774 - mae: 4.3906 - coeff_determination: 0.8100 Epoch 26/100 24/24 [==============================] - 16s 680ms/step - loss: 46.6306 - mae: 5.4381 - coeff_determination: 0.7131 Epoch 27/100 24/24 [==============================] - 16s 663ms/step - loss: 37.1984 - mae: 4.8595 - coeff_determination: 0.7682 Epoch 28/100 24/24 [==============================] - 16s 656ms/step - loss: 34.9714 - mae: 4.6747 - coeff_determination: 0.7849 Epoch 29/100 24/24 [==============================] - 16s 668ms/step - loss: 31.5821 - mae: 4.4671 - coeff_determination: 0.8049 Epoch 30/100 24/24 [==============================] - 18s 749ms/step - loss: 32.2119 - mae: 4.4525 - coeff_determination: 0.8017 Epoch 31/100 24/24 [==============================] - 19s 782ms/step - loss: 32.5023 - mae: 4.5349 - coeff_determination: 0.7978 Epoch 32/100 24/24 [==============================] - 17s 704ms/step - loss: 40.6027 - mae: 5.0236 - coeff_determination: 0.7506 Epoch 33/100 24/24 [==============================] - 17s 699ms/step - loss: 50.8656 - mae: 5.6579 - coeff_determination: 0.6905 Epoch 34/100 24/24 [==============================] - 17s 692ms/step - loss: 42.1978 - mae: 5.1377 - coeff_determination: 0.7381 Epoch 35/100 24/24 [==============================] - 17s 704ms/step - loss: 31.3396 - mae: 4.4228 - coeff_determination: 0.8086 Epoch 36/100 24/24 [==============================] - 17s 702ms/step - loss: 35.6828 - mae: 4.7280 - coeff_determination: 0.7810 Epoch 37/100 24/24 [==============================] - 17s 708ms/step - loss: 40.1741 - mae: 5.0382 - coeff_determination: 0.7528 Epoch 38/100 24/24 [==============================] - 17s 694ms/step - loss: 32.7423 - mae: 4.5179 - coeff_determination: 0.7984 Epoch 39/100 24/24 [==============================] - 17s 699ms/step - loss: 35.9244 - mae: 4.7406 - coeff_determination: 0.7790 Epoch 40/100 24/24 [==============================] - 17s 714ms/step - loss: 28.5643 - mae: 4.2108 - coeff_determination: 0.8244 Epoch 41/100 24/24 [==============================] - 18s 757ms/step - loss: 29.9133 - mae: 4.3215 - coeff_determination: 0.8170 Epoch 42/100 24/24 [==============================] - 16s 684ms/step - loss: 28.4265 - mae: 4.2175 - coeff_determination: 0.8250 Epoch 43/100 24/24 [==============================] - 17s 724ms/step - loss: 29.5041 - mae: 4.2522 - coeff_determination: 0.8192 Epoch 44/100 24/24 [==============================] - 16s 660ms/step - loss: 29.4678 - mae: 4.2509 - coeff_determination: 0.8202 Epoch 45/100 24/24 [==============================] - 16s 656ms/step - loss: 32.9390 - mae: 4.5337 - coeff_determination: 0.7994 Epoch 46/100 24/24 [==============================] - 20s 853ms/step - loss: 41.8966 - mae: 5.1812 - coeff_determination: 0.7394 Epoch 47/100 24/24 [==============================] - 19s 776ms/step - loss: 52.9660 - mae: 5.7268 - coeff_determination: 0.6763 Epoch 48/100 24/24 [==============================] - 15s 640ms/step - loss: 46.5214 - mae: 5.3592 - coeff_determination: 0.7169 Epoch 49/100 24/24 [==============================] - 16s 656ms/step - loss: 36.0353 - mae: 4.7809 - coeff_determination: 0.7774 Epoch 50/100 24/24 [==============================] - 15s 638ms/step - loss: 33.6252 - mae: 4.5684 - coeff_determination: 0.7953 Epoch 51/100 24/24 [==============================] - 16s 661ms/step - loss: 36.0339 - mae: 4.7634 - coeff_determination: 0.7780 Epoch 52/100 24/24 [==============================] - 16s 657ms/step - loss: 47.5640 - mae: 5.5322 - coeff_determination: 0.7066 Epoch 53/100 24/24 [==============================] - 16s 656ms/step - loss: 39.1250 - mae: 4.9503 - coeff_determination: 0.7585 Epoch 54/100 24/24 [==============================] - 16s 661ms/step - loss: 30.1963 - mae: 4.3167 - coeff_determination: 0.8134 Epoch 55/100 24/24 [==============================] - 16s 656ms/step - loss: 26.9871 - mae: 4.1112 - coeff_determination: 0.8323 Epoch 56/100 24/24 [==============================] - 15s 645ms/step - loss: 26.4923 - mae: 4.0700 - coeff_determination: 0.8355 Epoch 57/100 24/24 [==============================] - 16s 646ms/step - loss: 32.1471 - mae: 4.4993 - coeff_determination: 0.8021 Epoch 58/100 24/24 [==============================] - 16s 655ms/step - loss: 34.8131 - mae: 4.6617 - coeff_determination: 0.7865 Epoch 59/100 24/24 [==============================] - 16s 663ms/step - loss: 32.2503 - mae: 4.4575 - coeff_determination: 0.8017 Epoch 60/100 24/24 [==============================] - 16s 659ms/step - loss: 32.4689 - mae: 4.5188 - coeff_determination: 0.7983 Epoch 61/100 24/24 [==============================] - 15s 639ms/step - loss: 30.5120 - mae: 4.3994 - coeff_determination: 0.8065 Epoch 62/100 24/24 [==============================] - 15s 643ms/step - loss: 31.4003 - mae: 4.4199 - coeff_determination: 0.8063 Epoch 63/100 24/24 [==============================] - 17s 698ms/step - loss: 28.7524 - mae: 4.2266 - coeff_determination: 0.8219 Epoch 64/100 24/24 [==============================] - 19s 808ms/step - loss: 27.6282 - mae: 4.1156 - coeff_determination: 0.8317 Epoch 65/100 24/24 [==============================] - 17s 727ms/step - loss: 30.8514 - mae: 4.3791 - coeff_determination: 0.8105 Epoch 66/100 24/24 [==============================] - 16s 681ms/step - loss: 27.9000 - mae: 4.1357 - coeff_determination: 0.8297 Epoch 67/100 24/24 [==============================] - 17s 696ms/step - loss: 44.4957 - mae: 5.3701 - coeff_determination: 0.7195 Epoch 68/100 24/24 [==============================] - 17s 714ms/step - loss: 42.3163 - mae: 5.1028 - coeff_determination: 0.7474 Epoch 69/100 24/24 [==============================] - 17s 708ms/step - loss: 34.1595 - mae: 4.6539 - coeff_determination: 0.7851 Epoch 70/100 24/24 [==============================] - 16s 649ms/step - loss: 29.3232 - mae: 4.2687 - coeff_determination: 0.8210 Epoch 71/100 24/24 [==============================] - 16s 652ms/step - loss: 27.6167 - mae: 4.1228 - coeff_determination: 0.8304 Epoch 72/100 24/24 [==============================] - 15s 627ms/step - loss: 29.5548 - mae: 4.2606 - coeff_determination: 0.8180 Epoch 73/100 24/24 [==============================] - 15s 625ms/step - loss: 30.5151 - mae: 4.3798 - coeff_determination: 0.8139 Epoch 74/100 24/24 [==============================] - 15s 628ms/step - loss: 26.5167 - mae: 4.0589 - coeff_determination: 0.8362 Epoch 75/100 24/24 [==============================] - 15s 633ms/step - loss: 27.3609 - mae: 4.1134 - coeff_determination: 0.8321 Epoch 76/100 24/24 [==============================] - 15s 640ms/step - loss: 48.8304 - mae: 5.5913 - coeff_determination: 0.6995 Epoch 77/100 24/24 [==============================] - 15s 638ms/step - loss: 47.7019 - mae: 5.4899 - coeff_determination: 0.7087 Epoch 78/100 24/24 [==============================] - 16s 677ms/step - loss: 33.4930 - mae: 4.5763 - coeff_determination: 0.7926 Epoch 79/100 24/24 [==============================] - 15s 623ms/step - loss: 28.1789 - mae: 4.1635 - coeff_determination: 0.8266 Epoch 80/100 24/24 [==============================] - 16s 661ms/step - loss: 27.8058 - mae: 4.1553 - coeff_determination: 0.8272 Epoch 81/100 24/24 [==============================] - 16s 662ms/step - loss: 27.5766 - mae: 4.1194 - coeff_determination: 0.8317 Epoch 82/100 24/24 [==============================] - 15s 645ms/step - loss: 24.8118 - mae: 3.9091 - coeff_determination: 0.8441 Epoch 83/100 24/24 [==============================] - 15s 642ms/step - loss: 27.8493 - mae: 4.1771 - coeff_determination: 0.8272 Epoch 84/100 24/24 [==============================] - 15s 645ms/step - loss: 35.5864 - mae: 4.7255 - coeff_determination: 0.7764 Epoch 85/100 24/24 [==============================] - 16s 653ms/step - loss: 34.4130 - mae: 4.6365 - coeff_determination: 0.7901 Epoch 86/100 24/24 [==============================] - 16s 647ms/step - loss: 33.4253 - mae: 4.5544 - coeff_determination: 0.7968 Epoch 87/100 24/24 [==============================] - 16s 647ms/step - loss: 38.4344 - mae: 4.8852 - coeff_determination: 0.7652 Epoch 88/100 24/24 [==============================] - 16s 671ms/step - loss: 32.5958 - mae: 4.5399 - coeff_determination: 0.7992 Epoch 89/100 24/24 [==============================] - 16s 668ms/step - loss: 29.0802 - mae: 4.2279 - coeff_determination: 0.8219 Epoch 90/100 24/24 [==============================] - 15s 642ms/step - loss: 30.3486 - mae: 4.3206 - coeff_determination: 0.8156 Epoch 91/100 24/24 [==============================] - 15s 633ms/step - loss: 44.3268 - mae: 5.2965 - coeff_determination: 0.7245 Epoch 92/100 24/24 [==============================] - 16s 671ms/step - loss: 32.5945 - mae: 4.5144 - coeff_determination: 0.8008 Epoch 93/100 24/24 [==============================] - 15s 641ms/step - loss: 28.0697 - mae: 4.1999 - coeff_determination: 0.8250 Epoch 94/100 24/24 [==============================] - 15s 645ms/step - loss: 29.4225 - mae: 4.2962 - coeff_determination: 0.8188 Epoch 95/100 24/24 [==============================] - 15s 635ms/step - loss: 25.6827 - mae: 4.0029 - coeff_determination: 0.8401 Epoch 96/100 24/24 [==============================] - 15s 628ms/step - loss: 36.9919 - mae: 4.7887 - coeff_determination: 0.7724 Epoch 97/100 24/24 [==============================] - 15s 618ms/step - loss: 28.4039 - mae: 4.2527 - coeff_determination: 0.8246 Epoch 98/100 24/24 [==============================] - 16s 647ms/step - loss: 27.9236 - mae: 4.1662 - coeff_determination: 0.8270 Epoch 99/100 24/24 [==============================] - 16s 649ms/step - loss: 27.7571 - mae: 4.1464 - coeff_determination: 0.8298 Epoch 100/100 24/24 [==============================] - 15s 643ms/step - loss: 27.3318 - mae: 4.1514 - coeff_determination: 0.8314 ---------<TEST RESULTS FOR CLIENT client_2 ; USING LOCAL MODEL>----------- R^2 0.5216889878206556 Mean squared error 77.67610433223894 Mean absolute error 6.7768342822023 Huber loss 12.773990798312507 SCALING FACTOR : 0.5 ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 24/24 [==============================] - 22s 900ms/step - loss: 387.6057 - mae: 15.0622 - coeff_determination: -1.3799 Epoch 2/100 24/24 [==============================] - 15s 639ms/step - loss: 90.8386 - mae: 7.6992 - coeff_determination: 0.4325 Epoch 3/100 24/24 [==============================] - 15s 634ms/step - loss: 79.7585 - mae: 7.1408 - coeff_determination: 0.5142 Epoch 4/100 24/24 [==============================] - 15s 634ms/step - loss: 64.1892 - mae: 6.3698 - coeff_determination: 0.6072 Epoch 5/100 24/24 [==============================] - 15s 633ms/step - loss: 58.2567 - mae: 6.0641 - coeff_determination: 0.6438 Epoch 6/100 24/24 [==============================] - 17s 719ms/step - loss: 53.4009 - mae: 5.8216 - coeff_determination: 0.6717 Epoch 7/100 24/24 [==============================] - 24s 1s/step - loss: 45.3709 - mae: 5.3438 - coeff_determination: 0.7195 Epoch 8/100 24/24 [==============================] - 19s 776ms/step - loss: 45.8697 - mae: 5.3866 - coeff_determination: 0.7160 Epoch 9/100 24/24 [==============================] - 21s 870ms/step - loss: 49.9530 - mae: 5.6231 - coeff_determination: 0.6929 Epoch 10/100 24/24 [==============================] - 27s 1s/step - loss: 43.5048 - mae: 5.2681 - coeff_determination: 0.7339 Epoch 11/100 24/24 [==============================] - 17s 706ms/step - loss: 38.3123 - mae: 4.9361 - coeff_determination: 0.7627 Epoch 12/100 24/24 [==============================] - 18s 751ms/step - loss: 41.3056 - mae: 5.1105 - coeff_determination: 0.7480 Epoch 13/100 24/24 [==============================] - 20s 825ms/step - loss: 38.2514 - mae: 4.9236 - coeff_determination: 0.7650 Epoch 14/100 24/24 [==============================] - 21s 880ms/step - loss: 38.9949 - mae: 4.9339 - coeff_determination: 0.7612 Epoch 15/100 24/24 [==============================] - 18s 747ms/step - loss: 35.8292 - mae: 4.7352 - coeff_determination: 0.7772 Epoch 16/100 24/24 [==============================] - 16s 686ms/step - loss: 38.0581 - mae: 4.9410 - coeff_determination: 0.7638 Epoch 17/100 24/24 [==============================] - 16s 664ms/step - loss: 42.1898 - mae: 5.1783 - coeff_determination: 0.7430 Epoch 18/100 24/24 [==============================] - 19s 794ms/step - loss: 37.8145 - mae: 4.8660 - coeff_determination: 0.7673 Epoch 19/100 24/24 [==============================] - 23s 974ms/step - loss: 34.9506 - mae: 4.6564 - coeff_determination: 0.7874 Epoch 20/100 24/24 [==============================] - 19s 802ms/step - loss: 32.1934 - mae: 4.4683 - coeff_determination: 0.8023 Epoch 21/100 24/24 [==============================] - 18s 755ms/step - loss: 34.3137 - mae: 4.6419 - coeff_determination: 0.7869 Epoch 22/100 24/24 [==============================] - 15s 637ms/step - loss: 36.6250 - mae: 4.7988 - coeff_determination: 0.7768 Epoch 23/100 24/24 [==============================] - 18s 759ms/step - loss: 36.5360 - mae: 4.8217 - coeff_determination: 0.7748 Epoch 24/100 24/24 [==============================] - 14s 593ms/step - loss: 33.2754 - mae: 4.5226 - coeff_determination: 0.7954 Epoch 25/100 24/24 [==============================] - 13s 555ms/step - loss: 34.1846 - mae: 4.6120 - coeff_determination: 0.7886 Epoch 26/100 24/24 [==============================] - 14s 580ms/step - loss: 39.4150 - mae: 5.0148 - coeff_determination: 0.7501 Epoch 27/100 24/24 [==============================] - 13s 560ms/step - loss: 39.9669 - mae: 4.9570 - coeff_determination: 0.7579 Epoch 28/100 24/24 [==============================] - 13s 559ms/step - loss: 32.3327 - mae: 4.4943 - coeff_determination: 0.8003 Epoch 29/100 24/24 [==============================] - 13s 551ms/step - loss: 30.3536 - mae: 4.3397 - coeff_determination: 0.8120 Epoch 30/100 24/24 [==============================] - 14s 572ms/step - loss: 30.9421 - mae: 4.3920 - coeff_determination: 0.8068 Epoch 31/100 24/24 [==============================] - 13s 561ms/step - loss: 32.0233 - mae: 4.5001 - coeff_determination: 0.7979 Epoch 32/100 24/24 [==============================] - 13s 555ms/step - loss: 44.8381 - mae: 5.3959 - coeff_determination: 0.7168 Epoch 33/100 24/24 [==============================] - 13s 546ms/step - loss: 35.4420 - mae: 4.6663 - coeff_determination: 0.7837 Epoch 34/100 24/24 [==============================] - 14s 563ms/step - loss: 31.8304 - mae: 4.4233 - coeff_determination: 0.8037 Epoch 35/100 24/24 [==============================] - 13s 554ms/step - loss: 30.2261 - mae: 4.3446 - coeff_determination: 0.8146 Epoch 36/100 24/24 [==============================] - 13s 556ms/step - loss: 31.6756 - mae: 4.4645 - coeff_determination: 0.7996 Epoch 37/100 24/24 [==============================] - 13s 553ms/step - loss: 37.9998 - mae: 4.8819 - coeff_determination: 0.7674 Epoch 38/100 24/24 [==============================] - 13s 550ms/step - loss: 30.5540 - mae: 4.3800 - coeff_determination: 0.8121 Epoch 39/100 24/24 [==============================] - 13s 558ms/step - loss: 35.6594 - mae: 4.7659 - coeff_determination: 0.7817 Epoch 40/100 24/24 [==============================] - 13s 555ms/step - loss: 38.3286 - mae: 4.9214 - coeff_determination: 0.7643 Epoch 41/100 24/24 [==============================] - 13s 557ms/step - loss: 36.9202 - mae: 4.8143 - coeff_determination: 0.7724 Epoch 42/100 24/24 [==============================] - 13s 551ms/step - loss: 39.3939 - mae: 4.9873 - coeff_determination: 0.7585 Epoch 43/100 24/24 [==============================] - 13s 556ms/step - loss: 31.9431 - mae: 4.4667 - coeff_determination: 0.8029 Epoch 44/100 24/24 [==============================] - 13s 556ms/step - loss: 30.7084 - mae: 4.3986 - coeff_determination: 0.8106 Epoch 45/100 24/24 [==============================] - 15s 639ms/step - loss: 30.6171 - mae: 4.3575 - coeff_determination: 0.8111 Epoch 46/100 24/24 [==============================] - 16s 652ms/step - loss: 27.5526 - mae: 4.1394 - coeff_determination: 0.8298 Epoch 47/100 24/24 [==============================] - 19s 808ms/step - loss: 38.7964 - mae: 4.9045 - coeff_determination: 0.7591 Epoch 48/100 24/24 [==============================] - 16s 677ms/step - loss: 38.2821 - mae: 4.9153 - coeff_determination: 0.7641 Epoch 49/100 24/24 [==============================] - 16s 683ms/step - loss: 34.2721 - mae: 4.6187 - coeff_determination: 0.7913 Epoch 50/100 24/24 [==============================] - 15s 627ms/step - loss: 30.3697 - mae: 4.3226 - coeff_determination: 0.8138 Epoch 51/100 24/24 [==============================] - 15s 613ms/step - loss: 30.1495 - mae: 4.3627 - coeff_determination: 0.8122 Epoch 52/100 24/24 [==============================] - 17s 705ms/step - loss: 32.1353 - mae: 4.4780 - coeff_determination: 0.8016 Epoch 53/100 24/24 [==============================] - 15s 624ms/step - loss: 31.9771 - mae: 4.4286 - coeff_determination: 0.8042 Epoch 54/100 24/24 [==============================] - 13s 547ms/step - loss: 30.2335 - mae: 4.3410 - coeff_determination: 0.8138 Epoch 55/100 24/24 [==============================] - 13s 562ms/step - loss: 27.6717 - mae: 4.1754 - coeff_determination: 0.8294 Epoch 56/100 24/24 [==============================] - 14s 567ms/step - loss: 26.3451 - mae: 4.0616 - coeff_determination: 0.8384 Epoch 57/100 24/24 [==============================] - 13s 559ms/step - loss: 29.2632 - mae: 4.2824 - coeff_determination: 0.8196 Epoch 58/100 24/24 [==============================] - 14s 564ms/step - loss: 31.2074 - mae: 4.4088 - coeff_determination: 0.8094 Epoch 59/100 24/24 [==============================] - 22s 918ms/step - loss: 31.3708 - mae: 4.4324 - coeff_determination: 0.8058 Epoch 60/100 24/24 [==============================] - 28s 1s/step - loss: 32.5388 - mae: 4.5590 - coeff_determination: 0.7981 Epoch 61/100 24/24 [==============================] - 28s 1s/step - loss: 36.4840 - mae: 4.7787 - coeff_determination: 0.7772 Epoch 62/100 24/24 [==============================] - 18s 755ms/step - loss: 29.9100 - mae: 4.3095 - coeff_determination: 0.8144 Epoch 63/100 24/24 [==============================] - 21s 894ms/step - loss: 27.4183 - mae: 4.1251 - coeff_determination: 0.8306 Epoch 64/100 24/24 [==============================] - 17s 722ms/step - loss: 30.2739 - mae: 4.3427 - coeff_determination: 0.8134 Epoch 65/100 24/24 [==============================] - 16s 686ms/step - loss: 27.2544 - mae: 4.0860 - coeff_determination: 0.8329 Epoch 66/100 24/24 [==============================] - 15s 638ms/step - loss: 37.2966 - mae: 4.8164 - coeff_determination: 0.7735 Epoch 67/100 24/24 [==============================] - 15s 614ms/step - loss: 32.9273 - mae: 4.5331 - coeff_determination: 0.7985 Epoch 68/100 24/24 [==============================] - 15s 606ms/step - loss: 27.4392 - mae: 4.1196 - coeff_determination: 0.8315 Epoch 69/100 24/24 [==============================] - 15s 614ms/step - loss: 28.7904 - mae: 4.2434 - coeff_determination: 0.8227 Epoch 70/100 24/24 [==============================] - 20s 834ms/step - loss: 27.9593 - mae: 4.1420 - coeff_determination: 0.8264 Epoch 71/100 24/24 [==============================] - 16s 681ms/step - loss: 41.6969 - mae: 5.1071 - coeff_determination: 0.7436 Epoch 72/100 24/24 [==============================] - 15s 617ms/step - loss: 26.9057 - mae: 4.0811 - coeff_determination: 0.8354 Epoch 73/100 24/24 [==============================] - 16s 667ms/step - loss: 25.6561 - mae: 3.9874 - coeff_determination: 0.8427 Epoch 74/100 24/24 [==============================] - 19s 810ms/step - loss: 36.5726 - mae: 4.7702 - coeff_determination: 0.7744 Epoch 75/100 24/24 [==============================] - 19s 782ms/step - loss: 34.3009 - mae: 4.6279 - coeff_determination: 0.7890 Epoch 76/100 24/24 [==============================] - 17s 724ms/step - loss: 35.0261 - mae: 4.7418 - coeff_determination: 0.7824 Epoch 77/100 24/24 [==============================] - 15s 627ms/step - loss: 49.1010 - mae: 5.6796 - coeff_determination: 0.6874 Epoch 78/100 24/24 [==============================] - 15s 625ms/step - loss: 35.3682 - mae: 4.7096 - coeff_determination: 0.7853 Epoch 79/100 24/24 [==============================] - 15s 625ms/step - loss: 29.1051 - mae: 4.2755 - coeff_determination: 0.8188 Epoch 80/100 24/24 [==============================] - 15s 611ms/step - loss: 29.1550 - mae: 4.2807 - coeff_determination: 0.8213 Epoch 81/100 24/24 [==============================] - 15s 633ms/step - loss: 32.8928 - mae: 4.5822 - coeff_determination: 0.7928 Epoch 82/100 24/24 [==============================] - 15s 631ms/step - loss: 32.4686 - mae: 4.4735 - coeff_determination: 0.8011 Epoch 83/100 24/24 [==============================] - 14s 603ms/step - loss: 31.4926 - mae: 4.4531 - coeff_determination: 0.8078 Epoch 84/100 24/24 [==============================] - 15s 632ms/step - loss: 26.3748 - mae: 4.0203 - coeff_determination: 0.8374 Epoch 85/100 24/24 [==============================] - 18s 759ms/step - loss: 27.8290 - mae: 4.1863 - coeff_determination: 0.8270 Epoch 86/100 24/24 [==============================] - 17s 725ms/step - loss: 35.2568 - mae: 4.7544 - coeff_determination: 0.7797 Epoch 87/100 24/24 [==============================] - 17s 720ms/step - loss: 26.2382 - mae: 4.0300 - coeff_determination: 0.8376 Epoch 88/100 24/24 [==============================] - 14s 599ms/step - loss: 27.5494 - mae: 4.1326 - coeff_determination: 0.8302 Epoch 89/100 24/24 [==============================] - 14s 600ms/step - loss: 32.3824 - mae: 4.4646 - coeff_determination: 0.8012 Epoch 90/100 24/24 [==============================] - 14s 588ms/step - loss: 38.3998 - mae: 4.9170 - coeff_determination: 0.7674 Epoch 91/100 24/24 [==============================] - 15s 608ms/step - loss: 35.1872 - mae: 4.6982 - coeff_determination: 0.7860 Epoch 92/100 24/24 [==============================] - 14s 582ms/step - loss: 33.6785 - mae: 4.6399 - coeff_determination: 0.7904 Epoch 93/100 24/24 [==============================] - 14s 595ms/step - loss: 29.9077 - mae: 4.3031 - coeff_determination: 0.8170 Epoch 94/100 24/24 [==============================] - 14s 591ms/step - loss: 25.8628 - mae: 4.0351 - coeff_determination: 0.8381 Epoch 95/100 24/24 [==============================] - 15s 605ms/step - loss: 26.6560 - mae: 4.0504 - coeff_determination: 0.8361 Epoch 96/100 24/24 [==============================] - 14s 597ms/step - loss: 32.6056 - mae: 4.4714 - coeff_determination: 0.8015 Epoch 97/100 24/24 [==============================] - 15s 608ms/step - loss: 29.3722 - mae: 4.2690 - coeff_determination: 0.8206 Epoch 98/100 24/24 [==============================] - 14s 587ms/step - loss: 25.4440 - mae: 3.9829 - coeff_determination: 0.8408 Epoch 99/100 24/24 [==============================] - 14s 595ms/step - loss: 25.0147 - mae: 3.9273 - coeff_determination: 0.8462 Epoch 100/100 24/24 [==============================] - 14s 597ms/step - loss: 25.1098 - mae: 3.9621 - coeff_determination: 0.8448 ---------<TEST RESULTS FOR CLIENT client_1 ; USING LOCAL MODEL>----------- R^2 0.5112753933774674 Mean squared error 79.36723714717698 Mean absolute error 6.75066868821508 Huber loss 12.848073473751517 SCALING FACTOR : 0.5 --------<TEST RESULTS AFTER ROUND 4 ; USING GLOBAL MODEL>--------- R^2 0.235 Mean squared error 124.264 Mean absolute error 9.248 Huber loss 13.452 ============================================================== ============================================================== ---------<STARTING TRAINING FOR ROUND 5>----------- ---------<STARTING TRAINING FOR CLIENT client_1>----------- Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 18388)] 0 _________________________________________________________________ dense (Dense) (None, 1024) 18830336 _________________________________________________________________ dropout (Dropout) (None, 1024) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 524800 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 64) 32832 _________________________________________________________________ dropout_2 (Dropout) (None, 64) 0 _________________________________________________________________ age_output (Dense) (None, 1) 65 ================================================================= Total params: 19,388,033 Trainable params: 19,388,033 Non-trainable params: 0 _________________________________________________________________ Epoch 1/100 14/Unknown - 11s 792ms/step - loss: 892.6613 - mae: 24.2433 - coeff_determination: -4.5195
playbook/tactics/privilege-escalation/T1546.013.ipynb
###Markdown T1546.013 - Event Triggered Execution: PowerShell ProfileAdversaries may gain persistence and elevate privileges by executing malicious content triggered by PowerShell profiles. A PowerShell profile (profile.ps1) is a script that runs when [PowerShell](https://attack.mitre.org/techniques/T1059/001) starts and can be used as a logon script to customize user environments.[PowerShell](https://attack.mitre.org/techniques/T1059/001) supports several profiles depending on the user or host program. For example, there can be different profiles for [PowerShell](https://attack.mitre.org/techniques/T1059/001) host programs such as the PowerShell console, PowerShell ISE or Visual Studio Code. An administrator can also configure a profile that applies to all users and host programs on the local computer. (Citation: Microsoft About Profiles) Adversaries may modify these profiles to include arbitrary commands, functions, modules, and/or [PowerShell](https://attack.mitre.org/techniques/T1059/001) drives to gain persistence. Every time a user opens a [PowerShell](https://attack.mitre.org/techniques/T1059/001) session the modified script will be executed unless the -NoProfile flag is used when it is launched. (Citation: ESET Turla PowerShell May 2019) An adversary may also be able to escalate privileges if a script in a PowerShell profile is loaded and executed by an account with higher privileges, such as a domain administrator. (Citation: Wits End and Shady PowerShell Profiles) Atomic Tests ###Code #Import the Module before running the tests. # Checkout Jupyter Notebook at https://github.com/cyb3rbuff/TheAtomicPlaybook to run PS scripts. Import-Module /Users/0x6c/AtomicRedTeam/atomics/invoke-atomicredteam/Invoke-AtomicRedTeam.psd1 - Force ###Output _____no_output_____ ###Markdown Atomic Test 1 - Append malicious start-process cmdletAppends a start process cmdlet to the current user's powershell profile pofile that points to a malicious executable. Upon execution, calc.exe will be launched.**Supported Platforms:** windows Dependencies: Run with `powershell`! Description: Ensure a powershell profile exists for the current user Check Prereq Commands:```powershellif (Test-Path $profile) {exit 0} else {exit 1}``` Get Prereq Commands:```powershellNew-Item -Path $profile -Type File -Force``` ###Code Invoke-AtomicTest T1546.013 -TestNumbers 1 -GetPreReqs ###Output _____no_output_____ ###Markdown Attack Commands: Run with `powershell````powershellAdd-Content $profile -Value ""Add-Content $profile -Value "Start-Process calc.exe"powershell -Command exit``` ###Code Invoke-AtomicTest T1546.013 -TestNumbers 1 ###Output _____no_output_____
Recommendation Study/Recommender system.ipynb
###Markdown 추천시스템 (Recommende System)- 추천시스템은 크게 두가지로 구분가능 - 컨텐츠 기반 필터링(content-based filtering) - 협업 필터링(collaborative filtering)- 두가지를 조합한 Hybrid 방식도 가능- 컨텐츠 기반 필터링은 지금까지 사용자의 이전행동과 명시적 피드백을 통해 사용자가 좋아하는 것과 유사한 항목을 추천- 협업 필터링은 사용자와 항목간의 유사성을 동시에 사용해 추천 Surprise- 추천 시스템 개발을 위한 라이브러리- 다양한 모델과 데이터 제공- scikit-learn과 유사한 사용 방법 ###Code from surprise import SVD from surprise import Dataset from surprise.model_selection import cross_validate from sklearn.decomposition import randomized_svd, non_negative_factorization import numpy as np data = Dataset.load_builtin('ml-100k',prompt=False) data.raw_ratings[:10] #data 구성 #user/item(movie)/score(rating)/ID model=SVD() cross_validate(model, data, measures=['rmse', 'mae'], cv=5, verbose=True) ###Output Evaluating RMSE, MAE of algorithm SVD on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9298 0.9357 0.9473 0.9354 0.9308 0.9358 0.0062 MAE (testset) 0.7328 0.7403 0.7476 0.7373 0.7316 0.7379 0.0058 Fit time 4.67 4.76 4.80 4.82 5.00 4.81 0.11 Test time 0.18 0.18 0.16 0.12 0.16 0.16 0.02 ###Markdown 컨텐츠 기반 필터링(Content-based Filtering)- 컨텐츠 기반 필터링은 이전의 행동과 명시적 피드백을 통해 좋아하는 것과 유사한 항목을 추천 - 예를들어 내가 지금까지 시청한 영화 목록과 다른 사용자의 시청 목록을 비교해 나와 비슷한 취향의 사용자가 시청한 영화를 추천- 유사도를 기반으로 추천- 컨텐츠 기반 필터링은 다음과 같은 장단점이 있다. - 장점 - 많은 수의 사용자를 대상으로 쉽게 확장이 가능 - 사용자가 관심을 갖지 않던 상품 추천가능 - 단점 - 입력 특성을 직접 설계해야 하기 때문에 많은 도메인 지식이 필요 - 사용자의 기존 관심사항을 기반으로만 추천 가능 - 콜드 스타트 문제 존재 ###Code data = Dataset.load_builtin('ml-100k', prompt=False) raw_data = np.array(data.raw_ratings, dtype=int) raw_data raw_data[:,0]-=1 raw_data[:,1]-=1 raw_data n_users = np.max(raw_data[:,0]) n_movies = np.max(raw_data[:,1]) shape = (n_users+1, n_movies+1) shape adj_matrix = np.ndarray(shape,dtype=int) for user_id, movie_id, rating, time in raw_data: adj_matrix[user_id][movie_id]=1. adj_matrix my_id, my_vector = 0, adj_matrix[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(adj_matrix): if my_id != user_id: similarity = np.dot(my_vector, user_vector) if similarity > best_match: best_match = similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, log in enumerate(zip(my_vector, best_match_vector)): log1, log2 = log if log1<1. and log2>0.: recommed_list.append(i) print(recommed_list) ###Output [272, 273, 275, 280, 281, 283, 287, 288, 289, 290, 292, 293, 297, 299, 300, 301, 302, 306, 312, 314, 315, 316, 317, 321, 322, 323, 324, 327, 330, 331, 332, 333, 339, 342, 345, 346, 353, 354, 355, 356, 357, 363, 364, 365, 366, 372, 374, 378, 379, 381, 382, 383, 384, 385, 386, 387, 390, 391, 392, 394, 395, 396, 398, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 412, 414, 416, 417, 418, 419, 420, 422, 424, 425, 426, 427, 428, 430, 431, 432, 435, 442, 446, 447, 448, 449, 450, 451, 452, 454, 455, 457, 460, 461, 462, 468, 469, 470, 471, 472, 473, 474, 478, 495, 500, 507, 517, 522, 525, 530, 539, 540, 543, 545, 546, 548, 549, 550, 551, 553, 557, 558, 560, 561, 562, 563, 565, 566, 567, 568, 570, 571, 574, 575, 576, 577, 580, 581, 582, 585, 587, 589, 590, 594, 596, 602, 623, 626, 627, 630, 633, 635, 639, 646, 648, 651, 652, 654, 657, 664, 668, 671, 677, 678, 681, 683, 684, 685, 690, 691, 692, 695, 696, 708, 709, 714, 718, 719, 720, 724, 726, 727, 731, 733, 734, 736, 738, 741, 742, 745, 746, 747, 749, 750, 754, 758, 762, 764, 767, 768, 769, 770, 771, 772, 773, 778, 779, 782, 785, 788, 789, 793, 795, 796, 799, 800, 801, 802, 805, 806, 808, 815, 819, 822, 824, 830, 839, 842, 843, 844, 852, 853, 870, 875, 878, 880, 889, 901, 914, 915, 918, 921, 927, 929, 930, 938, 940, 941, 942, 948, 950, 958, 968, 973, 974, 976, 992, 999, 1005, 1009, 1010, 1012, 1015, 1018, 1027, 1030, 1034, 1035, 1041, 1043, 1045, 1046, 1051, 1055, 1072, 1073, 1078, 1080, 1082, 1088, 1089, 1090, 1094, 1097, 1108, 1109, 1117, 1128, 1130, 1134, 1139, 1140, 1144, 1156, 1169, 1171, 1179, 1193, 1198, 1207, 1209, 1212, 1217, 1219, 1220, 1227, 1231, 1238, 1239, 1243, 1244, 1252, 1266, 1272, 1273, 1300, 1313, 1406, 1412, 1415, 1470, 1477, 1480, 1481, 1482] ###Markdown 유클리드 거리를 사용해 추천$$euclidean=\ \sqrt{\sum_{d=1}^{D\ }{(A_i-B_i)^2}} $$- 거리가 가까울 수록(값이 작을 수록) 나와 유사항 사용자 ###Code my_id, my_vector = 0, adj_matrix[0] best_match, best_match_id, best_match_vector = 999,-1,[] for user_id, user_vector in enumerate(adj_matrix): if my_id != user_id: euclidean_dist = np.sqrt(np.sum(np.square(my_vector - user_vector))) if euclidean_dist < best_match: best_match = euclidean_dist best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, log in enumerate(zip(my_vector, best_match_vector)): log1, log2 = log if log1<1. and log2>0.: recommed_list.append(i) print(recommed_list) ###Output [297, 312, 317, 342, 356, 366, 379, 384, 392, 402, 404, 407, 417, 422, 428, 433, 448, 454, 469, 473, 495, 510, 516, 526, 527, 549, 567, 602, 635, 649, 650, 654, 658, 661, 664, 696, 731, 746, 750, 754, 915, 918, 925, 929, 950, 968, 1015, 1046] ###Markdown 코사인 유사도를 사용해 추천$$cos\theta = \dfrac{A \bullet B}{\rVert A \rVert \times \rVert B \rVert}$$- 두 벡터가 이루고 있는 각을 계산 ###Code def compute_cos_similarity(v1,v2): norm1 = np.sqrt(np.sum(np.square(v1))) norm2 = np.sqrt(np.sum(np.square(v2))) dot = np.dot(v1,v2) return dot / (norm1*norm2) my_id, my_vector = 0, adj_matrix[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(adj_matrix): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, log in enumerate(zip(my_vector, best_match_vector)): log1, log2 = log if log1<1. and log2>0.: recommed_list.append(i) print(recommed_list) ###Output [272, 275, 279, 280, 283, 285, 289, 294, 297, 316, 317, 355, 365, 366, 368, 379, 380, 381, 384, 386, 392, 398, 401, 404, 416, 420, 422, 424, 426, 427, 430, 432, 450, 460, 461, 466, 469, 471, 473, 474, 475, 479, 482, 483, 497, 505, 508, 510, 511, 522, 526, 527, 529, 530, 534, 536, 540, 545, 548, 549, 556, 557, 558, 560, 565, 567, 568, 569, 577, 580, 581, 582, 592, 596, 630, 635, 639, 641, 649, 651, 654, 673, 677, 678, 683, 684, 692, 696, 701, 703, 707, 708, 709, 712, 714, 719, 720, 726, 731, 734, 736, 738, 740, 745, 747, 754, 755, 761, 762, 763, 766, 780, 789, 791, 805, 819, 823, 824, 830, 843, 862, 865, 918, 929, 930, 938, 942, 943, 947, 958, 959, 960, 970, 977, 1004, 1008, 1009, 1010, 1013, 1041, 1045, 1069, 1072, 1073, 1078, 1097, 1100, 1108, 1112, 1118, 1134, 1193, 1205, 1207, 1216, 1219, 1267, 1334, 1400, 1427, 1596, 1681] ###Markdown 기존 방법에 명시적 피드백(사용자가 평가한 영화 점수)을 추가해 실험- 위 테스트 까지는 봣는지 안봤는지 0,1로만 구분했지만,- rating 점수를 추가 기입 ###Code adj_matrix = np.ndarray(shape,dtype=int) for user_id, movie_id, rating, time in raw_data: adj_matrix[user_id][movie_id] = rating adj_matrix my_id, my_vector = 0, adj_matrix[0] best_match, best_match_id, best_match_vector = 999,-1,[] for user_id, user_vector in enumerate(adj_matrix): if my_id != user_id: euclidean_dist = np.sqrt(np.sum(np.square(my_vector - user_vector))) if euclidean_dist < best_match: best_match = euclidean_dist best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) my_id, my_vector = 0, adj_matrix[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(adj_matrix): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) ###Output Best Match : 0.569065731527988, Best Match ID : 915 ###Markdown 협업 필터링(Collaborative Filtering)- 사용자가 항목의 유사성을 동시에 고려해 추천- 기존에 내 관심사가 아닌 항목이라도 추천 가능- 자동으로 임베딩 학습 가능- 협업 필터링은 다음과 같은 장단점을 갖고 있다. - 장점 - 자동으로 임베딜을 학습하기 때문에 도메인 지식이 필요 없다. - 기존의 관심사가 아니더라도 추천 가능 - 단점 - 학습 과정에 나오지 않은 항목은 임베딩을 만들 수 없음 - 추가 특성을 사용하기 어려움 ###Code from surprise import KNNBasic, SVD, SVDpp, NMF from surprise.model_selection import cross_validate data = Dataset.load_builtin('ml-100k',prompt=False) ###Output _____no_output_____ ###Markdown KNN ###Code model = KNNBasic() cross_validate(model, data, measures=['rmse','mae'],cv=5,n_jobs=4,verbose=True) ###Output Evaluating RMSE, MAE of algorithm KNNBasic on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9801 0.9761 0.9770 0.9886 0.9750 0.9794 0.0049 MAE (testset) 0.7739 0.7722 0.7681 0.7825 0.7693 0.7732 0.0051 Fit time 0.23 0.29 0.36 0.34 0.35 0.31 0.05 Test time 3.73 4.37 4.57 3.81 3.00 3.90 0.55 ###Markdown SVD ###Code model = SVD() cross_validate(model, data, measures=['rmse','mae'],cv=5,n_jobs=4,verbose=True) ###Output Evaluating RMSE, MAE of algorithm SVD on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9312 0.9389 0.9403 0.9316 0.9365 0.9357 0.0037 MAE (testset) 0.7352 0.7429 0.7385 0.7368 0.7361 0.7379 0.0027 Fit time 8.09 9.47 9.21 7.99 6.38 8.23 1.10 Test time 0.31 0.28 0.21 0.14 0.14 0.22 0.07 ###Markdown NMF ###Code model = NMF() cross_validate(model, data, measures=['rmse','mae'],cv=5,n_jobs=4,verbose=True) ###Output Evaluating RMSE, MAE of algorithm NMF on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9696 0.9539 0.9657 0.9569 0.9675 0.9627 0.0062 MAE (testset) 0.7622 0.7496 0.7594 0.7522 0.7606 0.7568 0.0050 Fit time 6.31 7.91 7.90 6.73 5.21 6.81 1.02 Test time 0.31 0.19 0.17 0.11 0.12 0.18 0.07 ###Markdown SVD++ (need long time) ###Code model = SVDpp() cross_validate(model, data, measures=['rmse','mae'],cv=5,n_jobs=4,verbose=True) ###Output Evaluating RMSE, MAE of algorithm SVDpp on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9176 0.9236 0.9195 0.9160 0.9105 0.9174 0.0043 MAE (testset) 0.7186 0.7234 0.7213 0.7197 0.7129 0.7192 0.0035 Fit time 331.22 332.18 331.31 333.60 158.24 297.31 69.54 Test time 5.16 5.26 5.00 2.82 2.42 4.13 1.24 ###Markdown 하이브리드(Hybrid)- 컨텐츠 기반 필터링과 협업 필터링을 조합한 방식- 많은 하이브리드 방식이 존재- 실습에서는 협업 필터링으로 임베딩을 학습하고 컨텐츠 기반 필터링으로 유사도 기반 추천을 수행하는 추천 엔진 개발 ###Code data = Dataset.load_builtin('ml-100k',prompt=False) raw_data = np.array(data.raw_ratings, dtype=int) raw_data[:,0]-=1 raw_data[:,1]-=1 n_users = np.max(raw_data[:,0]) n_movies = np.max(raw_data[:,1]) shape = (n_users+1,n_movies+1) shape adj_matrix = np.ndarray(shape, dtype=int) for user_id, movie_id, rating, time in raw_data: adj_matrix[user_id][movie_id] = rating adj_matrix ###Output _____no_output_____ ###Markdown - 행렬 분해 ###Code U, S, V = randomized_svd(adj_matrix, n_components=2) S = np.diag(S) print(U.shape) print(S.shape) print(V.shape) np.matmul(np.matmul(U,S),V) ###Output _____no_output_____ ###Markdown - 사용자 기반 추천- 나와 비슷한 취향을 가진 다른 사용자의 행동을 추천- 사용자 특징 벡터의 유사도 사용 ###Code my_id, my_vector = 0, U[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(U): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, log in enumerate(zip(adj_matrix[my_id], adj_matrix[best_match_id])): log1, log2 = log if log1<1. and log2>0.: recommed_list.append(i) print(recommed_list) ###Output [272, 273, 274, 281, 285, 288, 293, 297, 303, 306, 312, 317, 327, 332, 369, 410, 418, 419, 422, 426, 428, 431, 434, 442, 461, 475, 477, 482, 495, 503, 504, 505, 506, 509, 519, 520, 522, 525, 531, 545, 548, 590, 594, 595, 613, 631, 654, 658, 660, 672, 684, 685, 691, 695, 698, 704, 716, 728, 734, 749, 755, 863, 865, 933, 1012, 1038, 1101, 1327, 1400] ###Markdown - 항목 기반 추천- 내가 본 항목과 비슷한 항목을 추천- 항목 특징 벡터의 유사도 사용 ###Code my_id, my_vector = 0, V.T[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(V.T): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, user_vector in enumerate(adj_matrix): if adj_matrix[i][my_id] > 0.9: recommed_list.append(i) print(recommed_list) ###Output [0, 1, 4, 5, 9, 12, 14, 15, 16, 17, 19, 20, 22, 24, 25, 37, 40, 41, 42, 43, 44, 48, 53, 55, 56, 57, 58, 61, 62, 63, 64, 65, 66, 69, 71, 72, 74, 76, 78, 80, 81, 82, 83, 88, 91, 92, 93, 94, 95, 96, 98, 100, 101, 105, 107, 108, 116, 119, 120, 123, 124, 127, 129, 130, 133, 136, 137, 140, 143, 144, 147, 149, 150, 156, 157, 159, 161, 167, 173, 176, 177, 180, 181, 183, 188, 192, 193, 197, 198, 199, 200, 201, 202, 203, 208, 209, 212, 215, 221, 222, 229, 230, 231, 233, 234, 241, 242, 243, 245, 246, 247, 248, 249, 250, 251, 252, 253, 255, 261, 262, 264, 267, 270, 273, 274, 275, 276, 278, 279, 285, 286, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 302, 304, 306, 307, 310, 311, 312, 313, 319, 321, 323, 324, 325, 326, 329, 330, 331, 335, 337, 338, 339, 342, 343, 344, 346, 347, 349, 356, 358, 359, 362, 364, 370, 373, 377, 378, 379, 380, 386, 387, 388, 389, 392, 393, 394, 395, 397, 398, 400, 401, 402, 405, 406, 410, 411, 415, 416, 418, 421, 423, 424, 428, 431, 433, 434, 437, 440, 444, 446, 449, 453, 454, 455, 456, 457, 458, 459, 462, 464, 466, 467, 469, 470, 471, 477, 478, 482, 483, 485, 486, 487, 489, 492, 493, 494, 496, 499, 502, 504, 507, 511, 513, 516, 517, 520, 522, 524, 525, 531, 532, 533, 534, 535, 536, 539, 540, 541, 544, 547, 548, 549, 551, 552, 553, 559, 560, 561, 566, 568, 575, 576, 578, 579, 581, 587, 591, 592, 596, 598, 601, 604, 605, 608, 609, 611, 612, 613, 617, 619, 620, 621, 623, 629, 631, 633, 634, 635, 636, 641, 642, 647, 648, 649, 652, 653, 654, 656, 657, 659, 660, 662, 663, 664, 668, 673, 675, 676, 677, 678, 679, 681, 683, 688, 689, 690, 691, 696, 697, 698, 700, 702, 704, 705, 707, 708, 709, 713, 714, 715, 720, 722, 725, 726, 729, 730, 732, 734, 737, 741, 743, 744, 745, 746, 747, 748, 750, 755, 756, 758, 760, 762, 763, 766, 767, 768, 769, 770, 772, 776, 778, 784, 785, 787, 788, 789, 791, 792, 793, 794, 795, 797, 799, 803, 804, 805, 806, 814, 816, 820, 821, 822, 825, 828, 829, 830, 834, 837, 838, 842, 846, 851, 853, 863, 864, 866, 867, 869, 871, 878, 879, 880, 881, 882, 884, 885, 886, 888, 889, 891, 892, 893, 894, 895, 896, 898, 900, 901, 902, 906, 909, 912, 915, 916, 917, 918, 920, 921, 922, 923, 926, 928, 929, 931, 932, 933, 934, 935, 937, 940] ###Markdown - 비음수 행렬 분해를 사용한 하이브리드 추천 ###Code adj_matrix A, B, iter = non_negative_factorization(adj_matrix,n_components=2) np.matmul(A,B) ###Output _____no_output_____ ###Markdown - 사용자 기반 추천 ###Code my_id, my_vector = 0, U[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(U): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, log in enumerate(zip(adj_matrix[my_id], adj_matrix[best_match_id])): log1, log2 = log if log1<1. and log2>0.: recommed_list.append(i) print(recommed_list) ###Output [272, 273, 274, 281, 285, 288, 293, 297, 303, 306, 312, 317, 327, 332, 369, 410, 418, 419, 422, 426, 428, 431, 434, 442, 461, 475, 477, 482, 495, 503, 504, 505, 506, 509, 519, 520, 522, 525, 531, 545, 548, 590, 594, 595, 613, 631, 654, 658, 660, 672, 684, 685, 691, 695, 698, 704, 716, 728, 734, 749, 755, 863, 865, 933, 1012, 1038, 1101, 1327, 1400] ###Markdown - 항목 기반 추천 ###Code my_id, my_vector = 0, V.T[0] best_match, best_match_id, best_match_vector = -1,-1,[] for user_id, user_vector in enumerate(V.T): if my_id != user_id: cos_similarity = compute_cos_similarity(my_vector, user_vector) if cos_similarity > best_match: best_match = cos_similarity best_match_id = user_id best_match_vector = user_vector print('Best Match : {}, Best Match ID : {}'.format(best_match,best_match_id)) recommed_list = [] for i, user_vector in enumerate(adj_matrix): if adj_matrix[i][my_id] > 0.9: recommed_list.append(i) print(recommed_list) ###Output [0, 1, 4, 5, 9, 12, 14, 15, 16, 17, 19, 20, 22, 24, 25, 37, 40, 41, 42, 43, 44, 48, 53, 55, 56, 57, 58, 61, 62, 63, 64, 65, 66, 69, 71, 72, 74, 76, 78, 80, 81, 82, 83, 88, 91, 92, 93, 94, 95, 96, 98, 100, 101, 105, 107, 108, 116, 119, 120, 123, 124, 127, 129, 130, 133, 136, 137, 140, 143, 144, 147, 149, 150, 156, 157, 159, 161, 167, 173, 176, 177, 180, 181, 183, 188, 192, 193, 197, 198, 199, 200, 201, 202, 203, 208, 209, 212, 215, 221, 222, 229, 230, 231, 233, 234, 241, 242, 243, 245, 246, 247, 248, 249, 250, 251, 252, 253, 255, 261, 262, 264, 267, 270, 273, 274, 275, 276, 278, 279, 285, 286, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 302, 304, 306, 307, 310, 311, 312, 313, 319, 321, 323, 324, 325, 326, 329, 330, 331, 335, 337, 338, 339, 342, 343, 344, 346, 347, 349, 356, 358, 359, 362, 364, 370, 373, 377, 378, 379, 380, 386, 387, 388, 389, 392, 393, 394, 395, 397, 398, 400, 401, 402, 405, 406, 410, 411, 415, 416, 418, 421, 423, 424, 428, 431, 433, 434, 437, 440, 444, 446, 449, 453, 454, 455, 456, 457, 458, 459, 462, 464, 466, 467, 469, 470, 471, 477, 478, 482, 483, 485, 486, 487, 489, 492, 493, 494, 496, 499, 502, 504, 507, 511, 513, 516, 517, 520, 522, 524, 525, 531, 532, 533, 534, 535, 536, 539, 540, 541, 544, 547, 548, 549, 551, 552, 553, 559, 560, 561, 566, 568, 575, 576, 578, 579, 581, 587, 591, 592, 596, 598, 601, 604, 605, 608, 609, 611, 612, 613, 617, 619, 620, 621, 623, 629, 631, 633, 634, 635, 636, 641, 642, 647, 648, 649, 652, 653, 654, 656, 657, 659, 660, 662, 663, 664, 668, 673, 675, 676, 677, 678, 679, 681, 683, 688, 689, 690, 691, 696, 697, 698, 700, 702, 704, 705, 707, 708, 709, 713, 714, 715, 720, 722, 725, 726, 729, 730, 732, 734, 737, 741, 743, 744, 745, 746, 747, 748, 750, 755, 756, 758, 760, 762, 763, 766, 767, 768, 769, 770, 772, 776, 778, 784, 785, 787, 788, 789, 791, 792, 793, 794, 795, 797, 799, 803, 804, 805, 806, 814, 816, 820, 821, 822, 825, 828, 829, 830, 834, 837, 838, 842, 846, 851, 853, 863, 864, 866, 867, 869, 871, 878, 879, 880, 881, 882, 884, 885, 886, 888, 889, 891, 892, 893, 894, 895, 896, 898, 900, 901, 902, 906, 909, 912, 915, 916, 917, 918, 920, 921, 922, 923, 926, 928, 929, 931, 932, 933, 934, 935, 937, 940]
notebooks/create_models.ipynb
###Markdown Create model classes ###Code # Make conv layer class for easy writing in next class class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super().__init__() # We have to keep the image size same num_pad = int(np.floor(kernel_size / 2)) self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=num_pad) def forward(self, x): return self.conv(x) class BottleneckBlock(nn.Module): """ Bottleneck layer similar to resnet bottleneck layer. InstanceNorm is used instead of BatchNorm because when we want to generate images, we normalize all the images independently. (In batch norm you compute mean and std over complete batch, while in instance norm you compute mean and std of each image independently). The reason for doing this is, the generated images are independent of each other, so we should not normalize them using a common statistic. If you confused about the bottleneck architecture refer to the official pytorch resnet implementation and paper. """ def __init__(self, in_channels, out_channels, kernel_size=3, stride=1): super().__init__() self.in_c = in_channels self.out_c = out_channels self.identity_block = nn.Sequential( ConvLayer(in_channels, out_channels//4, kernel_size=1, stride=1), nn.InstanceNorm2d(out_channels//4), nn.ReLU(), ConvLayer(out_channels//4, out_channels//4, kernel_size, stride=stride), nn.InstanceNorm2d(out_channels//4), nn.ReLU(), ConvLayer(out_channels//4, out_channels, kernel_size=1, stride=1), nn.InstanceNorm2d(out_channels), nn.ReLU(), ) self.shortcut = nn.Sequential( ConvLayer(in_channels, out_channels, 1, stride), nn.InstanceNorm2d(out_channels), ) def forward(self, x): out = self.identity_block(x) if self.in_c == self.out_c: residual = x else: residual = self.shortcut(x) out += residual out = F.relu(out) return out # Not used in the implementation class UpSample(nn.Module): def __init__(self, in_channels, out_channels, scale_factor, mode='bilinear'): super().__init__() self.scale_factor = scale_factor self.mode = mode self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1) self.norm = nn.InstanceNorm2d(out_channels) def forward(self, x): out = self.conv(x) out = F.interpolate(out, scale_factor=self.scale_factor, mode=self.mode, align_corners=False) out = self.norm(out) out = F.relu(out) return out # Helper functions for HRNet def conv_down(in_c, out_c, stride=2): return nn.Conv2d(in_c, out_c, kernel_size=3, stride=stride, padding=1) def upsample(scale_factor): return nn.Upsample(scale_factor=scale_factor, mode='bilinear') class HRNet(nn.Module): """ For model reference see Figure 2 of the paper https://arxiv.org/pdf/1904.11617v1.pdf. Naming convention used. I refer to vertical layers as a single layer, so from left to right we have 8 layers excluding the input image. E.g. layer 1 contains the 500x500x16 block layer 2 contains 500x500x32 and 250x250x32 blocks and so on self.layer{x}_{y}: x :- the layer number, as explained above y :- the index number for that function starting from 1. So if layer 3 has two downsample functions I write them as `downsample3_1`, `downsample3_2` """ def __init__(self): super().__init__() self.layer1_1 = BottleneckBlock(3, 16) self.layer2_1 = BottleneckBlock(16, 32) self.downsample2_1 = conv_down(16, 32) self.layer3_1 = BottleneckBlock(32, 32) self.layer3_2 = BottleneckBlock(32, 32) self.downsample3_1 = conv_down(32, 32) self.downsample3_2 = conv_down(32, 32, stride=4) self.downsample3_3 = conv_down(32, 32) self.layer4_1 = BottleneckBlock(64, 64) self.layer5_1 = BottleneckBlock(192, 64) self.layer6_1 = BottleneckBlock(64, 32) self.layer7_1 = BottleneckBlock(32, 16) self.layer8_1 = conv_down(16, 3, stride=1) def forward(self, x): map1_1 = self.layer1_1(x) map2_1 = self.layer2_1(map1_1) map2_2 = self.downsample2_1(map1_1) map3_1 = torch.cat((self.layer3_1(map2_1), upsample(map2_2, 2)), 1) map3_2 = torch.cat((self.downsample3_1(map2_1), self.layer3_2(map2_2)), 1) map3_3 = torch.cat((self.downsample3_2(map2_1), self.downsample3_3(map2_2)), 1) map4_1 = torch.cat((self.layer4_1(map3_1), upsample(map3_2, 2), upsample(map3_3, 4)), 1) out = self.layer5_1(map4_1) out = self.layer6_1(out) out = self.layer7_1(out) out = self.layer8_1(out) return out ###Output _____no_output_____ ###Markdown Create utility functions for image loading ###Code def load_image(path, size=None): """ Resize img to size, size should be int and also normalize the image using imagenet_stats """ img = Image.open(path) if size is not None: img = img.resize((size, size)) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ]) img = transform(img).unsqueeze(0) return img def im_convert(img): """ Convert img from pytorch tensor to numpy array, so we can plot it. It follows the standard method of denormalizing the img and clipping the outputs Input: img :- (batch, channel, height, width) Output: img :- (height, width, channel) """ img = img.to('cpu').clone().detach() img = img.numpy().squeeze(0) img = img.transpose(1, 2, 0) img = img * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406)) img = img.clip(0, 1) return img def get_features(img, model, layers=None): """ Use VGG19 to extract features from the intermediate layers. """ if layers is None: layers = { '0': 'conv1_1', # style layer '5': 'conv2_1', # style layer '10': 'conv3_1', # style layer '19': 'conv4_1', # style layer '28': 'conv5_1', # style layer '21': 'conv4_2' # content layer } features = {} x = img for name, layer in model._modules.items(): x = layer(x) if name in layers: features[layers[name]] = x return features def get_gram_matrix(img): """ Compute the gram matrix by converting to 2D tensor and doing dot product img: (batch, channel, height, width) """ b, c, h, w = img.size() img = img.view(b*c, h*w) gram = torch.mm(img, img.t()) return gram ###Output _____no_output_____ ###Markdown Write style_transfer.py Refer to train_model.ipynb for continuation of this notebook ###Code # For data, place your images in the img folder and name it as content.png and style.png # You can also input your images directly (for .py script) class Args: def __init__(self): self.img_root = 'src/imgs' self.content_img = 'content.png' self.style_img = 'style.png' self.use_batch = False self.bs = 16 self.use_gpu = True args = Args() if args.use_gpu: if torch.cuda.is_available(): device = torch.device('cuda') else: raise Exception('GPU is not available') else: device = torch.device('cpu') # Load VGG19 features vgg = vgg19(pretrained=True).features vgg = vgg.to(device) # We don't want to train VGG for param in vgg.parameters(): param.requires_grad_(False) # Load style net style_net = HRNet() style_net = style_net.to(device) torch.backends.cudnn.benchmark = True import os content_img = load_image(os.path.join(args.img_root, args.content_img), size=500) content_img = content_img.to(device) style_img = load_image(os.path.join(args.img_root, args.style_img)) style_img = style_img.to(device) content_img.size(), style_img.size() ###Output _____no_output_____
test/math-test/notebook.ipynb
###Markdown This is an example project where I want to extract parameters from piece of spectrum data that I have. My gaussian function has the following form:$f(x) = a \mathrm{e}{\frac{-(x-c)^2}{2c^2}} + d$Where $a$ is a normalisation coefficient, $b$ is the center point, $c$ defines with the width of the curve and $d$ is the height above the x axis.First lets load and plot the data ###Code %pylab inline %config InlineBackend.figure_format = 'retina' import numpy as np x, y = np.loadtxt('./data/data.txt').T plt.plot(x, y) plt.xlabel('Wavelength [nm]') plt.ylabel('Counts [a.u.]') ###Output _____no_output_____ ###Markdown Clearly the data is a nice gaussian, so lets fit the function to get the center point and full-width at half max, which is given by $FWHM = 2\sqrt{2 ln(2)}$First we import some code which contains the gauss equation, and the optimize function from scipy to do the curve fitting. ###Code from scipy.optimize import curve_fit def gauss(t, a, b, c, d): return a*np.exp(-((t-b)**2)/(2*c**2)) + d p0 = [700, 990, 2, 0] params, cov = curve_fit(gauss, x, y, p0=p0) err = np.sqrt(np.diag(cov)) print("a = %lf +- %lf" % (params[0], err[0])) print("b = %lf +- %lf" % (params[1], err[1])) print("c = %lf +- %lf" % (params[2], err[2])) print("d = %lf +- %lf" % (params[3], err[3])) ###Output a = 9940.234967 +- 112.462988 b = 995.014369 +- 0.013048 c = 1.002707 +- 0.013202 d = 761.728754 +- 14.103390
matrix_one/matrix_day_4.ipynb
###Markdown Imports ###Code import pandas as pd import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import cross_val_score cd "/content/drive/My Drive/Colab Notebooks/dw_matrix/matrix_one" df = pd.read_csv('data/shoes_prices.csv', low_memory=False) df.shape df.columns mean_price = np.mean(df.prices_amountmin) mean_price [3] *5 y_true = df.prices_amountmin y_pred = [mean_price] * y_true.shape[0] mean_absolute_error(y_true, y_pred) df.prices_amountmin.hist(bins=100) np.log1p(df.prices_amountmin).hist(bins=100) y_true = df.prices_amountmin y_pred = [np.median(y_true)] * y_true.shape[0] mean_absolute_error(y_true, y_pred) y_true = df.prices_amountmin price_log_mean = np.expm1(np.mean(np.log1p(y_true))) y_pred = [price_log_mean] * y_true.shape[0] mean_absolute_error(y_true, y_pred) df.columns df.brand.value_counts() df['brand_cat'] = df.brand.factorize()[0] df['manufacturer_cat'] = df.manufacturer.factorize()[0] features = ['brand_cat'] def run_model(features): X = df[features].values y = df.prices_amountmin.values model = DecisionTreeRegressor(max_depth=5) scores = cross_val_score(model, X,y,scoring='neg_mean_absolute_error') return np.mean(scores), np.std(scores) run_model(['brand_cat']) run_model(['manufacturer_cat']) run_model(['brand_cat', 'manufacturer_cat']) ###Output _____no_output_____
Learning_Basics.ipynb
###Markdown Tokenization ###Code from nltk.tokenize import sent_tokenize, word_tokenize nltk.download('punkt') document = """ We are having fun at major league hacking local hack day build! feel free to join the discord channel. also share about the session on social media. """ sentence = "send all the documents related to chapter 1,2,3,4 to [email protected]" sents = sent_tokenize(document) words = word_tokenize? words = word_tokenize ###Output _____no_output_____ ###Markdown words Stopward removal ###Code from nltk.corpus import stopwords nltk.download('stopwords') sw = set(stopwords.words("english")) print("has" in sw) sentence = "send all the documents related to chapter 1,2,3,4 to [email protected]".split() print(sentence) def remove_stopwords(text, stopwords): useful_words = [word for word in text if word not in stopwords] return useful_words remove_stopwords(sentence, sw) sentence = "send all the documents related to chapter 1,2,3,4 to [email protected]" from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer('[a-zA-Z@.]+') useful_text = tokenizer.tokenize(sentence) print(useful_text) ###Output ['send', 'all', 'the', 'documents', 'related', 'to', 'chapter', 'to', '[email protected]'] ###Markdown Stemming ###Code document = """ I like this session and I liked all the sessions. I am liking everything. We are having fun at major league hacking local hack day build! feel free to join the discord channel. also share about the session on social media. """ from nltk.stem import PorterStemmer ps = PorterStemmer() ps.stem('liking') corpus = [ 'Indian cricket team will win World Cup, says Capt. Virat Kohli. World cup will be held at Sri Lanka.', 'We will win next Lok Sabha Elections, says confident Indian PM', 'The nobel laurate won the hearts of the people', 'The movie Raazi is an exciting Indian Spy thriller based upon a real story' ] from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer() vectorized_corpus = cv.fit_transform(corpus) vectorized_corpus = vectorized_corpus.toarray() print(vectorized_corpus[3]) print(cv.vocabulary_) ###Output {'indian': 12, 'cricket': 6, 'team': 31, 'will': 37, 'win': 38, 'world': 40, 'cup': 7, 'says': 27, 'capt': 4, 'virat': 35, 'kohli': 14, 'be': 3, 'held': 11, 'at': 1, 'sri': 29, 'lanka': 15, 'we': 36, 'next': 19, 'lok': 17, 'sabha': 26, 'elections': 8, 'confident': 5, 'pm': 23, 'the': 32, 'nobel': 20, 'laurate': 16, 'won': 39, 'hearts': 10, 'of': 21, 'people': 22, 'movie': 18, 'raazi': 24, 'is': 13, 'an': 0, 'exciting': 9, 'spy': 28, 'thriller': 33, 'based': 2, 'upon': 34, 'real': 25, 'story': 30} ###Markdown vectorisation with stopword removal ###Code def myTokenizer(document): words = tokenizer.tokenize(document.lower()) # this is nltk one # remove stopwards words = remove_stopwords(words, sw) return words myTokenizer('this is some function') cv = CountVectorizer(tokenizer=myTokenizer) vectorizedCorpus = cv.fit_transform(corpus).toarray() print(len(vectorizedCorpus[0])) print(cv.vocabulary_) ###Output _____no_output_____
ml_course/ipynbfiles/MCQ1.ipynb
###Markdown Microsoft Python Exam Preparation MCQ Set1: 20 Questions--- **Q1 What Will Be The Output Of The Following Code Snippet?**```pythona=[1,2,3,4,5,6,7,8,9]print(a[::2])```1. [1,2] 2. [8,9]3. [1,3,5,7,9]4. [1,2,3] >Answer: *3. [1,3,5,7,9]* ###Code a=[1,2,3,4,5,6,7,8,9] print(a[::2]) ###Output [1, 3, 5, 7, 9] ###Markdown ---**Q2 Which of the following statements create a dictionary?**1. d = {}2. d = {'john':40, 'peter':45}3. d = {40:'john', 45:'peter'}4. All of the mentioned>Answer: *4. All of the mentioned* ###Code d1 = {} d2 = {"john":40, "peter":45} d3 = {40:"john", 45:"peter"} print(type(d1),type(d2),type(d3)) ###Output <class 'dict'> <class 'dict'> <class 'dict'> ###Markdown ---**Q3 Read the code shown below carefully and pick out the keys?**```pythond = {"john":40, "peter":45}```1. “john”, 40, 45, and “peter”2. “john” and “peter”3. 40 and 454. d = (40:”john”, 45:”peter”)>Answer: *2. “john” and “peter”* ###Code d = {"john":40, "peter":45} d.keys() ###Output _____no_output_____ ###Markdown ---**Q4 What Will Be The Output Of The Following Code Snippet?**```pythona=[1,2,3,4,5]print(a[3:0:-1])```1. Syntax error2. [4, 3, 2]3. [4, 3]4. [4, 3, 2, 1]>Answer: *2. [4,3,2]* ###Code a=[1,2,3,4,5] print(a[3:0:-1]) ###Output [4, 3, 2] ###Markdown ---**Q5 What Will Be TheOutput Of The Following Code Snippet?**```python init_tuple_a = 'a', 'b'init_tuple_b = ('a', 'b')print (init_tuple_a == init_tuple_b)```1. 02. 13. False4. True>Answer: *4. True* ###Code init_tuple_a = 'a', 'b' init_tuple_b = ('a', 'b') print (init_tuple_a == init_tuple_b) ###Output True ###Markdown ---**Q6 What Will Be The Output Of The Following Code Snippet?**```pythoninit_tuple_a = '1', '2'init_tuple_b = ('3', '4')print (init_tuple_a + init_tuple_b)```1. (1, 2, 3, 4)2. (‘1’, ‘2’, ‘3’, ‘4’)3. [‘1’, ‘2’, ‘3’, ‘4’]4. None>Answer: *2. ('1','2','3','4')* ###Code init_tuple_a = '1', '2' init_tuple_b = ('3', '4') print (init_tuple_a + init_tuple_b) ###Output ('1', '2', '3', '4') ###Markdown ---**Q7 What Will Be The Output Of The Following Code Snippet?**```pythoninit_tuple_a = 1, 2init_tuple_b = (3, 4)[print(sum(x)) for x in [init_tuple_a + init_tuple_b]]```1. Nothing gets printed.2. 43. 104. TypeError: unsupported operand type>Answer: *3. 10* ###Code init_tuple_a = 1, 2 init_tuple_b = (3, 4) [print(sum(x)) for x in [init_tuple_a + init_tuple_b]] ###Output 10 ###Markdown ---**Q8 What will be the output?**```pythond = {"john":40, "peter":45}print(list(d.keys()))```1. [“john”, “peter”]2. [“john”:40, “peter”:45]3. (“john”, “peter”)4. (“john”:40, “peter”:45)>Answer:*1. [“john”, “peter”]* ###Code d = {"john":40, "peter":45} print(list(d.keys())) ###Output ['john', 'peter'] ###Markdown ---**Q9 You have a list which contains ten elements. Which of the following uses of range() would produce a list of the indexes in the list?**1. range(1,10)2. range(10)3. range(0,9)4. range(1,9)>Answer: *2. range(10)* ###Code for i in range(10): print(i,end=';') ###Output 0;1;2;3;4;5;6;7;8;9; ###Markdown ---**Q10 What is the output of the following?**```python i = 2while True: if i%3 == 0: break print(i) i += 2```1. 2 4 6 8 10 2. 2 4 3. 2 34. error>Answer: *2. 2 4* ###Code i = 2 while True: if i%3 == 0: break print(i) i += 2 ###Output 2 4 ###Markdown ---**Q11 What is the output of the following?**```pythonx = "abcdef"i = "i"while i in x: print(i, end=" ")``` 1. no output 2. i i i i i i ... 3. a b c d e f 4. abcdef>Answer: *1. no output* ###Code x = "abcdef" i = "i" while i in x: print(i, end=" ") ###Output _____no_output_____ ###Markdown ---**Q12 What is the output of the following?**```pythonx = 'abcd'for i in x: print(i.upper())```1. a b c d 2. A B C D 3. a B C D 4. error>Answer: *2. A B C D* ###Code x = 'abcd' for i in x: print(i.upper()) ###Output A B C D ###Markdown ---**Q13 What is the output of the following code?**```pythonnums = set([1,1,2,3,3,3,4,4])print(len(nums))```1. 72. Error, invalid syntax for formation of set3. 44. 8>Answer: *3. 4* ###Code nums = set([1,1,2,3,3,3,4,4]) print(len(nums)) ###Output 4 ###Markdown ---**Q14 Which of the following statements is used to create an empty set?**1. { }2. set()3. [ ]4. ( )>Answer: *2. set()* ###Code x = {} y = [] z = () m = set() print(type(x),type(y),type(z),type(m)) ###Output <class 'dict'> <class 'list'> <class 'tuple'> <class 'set'> ###Markdown ---**Q15 Suppose t = (1, 2, 4, 3), which of the following is incorrect?**1. print(t[3])2. t[3] = 453. print(max(t))4. print(len(t))>Answer: *2. t[3] = 45* ###Code t = (1, 2, 4, 3) t[3]=9 ###Output _____no_output_____ ###Markdown ---**Q16 What does the following code print to the console?**```pythonif False: print("Nissan")elif True: print("Ford")elif True: print("BMW")else: print("Audi")``` 1. Ford2. Ford BMW3. BMW4. None Of The Above>Answer: *1. Ford* ###Code if False: print("Nissan") elif True: print("Ford") elif True: print("BMW") else: print("Audi") ###Output Ford ###Markdown ---**Q17 Suppose list1 is [1, 3, 2], What is list1 * 2 ?**1. [2, 6, 4] 2. [1, 3, 2, 1, 3] 3. [1, 3, 2, 1, 3, 2] 4. [1, 3, 2, 3, 2, 1]>Answer: *3. [1, 3, 2, 1, 3, 2]* ###Code list1 = [1,3,2] list1*2 ###Output _____no_output_____ ###Markdown ---**Q18 What is the output when we execute list(“hello”)?**1. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]2. [‘hello’]3. [‘llo’]4. [‘olleh’]>Answer: *1. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]* ###Code list('hello') ###Output _____no_output_____ ###Markdown ---**Q19 Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1] ?**1. [2, 33, 222, 14]2. Error3. 254. [25, 14, 222, 33, 2]>Answer: *1. [2, 33, 222, 14]* ###Code list1 = [2, 33, 222, 14, 25] list1[:-1] ###Output _____no_output_____ ###Markdown ---**Q-20 Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing operation ?**1. print(list1[0])2. print(list1[:2])3. print(list1[:-2])4. all of the mentioned>Answer: *4. all of the mentioned* ###Code list1 = [4, 2, 2, 4, 5, 2, 1, 0] print(list1[0]) print(list1[:2]) print(list1[:-2]) ###Output 4 [4, 2] [4, 2, 2, 4, 5, 2]
module2/LS_DS9_122_Sampling_Confidence_Intervals_and_Hypothesis_Testing_Assignment.ipynb
###Markdown Assignment - Build a confidence intervalA confidence interval refers to a neighborhood around some point estimate, the size of which is determined by the desired p-value. For instance, we might say that 52% of Americans prefer tacos to burritos, with a 95% confidence interval of +/- 5%.52% (0.52) is the point estimate, and +/- 5% (the interval $[0.47, 0.57]$) is the confidence interval. "95% confidence" means a p-value $\leq 1 - 0.95 = 0.05$.In this case, the confidence interval includes $0.5$ - which is the natural null hypothesis (that half of Americans prefer tacos and half burritos, thus there is no clear favorite). So in this case, we could use the confidence interval to report that we've failed to reject the null hypothesis.But providing the full analysis with a confidence interval, including a graphical representation of it, can be a helpful and powerful way to tell your story. Done well, it is also more intuitive to a layperson than simply saying "fail to reject the null hypothesis" - it shows that in fact the data does *not* give a single clear result (the point estimate) but a whole range of possibilities.maiormarso.comHow is a confidence interval built, and how should it be interpreted? It does *not* mean that 95% of the data lies in that interval - instead, the frequentist interpretation is "if we were to repeat this experiment 100 times, we would expect the average result to lie in this interval ~95 times."For a 95% confidence interval and a normal(-ish) distribution, you can simply remember that +/-2 standard deviations contains 95% of the probability mass, and so the 95% confidence interval based on a given sample is centered at the mean (point estimate) and has a range of +/- 2 (or technically 1.96) standard deviations.Different distributions/assumptions (90% confidence, 99% confidence) will require different math, but the overall process and interpretation (with a frequentist approach) will be the same.Your assignment - using the data from the prior module ([congressional voting records](https://archive.ics.uci.edu/ml/datasets/Congressional+Voting+Records)): Confidence Intervals:1. Generate and numerically represent a confidence interval2. Graphically (with a plot) represent the confidence interval3. Interpret the confidence interval - what does it tell you about the data and its distribution? Chi-squared tests:4. Take a dataset that we have used in the past in class that has **categorical** variables. Pick two of those categorical variables and run a chi-squared tests on that data - By hand using Numpy - In a single line using Scipy ###Code !wget https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data import pandas as pd cols = [ 'party', 'handicapped-infants', 'water-project', 'budget', 'physician-fee-freeze', 'el-salvador-aid', 'religious-groups', 'anti-satellite-ban', 'aid-to-contras', 'mx-missile', 'immigration', 'synfuels', 'education', 'right-to-sue', 'crime', 'duty_free', 'south_Africa'] df = pd.read_csv('house-votes-84.data', names=cols) df.head(1) import numpy as np import pandas as pd df=df.replace({'?': 'NaN', 'n':0.0, 'y':1.0,'republican':1,'democrat':0}) #df=df.replace({'?':np.NaN}maior) df.head(8) df.index df.shape df.party.value_counts() df = df.astype(float) rep = df[df['party'] ==1] rep.head() rep = rep.astype(float) # rep.sum(axis = 0, skipna = True) dem = df[df['party'] ==0] dem.head() dem = dem.astype(float) # dem.sum(axis = 0, skipna = True) df = df.astype(float) from scipy.stats import t from scipy import stats CI = t.interval(0.95,df['budget']) a = df['budget'].dropna() confidence_interval = t.interval(0.95, len(a)-1, loc=np.mean(a), scale=stats.sem(a)) confidence_interval budget_m = df['budget'].mean() print(budget_m) mean_dem_budget = dem['budget'].mean() print(mean_dem_budget) std_error_dem_budget = stats.sem(dem['budget'], nan_policy='omit') print(std_error_dem_budget) t_stat_dem_budget = stats.ttest_1samp(dem['budget'], .5, nan_policy='omit') print(t_stat_dem_budget) t_stat_dem_budget[0] CI_plus = mean_dem_budget + t_stat_dem_budget[0]*std_error_dem_budget print(CI_plus) CI_minus = mean_dem_budget - t_stat_dem_budget[0]*std_error_dem_budget print(CI_minus) import seaborn as sns import matplotlib.pyplot as plt sns.kdeplot(dem['budget']) plt.axvline(x=CI_plus, color='red') plt.axvline(x=CI_minus, color='red') plt.show() ###Output /usr/local/lib/python3.6/dist-packages/statsmodels/nonparametric/kde.py:447: RuntimeWarning: invalid value encountered in greater X = X[np.logical_and(X > clip[0], X < clip[1])] # won't work for two columns. /usr/local/lib/python3.6/dist-packages/statsmodels/nonparametric/kde.py:447: RuntimeWarning: invalid value encountered in less X = X[np.logical_and(X > clip[0], X < clip[1])] # won't work for two columns. ###Markdown 3.1 what does it tell you about the data and its distribution?1. My null Hypothosis is that they are voting evenly.2. Alternative would also be voting even.3. The confidence level is .95 4. Using the mean for the sample mean, there is no bell and the mean line is standing vulnerable with the cutoff lines in an awkward position.See 3.2 below ###Code confidence = 0.95 (1 + confidence) / 2.0 # This converts confidence to two-tailed confidence_level = .95 dof = 431 - 1 stats.t.ppf((1 + confidence_level) / 2, dof) original_sample=a sample_means = [] for x in range(3000): m = np.random.choice(original_sample,300).mean() sample_means.append(m) import seaborn as sns import matplotlib.pyplot as plt sns.distplot(sample_means) plt.axvline(x=original_sample.mean()) plt.axvline(x=confidence_interval[0], color='r') plt.axvline(x=confidence_interval[1], color='r') plt.xlim(0, 1) df['budget'].value_counts() ###Output _____no_output_____ ###Markdown 3.2 what does it tell you about the data and its distribution?1. My null Hypothosis is that they are voting evenly.2. Alternative would also be voting even.3. The confidence level is .95 4. Using 3000 for the sample mean, the bell stands straight up narrow towering tightly between the cutoff lines. ###Code #m[0][1][1] sample_means = [] for x in range(3000): m = np.random.choice(original_sample,300).mean() sample_means.append(m) from scipy.stats import bayes_mvs m=bayes_mvs(original_sample) import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import matplotlib.pyplot as plt sns.distplot(sample_means) plt.axvline(x=m[0][0], color='r') plt.axvline(x=m[0][1][0], color='r') plt.axvline(x=m[0][1][1], color='r') plt.title('Budget Bill') plt.ylabel('votes') plt.xlim(0, 1) #dem['budget'].plot.hist(); df = df.astype(float) demlist = dem["budget"].tolist() demlist print(*demlist, sep=",") replist = rep["budget"].tolist() replist print(*replist, sep = ",") ddf=df[['party','budget','crime']] ddf import pandas as pd dc=df[['party','budget','crime']] ddf[['budget','crime']] contingency_table = pd.crosstab(df['party'], df['budget']) contingency_table e1 = (contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum() e2 = (contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum() e3 = (contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum() e4 = (contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum() contingency_table = pd.crosstab(df['party'], df['budget']) contingency_table ((contingency_table[0.0][0.0]-(contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum() )**2) / ((contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum()) ((contingency_table[1.0][0.0]-(contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum() )**2) / ((contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[0.0].sum()) ((contingency_table[0.0][1.0]-(contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum() )**2) / ((contingency_table[0.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum()) ((contingency_table[1.0][1.0]-(contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum() )**2) / ((contingency_table[1.0].sum()/contingency_table.sum().sum())*contingency_table.loc[1.0].sum()) #maior 54.878823449528504+37.09201110620308+87.00301278583787+58.80440785129753 chi_squared, p_value, dof, expected = stats.chi2_contingency(contingency_table) print(f"Chi-Squared: {chi_squared}") print(f"P-value: {p_value}") print(f"Degrees of Freedom: {dof}") print("Expected: \n", np.array(expected)) ###Output Chi-Squared: 234.65408769323486 P-value: 5.759792112623893e-53 Degrees of Freedom: 1 Expected: [[104.85849057 155.14150943] [ 66.14150943 97.85849057]]
Kaggle_Challenge_X7.ipynb
###Markdown ###Code # Installs %%capture !pip install --upgrade category_encoders plotly # Imports import os, sys os.chdir('/content') !git init . !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge.git !git pull origin master !pip install -r requirements.txt os.chdir('module1') # Imports import pandas as pd import numpy as np import math import sklearn sklearn.__version__ from sklearn.model_selection import train_test_split # Import the models from sklearn.linear_model import LogisticRegressionCV from sklearn.pipeline import make_pipeline # Import encoder and scaler and imputer import category_encoders as ce from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer # Import random forest classifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score def main_program(): def wrangle(X): # Wrangles train, validate, and test sets X = X.copy() # Convert date_recorded to datetime X['date_recorded'] = pd.to_datetime(X['date_recorded'], infer_datetime_format=True) # Extract components from date_recorded and drop the original column X['year_recorded'] = X['date_recorded'].dt.year X['month_recorded'] = X['date_recorded'].dt.month X['day_recorded'] = X['date_recorded'].dt.day X = X.drop(columns='date_recorded') # Engineer new feature years - construction_year to date_recorded X.loc[X['construction_year'] == 0, 'construction_year'] = np.nan X['years'] = X['year_recorded'] - X['construction_year'] # Remove latitude outliers X['latitude'] = X['latitude'].replace(-2e-08, np.nan) # Features with many zero's are likely nan's cols_with_zeros = ['construction_year', 'longitude', 'latitude', 'gps_height', 'population', 'amount_tsh'] for col in cols_with_zeros: X[col] = X[col].replace(0, np.nan) # Impute mean for years X.loc[X['years'].isna(), 'years'] = X['years'].mean() #X.loc[X['pump_age'].isna(), 'pump_age'] = X['pump_age'].mean() # Impute mean for longitude and latitude based on region average_lat = X.groupby('region').latitude.mean().reset_index() average_long = X.groupby('region').longitude.mean().reset_index() shinyanga_lat = average_lat.loc[average_lat['region'] == 'Shinyanga', 'latitude'] shinyanga_long = average_long.loc[average_long['region'] == 'Shinyanga', 'longitude'] X.loc[(X['region'] == 'Shinyanga') & (X['latitude'] > -1), ['latitude']] = shinyanga_lat[17] X.loc[(X['region'] == 'Shinyanga') & (X['longitude'].isna()), ['longitude']] = shinyanga_long[17] mwanza_lat = average_lat.loc[average_lat['region'] == 'Mwanza', 'latitude'] mwanza_long = average_long.loc[average_long['region'] == 'Mwanza', 'longitude'] X.loc[(X['region'] == 'Mwanza') & (X['latitude'] > -1), ['latitude']] = mwanza_lat[13] X.loc[(X['region'] == 'Mwanza') & (X['longitude'].isna()) , ['longitude']] = mwanza_long[13] #X.loc[X['amount_tsh'].isna(), 'amount_tsh'] = 0 # Clean installer X['installer'] = X['installer'].str.lower() X['installer'] = X['installer'].str[:4] X['installer'].value_counts(normalize=True) tops = X['installer'].value_counts()[:15].index X.loc[~X['installer'].isin(tops), 'installer'] = 'other' # Bin lga #tops = X['lga'].value_counts()[:10].index #X.loc[~X['lga'].isin(tops), 'lga'] = 'Other' # Bin subvillage tops = X['subvillage'].value_counts()[:25].index X.loc[~X['subvillage'].isin(tops), 'subvillage'] = 'Other' # Impute mean for a feature based on latitude and longitude def latlong_conversion(feature, pop, long, lat): radius = 0.1 radius_increment = 0.3 if math.isnan(pop): pop_temp = 0 while pop_temp <= 1 and radius <= 2: lat_from = lat - radius lat_to = lat + radius long_from = long - radius long_to = long + radius df = X[(X['latitude'] >= lat_from) & (X['latitude'] <= lat_to) & (X['longitude'] >= long_from) & (X['longitude'] <= long_to)] pop_temp = df[feature].mean() radius = radius + radius_increment else: pop_temp = pop if np.isnan(pop_temp): new_pop = X_train[feature].mean() else: new_pop = pop_temp return new_pop X.loc[X['population'].isna(), 'population'] = X['population'].mean() #X['population'] = X.apply(lambda x: latlong_conversion('population', x['population'], x['longitude'], x['latitude']), axis=1) # Impute mean for tsh based on mean of source_class/basin/waterpoint_type_group #def tsh_calc(tsh, source, base, waterpoint): # if math.isnan(tsh): # if (source, base, waterpoint) in tsh_dict: # new_tsh = tsh_dict[source, base, waterpoint] # return new_tsh # else: # return tsh # return tsh #temp = X[~X['amount_tsh'].isna()].groupby(['source_class', # 'basin', # 'waterpoint_type_group'])['amount_tsh'].mean() #tsh_dict = dict(temp) #X['amount_tsh'] = X.apply(lambda x: tsh_calc(x['amount_tsh'], x['source_class'], x['basin'], x['waterpoint_type_group']), axis=1) # Drop unneeded columns unusable_variance = ['recorded_by', 'id', 'num_private', 'wpt_name'] X = X.drop(columns=unusable_variance) return X # Merge train_features.csv & train_labels.csv train = pd.merge(pd.read_csv('../data/tanzania/train_features.csv'), pd.read_csv('../data/tanzania/train_labels.csv')) # Read test_features.csv & sample_submission.csv test = pd.read_csv('../data/tanzania/test_features.csv') sample_submission = pd.read_csv('../data/tanzania/sample_submission.csv') # Split train into train & val. Make val the same size as test. target = 'status_group' train, val = train_test_split(train, train_size=0.99, test_size=0.01, stratify=train[target], random_state=42) # Wrangle train, validate, and test sets in the same way train = wrangle(train) val = wrangle(val) test = wrangle(test) # Arrange data into X features matrix and y target vector X_train = train.drop(columns=target) y_train = train[target] X_val = val.drop(columns=target) y_val = val[target] X_test = test # Make pipeline! pipeline = make_pipeline( ce.OrdinalEncoder(), SimpleImputer(strategy='mean'), RandomForestClassifier(n_estimators=1400, random_state=42, min_samples_split=5, min_samples_leaf=1, max_features='auto', max_depth=30, bootstrap=True, n_jobs=-1, verbose = 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.ensemble import RandomForestRegressor from sklearn.model_selection import RandomizedSearchCV # Number of trees in random forest n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)] # Number of features to consider at every split max_features = ['auto', 'sqrt'] # Maximum number of levels in tree max_depth = [int(x) for x in np.linspace(10, 110, num = 11)] max_depth.append(None) # Minimum number of samples required to split a node min_samples_split = [2, 5, 10] # Minimum number of samples required at each leaf node min_samples_leaf = [1, 2, 4] # Method of selecting samples for training each tree bootstrap = [True, False] # Create the random grid random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} print(random_grid) y_train = np.where(y_train == 'functional', 1, y_train) y_train = np.where(y_train == 'non functional', 2, y_train) y_train = np.where(y_train == 'functional needs repair', 3, y_train) pipeline = make_pipeline ( ce.OrdinalEncoder(), SimpleImputer(strategy='mean'), RandomizedSearchCV(estimator = RandomForestRegressor(), param_distributions = random_grid, n_iter = 5, verbose=2, random_state=42, n_jobs = -1) ) pipeline.fit(X_train, y_train) pd.set_option('display.max_rows', 200) model = pipeline.named_steps['randomizedsearchcv'] best = pd.Series(model.best_params_) print(best) # pd.set_option('display.max_rows', 200) # model = pipeline.named_steps['randomforestclassifier'] # encoder = pipeline.named_steps['ordinalencoder'] # encoded_columns = encoder.transform(X_train).columns # importances = pd.Series(model.feature_importances_, encoded_columns) # importances.sort_values(ascending=False) # assert all(X_test.columns == X_train.columns) # y_pred = pipeline.predict(X_test) # submission = sample_submission.copy() # submission['status_group'] = y_pred # submission.to_csv('/content/submission-f8.csv', index=False) main_program() #for i in range(3, 10): # main_program(i) #for i in range(1, 6): # i = i * 5 # print('lga bins: ', i) # main_program(i) #i = 25 #for j in range(2, 6): # j = j * 5 # for k in range(2, 6): # k = k * 5 # print('installer bins: ', i, 'funder bins: ', j,'subvillage bins: ', k) # main_program( i, j, k) #pd.set_option('display.max_rows', 200) #model = pipeline.named_steps['randomforestclassifier'] #encoder = pipeline.named_steps['ordinalencoder'] #encoded_columns = encoder.transform(X_train).columns #importances = pd.Series(model.feature_importances_, encoded_columns) #importances.sort_values(ascending=False) #assert all(X_test.columns == X_train.columns) #y_pred = pipeline.predict(X_test) #submission = sample_submission.copy() #submission['status_group'] = y_pred #submission.to_csv('/content/submission-f2.csv', index=False) ###Output _____no_output_____
Project4/Notebooks/AI2_HW4_parts_1_2_andreas_spanopoulos.ipynb
###Markdown Install useful libraries ###Code !pip install sentence_transformers ###Output Requirement already satisfied: sentence_transformers in /usr/local/lib/python3.6/dist-packages (0.4.1.2) Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (1.4.1) Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (4.41.1) Requirement already satisfied: transformers<5.0.0,>=3.1.0 in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (4.2.1) Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (0.22.2.post1) Requirement already satisfied: sentencepiece in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (0.1.95) Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (3.2.5) Requirement already satisfied: torch>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (1.7.0+cu101) Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from sentence_transformers) (1.19.5) Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (2.23.0) Requirement already satisfied: tokenizers==0.9.4 in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (0.9.4) Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (20.8) Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (2019.12.20) Requirement already satisfied: dataclasses; python_version < "3.7" in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (0.8) Requirement already satisfied: sacremoses in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (0.0.43) Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (3.3.0) Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers<5.0.0,>=3.1.0->sentence_transformers) (3.0.12) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sentence_transformers) (1.0.0) Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from nltk->sentence_transformers) (1.15.0) Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch>=1.6.0->sentence_transformers) (3.7.4.3) Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch>=1.6.0->sentence_transformers) (0.16.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers<5.0.0,>=3.1.0->sentence_transformers) (2020.12.5) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers<5.0.0,>=3.1.0->sentence_transformers) (3.0.4) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers<5.0.0,>=3.1.0->sentence_transformers) (1.24.3) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers<5.0.0,>=3.1.0->sentence_transformers) (2.10) Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers<5.0.0,>=3.1.0->sentence_transformers) (2.4.7) Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers<5.0.0,>=3.1.0->sentence_transformers) (7.1.2) Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->transformers<5.0.0,>=3.1.0->sentence_transformers) (3.4.0) ###Markdown Imports ###Code import os import re import time import json import torch import pickle import nltk import nltk.data nltk.download('punkt') from sentence_transformers import SentenceTransformer, util from preprocessing import * ###Output _____no_output_____ ###Markdown Preprocessing Start by creating the class that will be used to store an article If the Dataset has already been parsed and stored in a pickle file, set this variable to True, to avoid parsing it again. If you are running this Notebook for the first time, then of course, the Dataset has not been parsed, so set the variable to False. ###Code has_already_been_parsed = True class CovidArticle: """ class used to keep the information of an article """ def __init__(self, article_data): tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') self._id = article_data["paper_id"] self._name = article_data["metadata"]["title"] self._abstract = self._preprocess_abstract(article_data["abstract"], tokenizer) self._corpus_text = self._preprocess_bodytext(article_data["body_text"], tokenizer) @property def id(self): return self._id @property def title(self): return self._name @property def abstract(self): return self._abstract @property def corpus(self): return self._corpus_text @id.setter def id(self, _id): self._id = _id @title.setter def title(self, _title): self._name = _title @abstract.setter def abstract(self, _abstract): self._abstract = _abstract @corpus.setter def corpus(self, _corpus): self._corpus_text = _corpus @staticmethod def _preprocess(text_data): result = remove_urls(text_data) result = remove_references(result) result = remove_multiple_full_stops(result) result = remove_et_al(result) result = remove_figure_references(result) result = remove_multiple_whitespace(result) return result def _preprocess_abstract(self, abstract, tokenizer): if not abstract: sentences = [""] else: sentences = [] for paragraph in abstract: sentences = sentences + self._preprocess_paragraph(paragraph, tokenizer)[1] return ("Abstract.", sentences) def _preprocess_bodytext(self, body_text, tokenizer): return [self._preprocess_paragraph(paragraph, tokenizer) for paragraph in body_text] if body_text else [("", "")] def _preprocess_paragraph(self, paragraph, tokenizer): return (paragraph['section'] + '.', [sentence.strip() for sentence in tokenizer.tokenize(self._preprocess(paragraph['text'])) if sentence != '.']) @property def summary(self): """ returns a list containing the title + the sentences in the abtract plus section names """ sentences = [paragraph_and_section[0] for paragraph_and_section in self._corpus_text if paragraph_and_section[0] != '.'] return list(set([self.title + '.', self._abstract[0], *self._abstract[1]] + sentences)) @property def text(self): """ returns all the text in the article: abstract + sections + paragraph text """ sentences = [self._abstract[0], *self._abstract[1]] for paragraph_and_section in self._corpus_text: if paragraph_and_section[0] != '.': sentences.append(paragraph_and_section[0]) if paragraph_and_section[1] != '.': sentences = sentences + paragraph_and_section[1] return sentences def get_section_from_index(self, idx): """ given an index of a sentence in the whole text of the article, it returns the section and the index of the sentence inside the section """ text = self.text abstract = self.abstract corpus_text = self.corpus length_of_abstract = 1 + len(abstract[1]) target_index = None target_section = None # indexed sentence is in abstract if idx < length_of_abstract: target_index = idx target_section = abstract # else, indexed sentence is in body text else: current_index = length_of_abstract for paragraph in corpus_text: paragraph_length = 1 + len(paragraph[1]) if idx <= current_index + paragraph_length: target_index = idx - current_index target_section = paragraph break else: current_index += paragraph_length return target_index, target_section ###Output _____no_output_____ ###Markdown Helper method to parse all the articles ###Code def get_articles(root_dir, filenames, log_every=None, stop_at=None): """ :param str root_dir: The root directory containing all the articles in json format. :param list[str] filenames: A list containing the names of the json files. :param int log_every: Frequency of prints that show how many files have been parsed at a specific timestep. :param int stop_at: The number of articles to parsed. If None, then all the articles available will be parsed. :return: A list containing Article objectes, one for every article. :rtype: list[CovidArticle] """ covid_articles = [] for filename in filenames: full_filepath = os.path.join(root_dir, filename) with open(full_filepath) as f: data = json.load(f) covid_articles.append(CovidArticle(data)) if log_every is not None and len(covid_articles) % log_every == 0: print('{} articles parsed'.format(len(covid_articles))) if stop_at is not None and len(covid_articles) == stop_at: break return covid_articles ###Output _____no_output_____ ###Markdown Get a list with the articles either by- Parsing it using the ``` get_articles() ``` function, which takes ~ 1 hour, and then saving it in a pickle file.- Loading an already parsed pickle file containing the list.I would suggest first parsing the Dataset in CPU, and then switching to GPU to load it. ###Code # edit your paths here root_dir = os.path.join('.', 'drive', 'My Drive', 'Colab Notebooks', 'AI2', 'Project4', 'Dataset', 'comm_use_subset') save_path = os.path.join('.', 'drive', 'My Drive', 'Colab Notebooks', 'AI2', 'Project4', 'Preprocessed_Dataset', 'processed_articles.pickle') # if the dataset is to be parsed for the first time if not has_already_been_parsed: filenames = sorted(os.listdir(root_dir)) articles = get_articles(root_dir, filenames, log_every=100) with open(save_path, 'wb') as f: pickle.dump(articles, f) # else, it has already been parsed, just load it else: with open(save_path, 'rb') as f: articles = pickle.load(f) len(articles) ###Output _____no_output_____ ###Markdown Let's take a look at IDs and the titles of the first 20 articles ###Code for article in articles[:20]: print('ID: {},\tTitle: {}'.format(article.id, article.title)) ###Output ID: 000b7d1517ceebb34e1e3e817695b6de03e2fa78, Title: Supplementary Information An eco-epidemiological study of Morbilli-related paramyxovirus infection in Madagascar bats reveals host-switching as the dominant macro-evolutionary mechanism ID: 00142f93c18b07350be89e96372d240372437ed9, Title: immunity to pathogens taught by specialized human dendritic cell subsets ID: 0022796bb2112abd2e6423ba2d57751db06049fb, Title: Public Health Responses to and Challenges for the Control of Dengue Transmission in High-Income Countries: Four Case Studies ID: 00326efcca0852dc6e39dc6b7786267e1bc4f194, Title: a section of the journal Frontiers in Pediatrics A Review of Pediatric Critical Care in Resource-Limited Settings: A Look at Past, Present, and Future Directions ID: 00352a58c8766861effed18a4b079d1683fec2ec, Title: MINI REVIEW Function of the Deubiquitinating Enzyme USP46 in the Nervous System and Its Regulation by WD40-Repeat Proteins ID: 0043d044273b8eb1585d3a66061e9b4e03edc062, Title: Evaluation of the tuberculosis programme in Ningxia Hui Autonomous region, the People's Republic of China: a retrospective case study ID: 0049ba8861864506e1e8559e7815f4de8b03dbed, Title: GPI-anchored single chain Fv -an effective way to capture transiently-exposed neutralization epitopes on HIV-1 envelope spike ID: 00623bf2715e25d3acacb3f210d6888ed840e3cb, Title: Transmissible gastroenteritis virus infection decreases arginine uptake by downregulating CAT-1 expression ID: 0072159e1ebecc889e9bcabb58bb45c47e18a403, Title: Chaperone-Mediated Autophagy Protein BAG3 Negatively Regulates Ebola and Marburg VP40-Mediated Egress ID: 007618ad76a3548195ab5d11c1e2459931c91cd1, Title: Molecular Sciences Monocytes and Macrophages as Viral Targets and Reservoirs ID: 007bf75961da42a7e0cc8e2855e5c208a5ec65c1, Title: The Murine Coronavirus Hemagglutinin-esterase Receptor-binding Site: A Major Shift in Ligand Specificity through Modest Changes in Architecture ID: 0080d3bd9fb92e022c27715c2d1249042aa998b8, Title: Rational Design of a Live Attenuated Dengue Vaccine: 29-O-Methyltransferase Mutants Are Highly Attenuated and Immunogenic in Mice and Macaques ID: 0089aa4b17549b9774f13a9e2e12a84fc827d60b, Title: The Domain-Specific and Temperature-Dependent Protein Misfolding Phenotype of Variant Medium-Chain acyl-CoA Dehydrogenase ID: 008c1ceaeffe7abc87b031af39fae2632fa72897, Title: AMS 3.0: prediction of post-translational modifications ID: 008d980cbcc283a9b707de3d9a02573dde8528ac, Title: A pilot study-genetic diversity and population structure of snow leopards of Gilgit-Baltistan, Pakistan, using molecular techniques ID: 009002e8a66b8c1df088cf04069629fd76b13bb9, Title: Epidemiological Characteristics of Imported Influenza A (H1N1) Cases during the 2009 Pandemic in Korea ID: 0093f9ae0861afc0d29fff935ae6a3af898cea00, Title: Emergence of infectious malignant thrombocytopenia in Japanese macaques (Macaca fuscata) by SRV-4 after transmission to a novel host ID: 0094b25e2500306fadbdfb41d520f2970bb086d3, Title: BMC Infectious Diseases Sex-and age-dependent association of SLC11A1 polymorphisms with tuberculosis in Chinese: a case control study ID: 00951716e01c8e0cc341770389fc38d1b5455210, Title: Knowledge of, attitudes toward, and preventive practices relating to cholera and oral cholera vaccine among urban high-risk groups: findings of a cross-sectional study in Dhaka, Bangladesh ID: 009892e02bc1a4c9abf6f547b979e68ecbde8087, Title: Viral respiratory tract infections in young children with cystic fibrosis: a prospective full-year seasonal study ###Markdown Let's also take a look at the contents of one article ###Code art = articles[3] art.id art.title art.abstract art.summary art.text ###Output _____no_output_____ ###Markdown Load the pre-trained models ###Code embedder1 = SentenceTransformer('stsb-distilbert-base') embedder2 = SentenceTransformer('stsb-roberta-base') ###Output _____no_output_____ ###Markdown Define Look-up dictionaries to avoid recomputing some embeddings Get the embeddings of the summaries of all the articles, for each model ###Code # should take ~ 15 mins on GPU for the whole Dataset index_to_summary_embeddings1 = {} for idx, article in enumerate(articles): index_to_summary_embeddings1[idx] = embedder1.encode(article.summary, convert_to_tensor=True) # should take ~ 27 mins on GPU for the whole Dataset index_to_summary_embeddings2 = {} for idx, article in enumerate(articles): index_to_summary_embeddings2[idx] = embedder2.encode(article.summary, convert_to_tensor=True) ###Output _____no_output_____ ###Markdown Also define dictionaries that will be used to store the embeddings of the whole articles, to avoid computing them twice ###Code index_to_article_embedding1 = {} index_to_article_embedding2 = {} ###Output _____no_output_____ ###Markdown Predict ###Code def max_similarity(corpus_embeddings, query_embedding, k=1): """ returns the indices and values (cosine similarity) of the sentences from the corpus with the top k cosine similarities with the query embedding """ cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0].cpu() return torch.topk(cos_scores, k=k) def relative_articles(articles, index_to_summary_embeddings, query_embedding, threshold=0.5): """ returns a list with the indices of the articles, for which a sentence in its summary with cosine similarity > threshold, exists """ return [idx for idx, article in enumerate(articles) if max_similarity(index_to_summary_embeddings[idx], query_embedding)[0][0] > threshold] def get_passage(corpus, best_sentence_idx, index_in_section, paragraph, embedder): """ given a sentence inside the corpus, it returns a string containing all the similar sentences that belong in the same section of the corpus """ best_sentence_embedding = embedder.encode([corpus[best_sentence_idx]], convert_to_tensor=True) previous_sentence_is_relevant = True next_sentence_is_relevant = True passage = corpus[best_sentence_idx] offset = 1 # while either the previous sentence of the next are relevant, keep appending them in the passage while previous_sentence_is_relevant is True or next_sentence_is_relevant is True: if index_in_section - offset < 0: previous_sentence_is_relevant = False elif index_in_section + offset >= len(paragraph): next_sentence_is_relevant = False if previous_sentence_is_relevant is True: previous_sentence = corpus[best_sentence_idx - offset] previous_sentence_embedding = embedder.encode([previous_sentence], convert_to_tensor=True) cosine_similarity = util.pytorch_cos_sim(best_sentence_embedding, previous_sentence_embedding)[0][0].cpu() if cosine_similarity < 0.5: previous_sentence_is_relevant = False else: passage = ' '.join([previous_sentence, passage]) if next_sentence_is_relevant is True: next_sentence = corpus[best_sentence_idx + offset] next_sentence_embedding = embedder.encode([next_sentence], convert_to_tensor=True) cosine_similarity = util.pytorch_cos_sim(best_sentence_embedding, next_sentence_embedding)[0][0].cpu() if cosine_similarity < 0.5: next_sentence_is_relevant = False else: passage = ' '.join([passage, next_sentence]) offset += 1 return passage # deprecated def threshold_is_ok(number_of_articles_included, min_articles=5, max_articles=150): """ returns a boolean that determines whether the number of articles that did not get filtered is acceptable """ return min_articles <= number_of_articles_included <= max_articles # deprecated def fix_threshold(number_of_articles_included, threshold, min_articles=5, max_articles=150, decrease_step=0.01, increase_step=0.05): """ computes a new value for a threshold, depending on how many articles were found relevant using the previous threshold """ if number_of_articles_included < min_articles: return threshold + increase_step elif number_of_articles_included > max_articles: return threshold - decrease_step def find_best_article(articles, index_to_summary_embeddings, index_to_article_embeddings, query, embedder, threshold=0.5): """ returns the index (in the articles list) of the article that best fits the given query """ query_embedding = embedder.encode(query, convert_to_tensor=True) articles_to_explore = relative_articles(articles, index_to_summary_embeddings, query_embedding, threshold=threshold) while len(articles_to_explore) == 0: threshold -= 0.05 articles_to_explore = relative_articles(articles, index_to_summary_embeddings, query_embedding, threshold=threshold) best_cos_sim = 0.0 best_article_idx = None best_sentence_idx = None # print("For query '{}', found {} articles to explore.\n".format(query, len(articles_to_explore))) # print([articles[article].id for article in articles_to_explore]) for idx in articles_to_explore: article = articles[idx] if idx not in index_to_article_embeddings: corpus = article.text corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True) index_to_article_embeddings[idx] = corpus_embeddings else: corpus_embeddings = index_to_article_embeddings[idx] top_sentences_and_scores = max_similarity(corpus_embeddings, query_embedding) score = top_sentences_and_scores[0][0] if score > best_cos_sim: best_cos_sim = score best_article_idx = idx best_sentence_idx = top_sentences_and_scores[1][0] best_article = articles[best_article_idx] corpus = best_article.text index_in_section, section = best_article.get_section_from_index(best_sentence_idx) paragraph = [section[0], *section[1]] passage = get_passage(corpus, best_sentence_idx, index_in_section, paragraph, embedder) return best_article_idx, passage ###Output _____no_output_____ ###Markdown These queries and their respective answers are written in the file queries.txt ###Code queries = ['How is the diagnosis of pulmonary tuberculosis made in TB clinics and hospitals?', 'Was the Porcine epidemic diarrhea virus first detected in Slovenia?', 'Is handwashing the most important measure against infectious diseases?', 'How was the importance of clathrin-mediated endocytosis for MHV confirmed?', 'Which alternatives do we have for conventional chemotherapy?', 'Is there a drug to treat the EV71 infection?', 'Which is common cause for diarrhea and septicemia in calves?', 'Which scanning technique was used to confirm hypotheses regarding the MAb-1G10 epitope structure?', 'How can host translational inhibition be achieved?', 'What is Multiple sclerosis?'] ###Output _____no_output_____ ###Markdown Define a threshold that will be use to filter out articles where their summary has an a cosine similarity with the query, lower than the threshold. The bigger the threshold, the more articles get filtered out. This has 2 effects:- Greatly improves running time- Increased probability of missing out the best article as it's summary might not be similar to the query, yet its body text may have the correct passage ###Code threshold = 0.65 ###Output _____no_output_____ ###Markdown Find the best articles for them ###Code total_time = 0.0 for idx, query in enumerate(queries): start_time = time.time() best_article_index, passage = find_best_article(articles, index_to_summary_embeddings1, index_to_article_embedding1, query, embedder1, threshold=threshold) elapsed_time = time.time() - start_time total_time += elapsed_time best_article = articles[best_article_index] print('-' * 200) print("For Query {}: '{}', the most relevant article is:\n".format(idx + 1, query)) print('ID: {},\tTitle: {}\n'.format(best_article.id, best_article.title)) print('The Passage is:') print(passage) print('\nFound the answer in %.2f seconds' % elapsed_time) print('-' * 200) print('\n') print('\n\n') print('-' * 200) print('\nAverage time per Query: {:.2f}\n'.format(total_time / len(queries))) print('-' * 200) total_time = 0.0 for idx, query in enumerate(queries): start_time = time.time() best_article_index, passage = find_best_article(articles, index_to_summary_embeddings2, index_to_article_embedding2, query, embedder2, threshold=threshold) elapsed_time = time.time() - start_time total_time += elapsed_time best_article = articles[best_article_index] print('-' * 200) print("For Query {}: '{}', the most relevant article is:\n".format(idx + 1, query)) print('ID: {},\tTitle: {}\n'.format(best_article.id, best_article.title)) print('The Passage is:') print(passage) print('\nFound the answer in %.2f seconds' % elapsed_time) print('-' * 200) print('\n') print('\n\n') print('-' * 200) print('\nAverage time per Query: {:.2f}\n'.format(total_time / len(queries))) print('-' * 200) ###Output -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 1: 'How is the diagnosis of pulmonary tuberculosis made in TB clinics and hospitals?', the most relevant article is: ID: 0043d044273b8eb1585d3a66061e9b4e03edc062, Title: Evaluation of the tuberculosis programme in Ningxia Hui Autonomous region, the People's Republic of China: a retrospective case study The Passage is: Diagnosis of pulmonary TB in hospitals and TB clinics is made on the basis of clinical examination; chest radiography and sputum smear microscopy and/or sputum culture. Following diagnosis, patients enter the DOTS program which prescribes short-course chemotherapy (SCC) comprising 2 months of isoniazid (H), rifampicin (R), pyrazinamide (Z) plus streptomycin (S) or ethambutol (E) followed by 4 months of H and R. This is the WHO recommended regimen for treating new cases of smear-positive pulmonary TB or smear-negative pulmonary TB with substantial radiographic evidence of active disease . Found the answer in 47.52 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 2: 'Was the Porcine epidemic diarrhea virus first detected in Slovenia?', the most relevant article is: ID: 105268027d44ab275991e358674462f77223e882, Title: Complete Genome Sequence of the Porcine Epidemic Diarrhea Virus Strain SLO/JH-11/2015 The Passage is: Porcine epidemic diarrhea virus (PEDV) was detected for the first time in Slovenia in January 2015. The complete genome sequence of PEDV strain SLO/JH-11/2015, obtained from a fecal sample of a fattening pig with diarrhea in September 2015, is closely related to recently detected European strains. Found the answer in 2.29 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 3: 'Is handwashing the most important measure against infectious diseases?', the most relevant article is: ID: 1edab5890fbff22ad353739d3d1e80a86d482820, Title: Open Access Handwashing with soap and national handwashing projects in Korea: focus on the National Handwashing Survey, 2006-2014 The Passage is: Handwashing is the most fundamental way to prevent the spread of infectious diseases. Correct handwashing can prevent 50 to 70% of water-infections and foodborne-infections. Found the answer in 25.42 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 4: 'How was the importance of clathrin-mediated endocytosis for MHV confirmed?', the most relevant article is: ID: 3339f4bb346bfa3070ae5fc7dc745ef051535b0e, Title: Coronavirus Cell Entry Occurs through the Endo-/ Lysosomal Pathway in a Proteolysis-Dependent Manner The Passage is: Clathrin-mediated endocytosis and late endosomal factors are required for MHV fusion. The importance of clathrin-mediated endocytosis and endosome maturation for MHV fusion was confirmed by analysis of endocytosis-affecting agents using the fusion assay. Found the answer in 55.34 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 5: 'Which alternatives do we have for conventional chemotherapy?', the most relevant article is: ID: 63a0d9767212d4316c91660dc4eedc8cb3fe527f, Title: Dihydroberberine exhibits synergistic effects with sunitinib on NSCLC NCI-H460 cells by repressing MAP kinase pathways and inflammatory mediators The Passage is: Highly effective and attenuated dose schedules are good regimens for drug research and development. Combination chemotherapy is a good strategy in cancer therapy. Found the answer in 5.79 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 6: 'Is there a drug to treat the EV71 infection?', the most relevant article is: ID: e447d139f1d046120a293f1219944e82c77bc829, Title: Oblongifolin M, an active compound isolated from a Chinese medical herb Garcinia oblongifolia, potently inhibits enterovirus 71 reproduction through downregulation of ERp57 The Passage is: There is no effective drug to treat EV71 infection yet. Found the answer in 29.16 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 7: 'Which is common cause for diarrhea and septicemia in calves?', the most relevant article is: ID: b7a6a987030c52cc7ecdf49c3933b6cfda488210, Title: A systematic review and meta-analysis of the epidemiology of pathogenic Escherichia coli of calves and the role of calves as reservoirs for human pathogenic E. coli The Passage is: Escherichia coli bacteria are the most common causes of diarrhea and septicemia in calves. Moreover, calves form a major reservoir for transmission of pathogenic E. coli to humans. Found the answer in 52.88 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 8: 'Which scanning technique was used to confirm hypotheses regarding the MAb-1G10 epitope structure?', the most relevant article is: ID: 76d39ac4634db5a0fcc8cddbefd965c463c0ace0, Title: Decreased Pattern Recognition Receptor Signaling, Interferon-Signature, and Bactericidal/Permeability- Increasing Protein Gene Expression in Cord Blood of Term Low Birth Weight Human Newborns The Passage is: RNA labeling and Affymetrix gene chip expression probe array hybridization. Found the answer in 5.02 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 9: 'How can host translational inhibition be achieved?', the most relevant article is: ID: 2e32842d3ebcee3ffaf4b6822dbac0f41f82130a, Title: Associated Virus Vectors The Passage is: Further studies demonstrated that scAAV1 and scAAV6 also induce cellular UPR in vitro, with AAV1 vectors activating the PERK pathway (3 fold) while AAV6 vectors induced a significant increase on all the three major UPR pathways [6-16 fold]. These data suggest that the type and strength of UPR activation is dependent on the viral capsid. We then examined if transient inhibition of UPR pathways by RNA interference has an effect on AAV transduction. siRNA mediated silencing of PERK and IRE1a had a modest effect on AAV2 and AAV6 mediated gene expression (,1.5-2 fold) in vitro. Found the answer in 12.19 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For Query 10: 'What is Multiple sclerosis?', the most relevant article is: ID: 86fca5af635ee9425e3375140fb48cbe6d429411, Title: Deep Sequencing for the Detection of Virus-Like Sequences in the Brains of Patients with Multiple Sclerosis: Detection of GBV-C in Human Brain The Passage is: It's relationship with the underlying disease, primary progressive multiple sclerosis, in this single person is not clear. Found the answer in 13.49 seconds -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Average time per Query: 24.91 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
notebooks/RankMarkov.ipynb
###Markdown Full Rank Markov and Geographic Rank Markov **Author: Wei Kang ** ###Code import libpysal as ps import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns import pandas as pd import geopandas as gpd ###Output _____no_output_____ ###Markdown Full Rank Markov ###Code from giddy.markov import FullRank_Markov income_table = pd.read_csv(ps.examples.get_path("usjoin.csv")) income_table.head() pci = income_table[list(map(str,range(1929,2010)))].values pci m = FullRank_Markov(pci) m.ranks m.transitions ###Output _____no_output_____ ###Markdown Full rank Markov transition probability matrix ###Code m.p ###Output _____no_output_____ ###Markdown Full rank first mean passage times ###Code m.fmpt m.sojourn_time df_fullrank = pd.DataFrame(np.c_[m.p.diagonal(),m.sojourn_time], columns=["Staying Probability","Sojourn Time"], index = np.arange(m.p.shape[0])+1) df_fullrank.head() df_fullrank.plot(subplots=True, layout=(1,2), figsize=(15,5)) sns.distplot(m.fmpt.flatten(),kde=False) ###Output /Users/weikang/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval ###Markdown Geographic Rank Markov ###Code from giddy.markov import GeoRank_Markov, Markov, sojourn_time gm = GeoRank_Markov(pci) gm.transitions gm.p gm.sojourn_time[:10] gm.sojourn_time gm.fmpt income_table["geo_sojourn_time"] = gm.sojourn_time i = 0 for state in income_table["Name"]: income_table["geo_fmpt_to_" + state] = gm.fmpt[:,i] income_table["geo_fmpt_from_" + state] = gm.fmpt[i,:] i = i + 1 income_table.head() geo_table = gpd.read_file(ps.examples.get_path('us48.shp')) # income_table = pd.read_csv(libpysal.examples.get_path("usjoin.csv")) complete_table = geo_table.merge(income_table,left_on='STATE_NAME',right_on='Name') complete_table.head() complete_table.columns ###Output _____no_output_____ ###Markdown Visualizing first mean passage time from/to California/Mississippi: ###Code fig, axes = plt.subplots(nrows=2, ncols=2,figsize = (15,7)) target_states = ["California","Mississippi"] directions = ["from","to"] for i, direction in enumerate(directions): for j, target in enumerate(target_states): ax = axes[i,j] col = direction+"_"+target complete_table.plot(ax=ax,column = "geo_fmpt_"+ col,cmap='OrRd', scheme='quantiles', legend=True) ax.set_title("First Mean Passage Time "+direction+" "+target) ax.axis('off') leg = ax.get_legend() leg.set_bbox_to_anchor((0.8, 0.15, 0.16, 0.2)) plt.tight_layout() ###Output /Users/weikang/anaconda3/lib/python3.6/site-packages/pysal/__init__.py:65: VisibleDeprecationWarning: PySAL's API will be changed on 2018-12-31. The last release made with this API is version 1.14.4. A preview of the next API version is provided in the `pysal` 2.0 prelease candidate. The API changes and a guide on how to change imports is provided at https://migrating.pysal.org ), VisibleDeprecationWarning) /Users/weikang/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval ###Markdown Visualizing sojourn time for each US state: ###Code fig, axes = plt.subplots(nrows=1, ncols=2,figsize = (15,7)) schemes = ["Quantiles","Equal_Interval"] for i, scheme in enumerate(schemes): ax = axes[i] complete_table.plot(ax=ax,column = "geo_sojourn_time",cmap='OrRd', scheme=scheme, legend=True) ax.set_title("Rank Sojourn Time ("+scheme+")") ax.axis('off') leg = ax.get_legend() leg.set_bbox_to_anchor((0.8, 0.15, 0.16, 0.2)) plt.tight_layout() ###Output /Users/weikang/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
Convolutional Neural Networks/week_4/Programming_Assignment/Art_Generation_with_Neural_Style_Transfer_v3a.ipynb
###Markdown Deep Learning & Art: Neural Style TransferIn this assignment, you will learn about Neural Style Transfer. This algorithm was created by [Gatys et al. (2015).](https://arxiv.org/abs/1508.06576)**In this assignment, you will:**- Implement the neural style transfer algorithm - Generate novel artistic images using your algorithm Most of the algorithms you've studied optimize a cost function to get a set of parameter values. In Neural Style Transfer, you'll optimize a cost function to get pixel values! Updates If you were working on the notebook before this update...* The current notebook is version "3a".* You can find your original work saved in the notebook with the previous version name ("v2") * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. List of updates* Use `pprint.PrettyPrinter` to format printing of the vgg model.* computing content cost: clarified and reformatted instructions, fixed broken links, added additional hints for unrolling.* style matrix: clarify two uses of variable "G" by using different notation for gram matrix.* style cost: use distinct notation for gram matrix, added additional hints.* Grammar and wording updates for clarity.* `model_nn`: added hints. ###Code import os import sys import scipy.io import scipy.misc import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from PIL import Image from nst_utils import * import numpy as np import tensorflow as tf import pprint %matplotlib inline ###Output _____no_output_____ ###Markdown 1 - Problem StatementNeural Style Transfer (NST) is one of the most fun techniques in deep learning. As seen below, it merges two images, namely: a **"content" image (C) and a "style" image (S), to create a "generated" image (G**). The generated image G combines the "content" of the image C with the "style" of image S. In this example, you are going to generate an image of the Louvre museum in Paris (content image C), mixed with a painting by Claude Monet, a leader of the impressionist movement (style image S).Let's see how you can do this. 2 - Transfer LearningNeural Style Transfer (NST) uses a previously trained convolutional network, and builds on top of that. The idea of using a network trained on a different task and applying it to a new task is called transfer learning. Following the [original NST paper](https://arxiv.org/abs/1508.06576), we will use the VGG network. Specifically, we'll use VGG-19, a 19-layer version of the VGG network. This model has already been trained on the very large ImageNet database, and thus has learned to recognize a variety of low level features (at the shallower layers) and high level features (at the deeper layers). Run the following code to load parameters from the VGG model. This may take a few seconds. ###Code pp = pprint.PrettyPrinter(indent=4) model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") pp.pprint(model) ###Output { 'avgpool1': <tf.Tensor 'AvgPool:0' shape=(1, 150, 200, 64) dtype=float32>, 'avgpool2': <tf.Tensor 'AvgPool_1:0' shape=(1, 75, 100, 128) dtype=float32>, 'avgpool3': <tf.Tensor 'AvgPool_2:0' shape=(1, 38, 50, 256) dtype=float32>, 'avgpool4': <tf.Tensor 'AvgPool_3:0' shape=(1, 19, 25, 512) dtype=float32>, 'avgpool5': <tf.Tensor 'AvgPool_4:0' shape=(1, 10, 13, 512) dtype=float32>, 'conv1_1': <tf.Tensor 'Relu:0' shape=(1, 300, 400, 64) dtype=float32>, 'conv1_2': <tf.Tensor 'Relu_1:0' shape=(1, 300, 400, 64) dtype=float32>, 'conv2_1': <tf.Tensor 'Relu_2:0' shape=(1, 150, 200, 128) dtype=float32>, 'conv2_2': <tf.Tensor 'Relu_3:0' shape=(1, 150, 200, 128) dtype=float32>, 'conv3_1': <tf.Tensor 'Relu_4:0' shape=(1, 75, 100, 256) dtype=float32>, 'conv3_2': <tf.Tensor 'Relu_5:0' shape=(1, 75, 100, 256) dtype=float32>, 'conv3_3': <tf.Tensor 'Relu_6:0' shape=(1, 75, 100, 256) dtype=float32>, 'conv3_4': <tf.Tensor 'Relu_7:0' shape=(1, 75, 100, 256) dtype=float32>, 'conv4_1': <tf.Tensor 'Relu_8:0' shape=(1, 38, 50, 512) dtype=float32>, 'conv4_2': <tf.Tensor 'Relu_9:0' shape=(1, 38, 50, 512) dtype=float32>, 'conv4_3': <tf.Tensor 'Relu_10:0' shape=(1, 38, 50, 512) dtype=float32>, 'conv4_4': <tf.Tensor 'Relu_11:0' shape=(1, 38, 50, 512) dtype=float32>, 'conv5_1': <tf.Tensor 'Relu_12:0' shape=(1, 19, 25, 512) dtype=float32>, 'conv5_2': <tf.Tensor 'Relu_13:0' shape=(1, 19, 25, 512) dtype=float32>, 'conv5_3': <tf.Tensor 'Relu_14:0' shape=(1, 19, 25, 512) dtype=float32>, 'conv5_4': <tf.Tensor 'Relu_15:0' shape=(1, 19, 25, 512) dtype=float32>, 'input': <tf.Variable 'Variable:0' shape=(1, 300, 400, 3) dtype=float32_ref>} ###Markdown * The model is stored in a python dictionary. * The python dictionary contains key-value pairs for each layer. * The 'key' is the variable name and the 'value' is a tensor for that layer. Assign input image to the model's input layerTo run an image through this network, you just have to feed the image to the model. In TensorFlow, you can do so using the [tf.assign](https://www.tensorflow.org/api_docs/python/tf/assign) function. In particular, you will use the assign function like this: ```pythonmodel["input"].assign(image)```This assigns the image as an input to the model. Activate a layerAfter this, if you want to access the activations of a particular layer, say layer `4_2` when the network is run on this image, you would run a TensorFlow session on the correct tensor `conv4_2`, as follows: ```pythonsess.run(model["conv4_2"])``` 3 - Neural Style Transfer (NST)We will build the Neural Style Transfer (NST) algorithm in three steps:- Build the content cost function $J_{content}(C,G)$- Build the style cost function $J_{style}(S,G)$- Put it together to get $J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$. 3.1 - Computing the content costIn our running example, the content image C will be the picture of the Louvre Museum in Paris. Run the code below to see a picture of the Louvre. ###Code content_image = scipy.misc.imread("images/louvre.jpg") imshow(content_image); ###Output _____no_output_____ ###Markdown The content image (C) shows the Louvre museum's pyramid surrounded by old Paris buildings, against a sunny sky with a few clouds.** 3.1.1 - Make generated image G match the content of image C** Shallower versus deeper layers* The shallower layers of a ConvNet tend to detect lower-level features such as edges and simple textures.* The deeper layers tend to detect higher-level features such as more complex textures as well as object classes. Choose a "middle" activation layer $a^{[l]}$We would like the "generated" image G to have similar content as the input image C. Suppose you have chosen some layer's activations to represent the content of an image. * In practice, you'll get the most visually pleasing results if you choose a layer in the **middle** of the network--neither too shallow nor too deep. * (After you have finished this exercise, feel free to come back and experiment with using different layers, to see how the results vary.) Forward propagate image "C"* Set the image C as the input to the pretrained VGG network, and run forward propagation. * Let $a^{(C)}$ be the hidden layer activations in the layer you had chosen. (In lecture, we had written this as $a^{[l](C)}$, but here we'll drop the superscript $[l]$ to simplify the notation.) This will be an $n_H \times n_W \times n_C$ tensor. Forward propagate image "G"* Repeat this process with the image G: Set G as the input, and run forward progation. * Let $a^{(G)}$ be the corresponding hidden layer activation. Content Cost Function $J_{content}(C,G)$We will define the content cost function as:$$J_{content}(C,G) = \frac{1}{4 \times n_H \times n_W \times n_C}\sum _{ \text{all entries}} (a^{(C)} - a^{(G)})^2\tag{1} $$* Here, $n_H, n_W$ and $n_C$ are the height, width and number of channels of the hidden layer you have chosen, and appear in a normalization term in the cost. * For clarity, note that $a^{(C)}$ and $a^{(G)}$ are the 3D volumes corresponding to a hidden layer's activations. * In order to compute the cost $J_{content}(C,G)$, it might also be convenient to unroll these 3D volumes into a 2D matrix, as shown below.* Technically this unrolling step isn't needed to compute $J_{content}$, but it will be good practice for when you do need to carry out a similar operation later for computing the style cost $J_{style}$. **Exercise:** Compute the "content cost" using TensorFlow. **Instructions**: The 3 steps to implement this function are:1. Retrieve dimensions from `a_G`: - To retrieve dimensions from a tensor `X`, use: `X.get_shape().as_list()`2. Unroll `a_C` and `a_G` as explained in the picture above - You'll likey want to use these functions: [tf.transpose](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/transpose) and [tf.reshape](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/reshape).3. Compute the content cost: - You'll likely want to use these functions: [tf.reduce_sum](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [tf.square](https://www.tensorflow.org/api_docs/python/tf/square) and [tf.subtract](https://www.tensorflow.org/api_docs/python/tf/subtract). Additional Hints for "Unrolling"* To unroll the tensor, we want the shape to change from $(m,n_H,n_W,n_C)$ to $(m, n_H \times n_W, n_C)$.* `tf.reshape(tensor, shape)` takes a list of integers that represent the desired output shape.* For the `shape` parameter, a `-1` tells the function to choose the correct dimension size so that the output tensor still contains all the values of the original tensor.* So tf.reshape(a_C, shape=[m, n_H * n_W, n_C]) gives the same result as tf.reshape(a_C, shape=[m, -1, n_C]).* If you prefer to re-order the dimensions, you can use `tf.transpose(tensor, perm)`, where `perm` is a list of integers containing the original index of the dimensions. * For example, `tf.transpose(a_C, perm=[0,3,1,2])` changes the dimensions from $(m, n_H, n_W, n_C)$ to $(m, n_C, n_H, n_W)$.* There is more than one way to unroll the tensors.* Notice that it's not necessary to use tf.transpose to 'unroll' the tensors in this case but this is a useful function to practice and understand for other situations that you'll encounter. ###Code # GRADED FUNCTION: compute_content_cost def compute_content_cost(a_C, a_G): """ Computes the content cost Arguments: a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G Returns: J_content -- scalar that you compute using equation 1 above. """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape a_C and a_G (≈2 lines) a_C_unrolled = tf.reshape(a_C,shape=[m,n_H*n_W,n_C]) a_G_unrolled = tf.reshape(a_G,shape=[m,n_H*n_W,n_C]) # compute the cost with tensorflow (≈1 line) J_content = tf.reduce_sum(tf.square(tf.subtract(a_C_unrolled,a_G_unrolled)))/(4 * n_H * n_W * n_C) ### END CODE HERE ### return J_content tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_C = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_content = compute_content_cost(a_C, a_G) print("J_content = " + str(J_content.eval())) ###Output J_content = 6.76559 ###Markdown **Expected Output**: **J_content** 6.76559 What you should remember- The content cost takes a hidden layer activation of the neural network, and measures how different $a^{(C)}$ and $a^{(G)}$ are. - When we minimize the content cost later, this will help make sure $G$ has similar content as $C$. 3.2 - Computing the style costFor our running example, we will use the following style image: ###Code style_image = scipy.misc.imread("images/monet_800600.jpg") imshow(style_image); ###Output _____no_output_____ ###Markdown This was painted in the style of *[impressionism](https://en.wikipedia.org/wiki/Impressionism)*.Lets see how you can now define a "style" cost function $J_{style}(S,G)$. 3.2.1 - Style matrix Gram matrix* The style matrix is also called a "Gram matrix." * In linear algebra, the Gram matrix G of a set of vectors $(v_{1},\dots ,v_{n})$ is the matrix of dot products, whose entries are ${\displaystyle G_{ij} = v_{i}^T v_{j} = np.dot(v_{i}, v_{j}) }$. * In other words, $G_{ij}$ compares how similar $v_i$ is to $v_j$: If they are highly similar, you would expect them to have a large dot product, and thus for $G_{ij}$ to be large. Two meanings of the variable $G$* Note that there is an unfortunate collision in the variable names used here. We are following common terminology used in the literature. * $G$ is used to denote the Style matrix (or Gram matrix) * $G$ also denotes the generated image. * For this assignment, we will use $G_{gram}$ to refer to the Gram matrix, and $G$ to denote the generated image. Compute $G_{gram}$In Neural Style Transfer (NST), you can compute the Style matrix by multiplying the "unrolled" filter matrix with its transpose:$$\mathbf{G}_{gram} = \mathbf{A}_{unrolled} \mathbf{A}_{unrolled}^T$$ $G_{(gram)i,j}$: correlationThe result is a matrix of dimension $(n_C,n_C)$ where $n_C$ is the number of filters (channels). The value $G_{(gram)i,j}$ measures how similar the activations of filter $i$ are to the activations of filter $j$. $G_{(gram),i,i}$: prevalence of patterns or textures* The diagonal elements $G_{(gram)ii}$ measure how "active" a filter $i$ is. * For example, suppose filter $i$ is detecting vertical textures in the image. Then $G_{(gram)ii}$ measures how common vertical textures are in the image as a whole.* If $G_{(gram)ii}$ is large, this means that the image has a lot of vertical texture. By capturing the prevalence of different types of features ($G_{(gram)ii}$), as well as how much different features occur together ($G_{(gram)ij}$), the Style matrix $G_{gram}$ measures the style of an image. **Exercise**:* Using TensorFlow, implement a function that computes the Gram matrix of a matrix A. * The formula is: The gram matrix of A is $G_A = AA^T$. * You may use these functions: [matmul](https://www.tensorflow.org/api_docs/python/tf/matmul) and [transpose](https://www.tensorflow.org/api_docs/python/tf/transpose). ###Code # GRADED FUNCTION: gram_matrix def gram_matrix(A): """ Argument: A -- matrix of shape (n_C, n_H*n_W) Returns: GA -- Gram matrix of A, of shape (n_C, n_C) """ ### START CODE HERE ### (≈1 line) GA = tf.matmul(A, tf.transpose(A)) ### END CODE HERE ### return GA tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) A = tf.random_normal([3, 2*1], mean=1, stddev=4) GA = gram_matrix(A) print("GA = \n" + str(GA.eval())) ###Output GA = [[ 6.42230511 -4.42912197 -2.09668207] [ -4.42912197 19.46583748 19.56387138] [ -2.09668207 19.56387138 20.6864624 ]] ###Markdown **Expected Output**: **GA** [[ 6.42230511 -4.42912197 -2.09668207] [ -4.42912197 19.46583748 19.56387138] [ -2.09668207 19.56387138 20.6864624 ]] 3.2.2 - Style cost Your goal will be to minimize the distance between the Gram matrix of the "style" image S and the gram matrix of the "generated" image G. * For now, we are using only a single hidden layer $a^{[l]}$. * The corresponding style cost for this layer is defined as: $$J_{style}^{[l]}(S,G) = \frac{1}{4 \times {n_C}^2 \times (n_H \times n_W)^2} \sum _{i=1}^{n_C}\sum_{j=1}^{n_C}(G^{(S)}_{(gram)i,j} - G^{(G)}_{(gram)i,j})^2\tag{2} $$* $G_{gram}^{(S)}$ Gram matrix of the "style" image.* $G_{gram}^{(G)}$ Gram matrix of the "generated" image.* Remember, this cost is computed using the hidden layer activations for a particular hidden layer in the network $a^{[l]}$ **Exercise**: Compute the style cost for a single layer. **Instructions**: The 3 steps to implement this function are:1. Retrieve dimensions from the hidden layer activations a_G: - To retrieve dimensions from a tensor X, use: `X.get_shape().as_list()`2. Unroll the hidden layer activations a_S and a_G into 2D matrices, as explained in the picture above (see the images in the sections "computing the content cost" and "style matrix"). - You may use [tf.transpose](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/transpose) and [tf.reshape](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/reshape).3. Compute the Style matrix of the images S and G. (Use the function you had previously written.) 4. Compute the Style cost: - You may find [tf.reduce_sum](https://www.tensorflow.org/api_docs/python/tf/reduce_sum), [tf.square](https://www.tensorflow.org/api_docs/python/tf/square) and [tf.subtract](https://www.tensorflow.org/api_docs/python/tf/subtract) useful. Additional Hints* Since the activation dimensions are $(m, n_H, n_W, n_C)$ whereas the desired unrolled matrix shape is $(n_C, n_H*n_W)$, the order of the filter dimension $n_C$ is changed. So `tf.transpose` can be used to change the order of the filter dimension.* for the product $\mathbf{G}_{gram} = \mathbf{A}_{} \mathbf{A}_{}^T$, you will also need to specify the `perm` parameter for the `tf.transpose` function. ###Code # GRADED FUNCTION: compute_layer_style_cost def compute_layer_style_cost(a_S, a_G): """ Arguments: a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G Returns: J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2) """ ### START CODE HERE ### # Retrieve dimensions from a_G (≈1 line) m, n_H, n_W, n_C = a_G.get_shape().as_list() # Reshape the images to have them of shape (n_C, n_H*n_W) (≈2 lines) a_S = tf.reshape(tf.transpose(a_S, perm = [0,3,1,2]),shape=[n_C,n_H * n_W]) a_G = tf.reshape(tf.transpose(a_G, perm= [0,3,1,2]),shape=[n_C,n_H * n_W]) # Computing gram_matrices for both images S and G (≈2 lines) GS = gram_matrix(a_S) GG = gram_matrix(a_G) # Computing the loss (≈1 line) J_style_layer = tf.reduce_sum(tf.square(tf.subtract(GS,GG)))/(4 * n_C**2 * (n_H * n_W)**2) ### END CODE HERE ### return J_style_layer tf.reset_default_graph() with tf.Session() as test: tf.set_random_seed(1) a_S = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4) J_style_layer = compute_layer_style_cost(a_S, a_G) print("J_style_layer = " + str(J_style_layer.eval())) ###Output J_style_layer = 9.19028 ###Markdown **Expected Output**: **J_style_layer** 9.19028 3.2.3 Style Weights* So far you have captured the style from only one layer. * We'll get better results if we "merge" style costs from several different layers. * Each layer will be given weights ($\lambda^{[l]}$) that reflect how much each layer will contribute to the style.* After completing this exercise, feel free to come back and experiment with different weights to see how it changes the generated image $G$.* By default, we'll give each layer equal weight, and the weights add up to 1. ($\sum_{l}^L\lambda^{[l]} = 1$) ###Code STYLE_LAYERS = [ ('conv1_1', 0.2), ('conv2_1', 0.2), ('conv3_1', 0.2), ('conv4_1', 0.2), ('conv5_1', 0.2)] ###Output _____no_output_____ ###Markdown You can combine the style costs for different layers as follows:$$J_{style}(S,G) = \sum_{l} \lambda^{[l]} J^{[l]}_{style}(S,G)$$where the values for $\lambda^{[l]}$ are given in `STYLE_LAYERS`. Exercise: compute style cost* We've implemented a compute_style_cost(...) function. * It calls your `compute_layer_style_cost(...)` several times, and weights their results using the values in `STYLE_LAYERS`. * Please read over it to make sure you understand what it's doing. Description of `compute_style_cost`For each layer:* Select the activation (the output tensor) of the current layer.* Get the style of the style image "S" from the current layer.* Get the style of the generated image "G" from the current layer.* Compute the "style cost" for the current layer* Add the weighted style cost to the overall style cost (J_style)Once you're done with the loop: * Return the overall style cost. ###Code def compute_style_cost(model, STYLE_LAYERS): """ Computes the overall style cost from several chosen layers Arguments: model -- our tensorflow model STYLE_LAYERS -- A python list containing: - the names of the layers we would like to extract style from - a coefficient for each of them Returns: J_style -- tensor representing a scalar value, style cost defined above by equation (2) """ # initialize the overall style cost J_style = 0 for layer_name, coeff in STYLE_LAYERS: # Select the output tensor of the currently selected layer out = model[layer_name] # Set a_S to be the hidden layer activation from the layer we have selected, by running the session on out a_S = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model[layer_name] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute style_cost for the current layer J_style_layer = compute_layer_style_cost(a_S, a_G) # Add coeff * J_style_layer of this layer to overall style cost J_style += coeff * J_style_layer return J_style ###Output _____no_output_____ ###Markdown **Note**: In the inner-loop of the for-loop above, `a_G` is a tensor and hasn't been evaluated yet. It will be evaluated and updated at each iteration when we run the TensorFlow graph in model_nn() below.<!-- How do you choose the coefficients for each layer? The deeper layers capture higher-level concepts, and the features in the deeper layers are less localized in the image relative to each other. So if you want the generated image to softly follow the style image, try choosing larger weights for deeper layers and smaller weights for the first layers. In contrast, if you want the generated image to strongly follow the style image, try choosing smaller weights for deeper layers and larger weights for the first layers!--> What you should remember- The style of an image can be represented using the Gram matrix of a hidden layer's activations. - We get even better results by combining this representation from multiple different layers. - This is in contrast to the content representation, where usually using just a single hidden layer is sufficient.- Minimizing the style cost will cause the image $G$ to follow the style of the image $S$. 3.3 - Defining the total cost to optimize Finally, let's create a cost function that minimizes both the style and the content cost. The formula is: $$J(G) = \alpha J_{content}(C,G) + \beta J_{style}(S,G)$$**Exercise**: Implement the total cost function which includes both the content cost and the style cost. ###Code # GRADED FUNCTION: total_cost def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the importance of the style cost Returns: J -- total cost as defined by the formula above. """ ### START CODE HERE ### (≈1 line) J = alpha*J_content + beta*J_style ### END CODE HERE ### return J tf.reset_default_graph() with tf.Session() as test: np.random.seed(3) J_content = np.random.randn() J_style = np.random.randn() J = total_cost(J_content, J_style) print("J = " + str(J)) ###Output J = 35.34667875478276 ###Markdown **Expected Output**: **J** 35.34667875478276 What you should remember- The total cost is a linear combination of the content cost $J_{content}(C,G)$ and the style cost $J_{style}(S,G)$.- $\alpha$ and $\beta$ are hyperparameters that control the relative weighting between content and style. 4 - Solving the optimization problem Finally, let's put everything together to implement Neural Style Transfer!Here's what the program will have to do:1. Create an Interactive Session2. Load the content image 3. Load the style image4. Randomly initialize the image to be generated 5. Load the VGG19 model7. Build the TensorFlow graph: - Run the content image through the VGG19 model and compute the content cost - Run the style image through the VGG19 model and compute the style cost - Compute the total cost - Define the optimizer and the learning rate8. Initialize the TensorFlow graph and run it for a large number of iterations, updating the generated image at every step.Lets go through the individual steps in detail. Interactive SessionsYou've previously implemented the overall cost $J(G)$. We'll now set up TensorFlow to optimize this with respect to $G$. * To do so, your program has to reset the graph and use an "[Interactive Session](https://www.tensorflow.org/api_docs/python/tf/InteractiveSession)". * Unlike a regular session, the "Interactive Session" installs itself as the default session to build a graph. * This allows you to run variables without constantly needing to refer to the session object (calling "sess.run()"), which simplifies the code. Start the interactive session. ###Code # Reset the graph tf.reset_default_graph() # Start interactive session sess = tf.InteractiveSession() ###Output _____no_output_____ ###Markdown Content imageLet's load, reshape, and normalize our "content" image (the Louvre museum picture): ###Code content_image = scipy.misc.imread("images/louvre_small.jpg") content_image = reshape_and_normalize_image(content_image) ###Output _____no_output_____ ###Markdown Style imageLet's load, reshape and normalize our "style" image (Claude Monet's painting): ###Code style_image = scipy.misc.imread("images/monet.jpg") style_image = reshape_and_normalize_image(style_image) ###Output _____no_output_____ ###Markdown Generated image correlated with content imageNow, we initialize the "generated" image as a noisy image created from the content_image.* The generated image is slightly correlated with the content image.* By initializing the pixels of the generated image to be mostly noise but slightly correlated with the content image, this will help the content of the "generated" image more rapidly match the content of the "content" image. * Feel free to look in `nst_utils.py` to see the details of `generate_noise_image(...)`; to do so, click "File-->Open..." at the upper-left corner of this Jupyter notebook. ###Code generated_image = generate_noise_image(content_image) imshow(generated_image[0]); ###Output _____no_output_____ ###Markdown Load pre-trained VGG19 modelNext, as explained in part (2), let's load the VGG19 model. ###Code model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") ###Output _____no_output_____ ###Markdown Content CostTo get the program to compute the content cost, we will now assign `a_C` and `a_G` to be the appropriate hidden layer activations. We will use layer `conv4_2` to compute the content cost. The code below does the following:1. Assign the content image to be the input to the VGG model.2. Set a_C to be the tensor giving the hidden layer activation for layer "conv4_2".3. Set a_G to be the tensor giving the hidden layer activation for the same layer. 4. Compute the content cost using a_C and a_G.**Note**: At this point, a_G is a tensor and hasn't been evaluated. It will be evaluated and updated at each iteration when we run the Tensorflow graph in model_nn() below. ###Code # Assign the content image to be the input of the VGG model. sess.run(model['input'].assign(content_image)) # Select the output tensor of layer conv4_2 out = model['conv4_2'] # Set a_C to be the hidden layer activation from the layer we have selected a_C = sess.run(out) # Set a_G to be the hidden layer activation from same layer. Here, a_G references model['conv4_2'] # and isn't evaluated yet. Later in the code, we'll assign the image G as the model input, so that # when we run the session, this will be the activations drawn from the appropriate layer, with G as input. a_G = out # Compute the content cost J_content = compute_content_cost(a_C, a_G) ###Output _____no_output_____ ###Markdown Style cost ###Code # Assign the input of the model to be the "style" image sess.run(model['input'].assign(style_image)) # Compute the style cost J_style = compute_style_cost(model, STYLE_LAYERS) ###Output _____no_output_____ ###Markdown Exercise: total cost* Now that you have J_content and J_style, compute the total cost J by calling `total_cost()`. * Use `alpha = 10` and `beta = 40`. ###Code ### START CODE HERE ### (1 line) J = total_cost(J_content, J_style, alpha=10, beta=40) ### END CODE HERE ### ###Output _____no_output_____ ###Markdown Optimizer* Use the Adam optimizer to minimize the total cost `J`.* Use a learning rate of 2.0. * [Adam Optimizer documentation](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) ###Code # define optimizer (1 line) optimizer = tf.train.AdamOptimizer(2.0) # define train_step (1 line) train_step = optimizer.minimize(J) ###Output _____no_output_____ ###Markdown Exercise: implement the model* Implement the model_nn() function. * The function **initializes** the variables of the tensorflow graph, * **assigns** the input image (initial generated image) as the input of the VGG19 model * and **runs** the `train_step` tensor (it was created in the code above this function) for a large number of steps. Hints* To initialize global variables, use this: ```Pythonsess.run(tf.global_variables_initializer())```* Run `sess.run()` to evaluate a variable.* [assign](https://www.tensorflow.org/versions/r1.14/api_docs/python/tf/assign) can be used like this:```pythonmodel["input"].assign(image)``` ###Code def model_nn(sess, input_image, num_iterations = 200): # Initialize global variables (you need to run the session on the initializer) ### START CODE HERE ### (1 line) sess.run(tf.global_variables_initializer()) ### END CODE HERE ### # Run the noisy input image (initial generated image) through the model. Use assign(). ### START CODE HERE ### (1 line) generated_image = sess.run(model["input"].assign(input_image)) ### END CODE HERE ### for i in range(num_iterations): # Run the session on the train_step to minimize the total cost ### START CODE HERE ### (1 line) sess.run(train_step) ### END CODE HERE ### # Compute the generated image by running the session on the current model['input'] ### START CODE HERE ### (1 line) generated_image = sess.run(model["input"]) ### END CODE HERE ### # Print every 20 iteration. if i%20 == 0: Jt, Jc, Js = sess.run([J, J_content, J_style]) print("Iteration " + str(i) + " :") print("total cost = " + str(Jt)) print("content cost = " + str(Jc)) print("style cost = " + str(Js)) # save current generated image in the "/output" directory save_image("output/" + str(i) + ".png", generated_image) # save last generated image save_image('output/generated_image.jpg', generated_image) return generated_image ###Output _____no_output_____ ###Markdown Run the following cell to generate an artistic image. It should take about 3min on CPU for every 20 iterations but you start observing attractive results after ≈140 iterations. Neural Style Transfer is generally trained using GPUs. ###Code model_nn(sess, generated_image) ###Output Iteration 0 : total cost = 5.05035e+09 content cost = 7877.68 style cost = 1.26257e+08 Iteration 20 : total cost = 9.43276e+08 content cost = 15187.0 style cost = 2.35781e+07 Iteration 40 : total cost = 4.84898e+08 content cost = 16785.0 style cost = 1.21183e+07 Iteration 60 : total cost = 3.12574e+08 content cost = 17465.8 style cost = 7.80998e+06 Iteration 80 : total cost = 2.28137e+08 content cost = 17715.0 style cost = 5.699e+06 Iteration 100 : total cost = 1.80694e+08 content cost = 17895.5 style cost = 4.51288e+06 Iteration 120 : total cost = 1.49996e+08 content cost = 18034.4 style cost = 3.74539e+06 Iteration 140 : total cost = 1.27698e+08 content cost = 18186.9 style cost = 3.18791e+06 Iteration 160 : total cost = 1.10698e+08 content cost = 18354.2 style cost = 2.76287e+06 Iteration 180 : total cost = 9.73408e+07 content cost = 18501.0 style cost = 2.4289e+06
notebooks/automl/02_automated_ML.ipynb
###Markdown ![LearnAI Header](https://coursematerial.blob.core.windows.net/assets/LearnAI_header.png) Classification using Automated MLIn this example we use Azure ML's Automated ML functionality to improve on the classifier we built earlier. Automated ML handles the task of building many models from a wide variety of algorithms and choosing a good set of hyper-parameters for them. We then select best the model (or one that meets our criteria) and deploy it as a web service. Load and prepare experiment As part of the setup we have already created an AML workspace. Let's load the workspace and create an experiment. ###Code import json import logging import os import random from matplotlib import pyplot as plt from matplotlib.pyplot import imshow import pandas as pd from sklearn import datasets from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_auc_score import azureml.core from azureml.core.experiment import Experiment from azureml.core.workspace import Workspace from azureml.train.automl import AutoMLConfig from azureml.train.automl.run import AutoMLRun ###Output _____no_output_____ ###Markdown We load the workspace directly from the config file we created in the early part of the course. ###Code config_path = '/dbfs/tmp/aml_config' ws = Workspace.from_config(path=os.path.join(config_path, 'config.json')) experiment_name = 'pred-maint-automl' # choose a name for experiment project_folder = '.' # project folder experiment=Experiment(ws, experiment_name) output = {} output['SDK version'] = azureml.core.VERSION output['Subscription ID'] = ws.subscription_id output['Workspace'] = ws.name output['Resource Group'] = ws.resource_group output['Location'] = ws.location output['Project Directory'] = project_folder output['Experiment Name'] = experiment.name pd.set_option('display.max_colwidth', -1) pd.DataFrame(data=output, index=['']).T ###Output _____no_output_____ ###Markdown Opt in for diagnostics for better experience, quality, and security of future releases: ###Code from azureml.telemetry import set_diagnostics_collection set_diagnostics_collection(send_diagnostics=True) ###Output _____no_output_____ ###Markdown Instantiate config file We now instantiate a `AutoMLConfig` object. This defines the settings and data used to run the experiment.|Property|Description||-|-||**task**|classification or regression||**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics accuracyAUC_weightedbalanced_accuracyaverage_precision_score_weightedprecision_score_weighted||**max_time_sec**|Time limit in seconds for each iterations||**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline||**n_cross_validations**|Number of cross validation splits||**X**|(sparse) array-like, shape = [n_samples, n_features]||**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers. ||**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. | ###Code df = spark.read.parquet("dbfs:/FileStore/tables/preprocessed").cache() display(df) from pandas import datetime from pyspark.sql.functions import col, hour # we sample every nth row of the data using the `hour` function df_train = df.filter((col('datetime') < datetime(2015, 10, 1))) # & (hour(col('datetime')) % 3 == 0)) df_test = df.filter(col('datetime') > datetime(2015, 10, 15)) X_keep = ['diff_maint_1', 'diff_error_1', 'volt_sd_3', 'diff_fail_3', 'pressure_ma_3', 'pressure_sd_3', 'diff_fail_1', 'diff_fail_0', 'age', 'vibration_ma_3', 'rotate_ma_3', 'diff_error_2', 'diff_fail_2', 'diff_error_3', 'diff_maint_2', 'volt_ma_3', 'diff_maint_0', 'vibration_sd_3', 'diff_maint_3', 'rotate_sd_3', 'diff_error_0', 'diff_error_4'] Y_keep = ['y_1'] # ['y_0', 'y_1', 'y_2', 'y_3'] # for now, we convert the spark DataFrames to Pandas dataframes, # because at this point automated ML only supports the latter. # This will change soon though. X_train = df_train.select(X_keep).toPandas() X_test = df_test.select(X_keep).toPandas() y_train = df_train.select(Y_keep).toPandas() y_test = df_test.select(Y_keep).toPandas() X_train.columns ###Output _____no_output_____ ###Markdown Here are the metrics we can choose to optimize our model over. ###Code azureml.train.automl.constants.Metric.CLASSIFICATION_PRIMARY_SET ###Output _____no_output_____ ###Markdown Since we are using `automl` on top of Spark, we have an additional step to run before running the experiment: We use the `azureml.dataprep` API to turn the data from a Pandas DataFrame to a Dataflow. A Dataflow represents a series of lazily-evaluated, immutable operations on data. ###Code %sh rm -r /dbfs/dprep mkdir /dbfs/dprep mkdir /dbfs/dprep/tmp import azureml.dataprep as dprep from pyspark.sql.functions import rand temp_location = '/dbfs/dprep/tmp' X_dflow = dprep.read_pandas_dataframe(X_train, temp_folder = temp_location + '/X') y_dflow = dprep.read_pandas_dataframe(y_train, temp_folder = temp_location + '/y') ###Output _____no_output_____ ###Markdown We now set up a configuration file for the automated ML training experiment. It contains details for how the experiment should run. ###Code num_iters = 15 automl_config = AutoMLConfig(task = 'classification', preprocess = False, name = experiment_name, debug_log = 'automl_errors.log', primary_metric = 'AUC_weighted', iteration_timeout_minutes = 15, iterations = num_iters, verbosity = logging.INFO, spark_context = sc, X = X_dflow, y = y_dflow, # validation_size = 0.10, n_cross_validations = 3, path = project_folder) ###Output _____no_output_____ ###Markdown Run training experiment You can call the submit method on the experiment object and pass the run configuration. For Local runs the execution is synchronous. Depending on the data and number of iterations this can run for while.You will see the currently running iterations printing to the console. ###Code local_run = experiment.submit(automl_config, show_output = True) ###Output _____no_output_____ ###Markdown Portal URL for Monitoring RunsThe following will provide a link to the web interface to explore individual run details and status. ###Code displayHTML("<a href={} target='_blank'>Your experiment in Azure Portal: {}</a>".format(local_run.get_portal_url(), local_run.id)) ###Output _____no_output_____ ###Markdown Retrieve the Best ModelBelow we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*. ###Code best_run, fitted_model = local_run.get_output() fitted_model ###Output _____no_output_____ ###Markdown We can see from the above results that `StandardScalerWrapper` was used to scale the features and a `LightGBMClassifier` was chosen as the best model based on the metric we defined. This of course does NOT automatically also make it the best model in production, but choosing the right model for production is beyond the scope of this course so we will not address it here. Hands-on lab Run the following cell and go to the link provided under Details Page. This links will take us to the Azure portal. Examine the content of the page. Can you find what resource group this resource is under? What kind of resource is it? ###Code displayHTML("<a href={} target='_blank'>Your experiment in Azure Portal: {}</a>".format(best_run.get_portal_url(), best_run.id)) ###Output _____no_output_____ ###Markdown In addition to choosing a good algorithm, the experiment also tuned hyper-parameters. So our model didn't just run with the default hyper-parameter values. Find out how we can get the chosen hyper-parameters from the `fitted_model` object. Describe the hyper-parameters you see. Which ones do you think are the most critical ones? ###Code # write solution here ###Output _____no_output_____ ###Markdown End of lab We can run the following code to get the hyper-parameters for the chosen model. ###Code n_steps = len(fitted_model.steps) for s in range(n_steps): print("Step: %s" % s) params = fitted_model.steps[s][1].get_params() print(params) ###Output _____no_output_____ ###Markdown With a little bit of re-arranging we can pull out the metrics we're interested in and compare them across different runs. Since we're in Databricks, we can use `display` to create a quick visualization with the results. ###Code children = list(local_run.get_children()) metricslist = {} for run in children: properties = run.get_properties() metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} metricslist[int(properties['iteration'])] = metrics rundata = pd.DataFrame(metricslist).sort_index(1) rundata['metric'] = rundata.index rundata = rundata.reset_index() res = rundata.melt(id_vars='metric', value_vars = range(num_iters)) display(res.loc[res.metric.str.contains('micro'), :]) # in this case we limit the metrics to the ones containing the word `micro` ###Output _____no_output_____ ###Markdown Quick note: macro and micro averages are only relevant in a multi-class classification scenario. In this situation, we can compute a single classification metric (such as precison, recall or AUC) in one of two ways. Let's use precision to illustrate the difference. Recall that precision = TP / (TP + FP). In a multi-class classification setting, each class has a TP and FP, and hence a precision. So we can compute a macro and micro precision as such:- We can compute precision *per class* and then average across all classes. This is called a **macro precision**. When class imbalances are strong macro averages are not recommended, because by taking a *simple* (not weighted) average we treat all classes equally.- We can compute the aggregated value for TP and FS (summed up for all classes) and then compute an aggregated precision. This is called a **micro presicion** and it works better when we have imbalances across the classes. Score and evaluate the chosen model Let's now pick the best model returned by the experiment and use it to get predictions for the test data. This is simply done by replacing `manual_model.predict` with `fitted_model.predict`. ###Code y_pred = fitted_model.predict(X_test) ###Output _____no_output_____ ###Markdown We should get the same confusion matrix we did in the section above. ###Code confusion_matrix(y_test.values, y_pred) ###Output _____no_output_____ ###Markdown We use `classification_report` to automatically calculate precision, recall, and the F-1 score from the confusion matrix above. ###Code cl_report = classification_report(y_test.values, y_pred) print(cl_report) ###Output _____no_output_____ ###Markdown The AUC is just the area under the ROC curve shown here: ###Code from sklearn.metrics import auc, roc_curve fpr, tpr, thresholds = roc_curve(y_test.values, y_pred) roc_auc = auc(fpr, tpr) import matplotlib.pyplot as plt plt.plot(fpr, tpr, 'b', label = 'AUC = {0:.2f}'.format(roc_auc)) plt.legend(loc = 'lower right') plt.plot([0, 1], [0, 1],'r--') plt.xlim([0, 1]) plt.ylim([0, 1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() display() ###Output _____no_output_____ ###Markdown Register fitted model for deployment Now that we have a model we're happy with, we register it to our Azure ML account. This will be the first step toward model management and deployment, which we cover in the next Notebook. Registered models can also be loaded into other workspaces. ###Code description = 'automated ML PdM (predict y_1)' tags = None model = local_run.register_model(description=description, tags=tags) local_run.model_id # Use this id to deploy the model as a web service in Azur ###Output _____no_output_____ ###Markdown Optionally, we can also take the model and save it on disk as a pickle file, as shown here: ###Code from sklearn.externals import joblib joblib.dump(value=fitted_model, filename='model.pkl') # You can ignore this code, we use it for testing our notebooks. assert isinstance(model, azureml.core.model.Model) ###Output _____no_output_____
10 Days of Statistics/Day_7. Pearson Correlation Coefficient I.ipynb
###Markdown Day_7. Pearson Correlation Coefficient I`Task`Given two `n`-element data sets, `X` and , `Y` calculate the value of the Pearson correlation coefficient.`Input Format`The first line contains an integer, `n`, denoting the size of data sets `X` and `Y`. The second line contains `n` space-separated real numbers (scaled to at most one decimal place), defining data set `X`. The third line contains `n` space-separated real numbers (scaled to at most one decimal place), defining data set `Y`.`Constraints`````10 <= n <= 100``1 <= Xi <= 500`, where `Xi` is the `i th` value of data set `X`.`1 <= Yi <= 500`, where `Yi` is the `i th` value of data set `Y`.Data set `X` contains unique values.Data set `Y` contains unique values.````Output Format`Print the value of the Pearson correlation coefficient, rounded to a scale of `3` decimal places.`Sample Input````1010 9.8 8 7.8 7.7 7 6 5 4 2 200 44 32 24 22 17 15 12 8 4````Sample Output````0.612``` ###Code from math import * n = int(input()) X = tuple(map(float, input().split())) Y = tuple(map(float, input().split())) X_bar = sum(X)/len(X) Y_bar = sum(Y)/len(Y) X_std = sqrt(sum(list(map(lambda x: x**2, X)))/len(X) - X_bar**2) Y_std = sqrt(sum(list(map(lambda y: y**2, Y)))/len(Y) - Y_bar**2) XY_cov = sum([x*y for x, y in zip(X, Y)])/len(X) - X_bar * Y_bar ro = XY_cov / (X_std * Y_std) print(f'{ro:.3f}') ###Output _____no_output_____
examples/grids/smib_milano_ex8p1/smib_milano_ex8p1_4ord_avr/smib_milano_ex8p1_4ord_avr_pss.ipynb
###Markdown SMIB system as in Milano's book example 8.1 ###Code %matplotlib widget import numpy as np import matplotlib.pyplot as plt import scipy.optimize as sopt import ipywidgets from pydae import ssa import json ###Output _____no_output_____ ###Markdown Import system module ###Code from smib_milano_ex8p1_4ord_avr_pss import smib_milano_ex8p1_4ord_avr_pss_class ###Output _____no_output_____ ###Markdown Instantiate system ###Code smib = smib_milano_ex8p1_4ord_avr_pss_class() xy_0_dict = { 'omega':1,'v_ref':1,'v_c':1 } ###Output _____no_output_____ ###Markdown Initialize the system (backward and foreward) ###Code events=[{'p_m':0.8, 'v_t':1.0, 'K_a':100, 'T_e':0.1}] smib.initialize(events,xy_0_dict) smib.save_0() smib.ss() smib.report_u() smib.report_x() smib.report_y() ssa.eval_A(smib) ssa.damp_report(smib) smib = smib_milano_ex8p1_4ord_avr_pss_class() smib.load_0('xy_0.json') smib.ss() smib.eval_jacobians() smib.eval_A() ssa.damp_report(smib) smib.report_params() smib.load_0('xy_0.json') def obj(x): T_1 = x[0] #K_stab = x[1] smib.set_value('T_1',T_1) freq = 1.2 T_2 = 0.1 cplx = (1j*2*np.pi*freq*T_1 + 1)/(1j*2*np.pi*freq*T_2 + 1) smib.set_value('K_stab',1) smib.set_value('K_a',100) smib.set_value('H',6) smib.ss() smib.eval_jacobians() ssa.eval_A(smib) eig_values,eig_vectors = np.linalg.eig(smib.A) zetas = -eig_values.real/np.abs(eig_values) return -100*np.min(zetas) sopt.differential_evolution(obj,bounds=[(0.1,5)]) events=[{'t_end':1.0}, {'t_end':5.0, 'v_ref':v_ref_0*1.05} ] smib.simulate(events,xy0='prev'); plt.close('all') fig, axes = plt.subplots(nrows=2,ncols=2, figsize=(10, 5), frameon=False, dpi=70) axes[0,0].plot(smib.T, smib.get_values('omega'), label=f'$\omega$') axes[0,1].plot(smib.T, smib.get_values('v_t'), label=f'$v_t$') axes[1,0].plot(smib.T, smib.get_values('p_t'), label=f'$p_t$') axes[1,1].plot(smib.T, smib.get_values('q_t'), label=f'$q_t$') for ax in axes.flatten(): ax.legend() ###Output _____no_output_____ ###Markdown Simulation ###Code smib = smib_milano_ex8p1_4ord_avr_pss_class() events=[{'p_t':0.8, 'v_t':1.0, 'K_a':200, 'T_e':0.2, 'H':6, 'K_stab':0, 'T_1':0.1}] smib.initialize(events,xy0=1) v_ref_0 = smib.get_value('v_ref') events=[{'t_end':1.0}, {'t_end':15.0, 'v_ref':v_ref_0*1.05} ] smib.simulate(events,xy0='prev'); plt.close('all') fig, axes = plt.subplots(nrows=2,ncols=2, figsize=(10, 5), frameon=False, dpi=70) axes[0,0].plot(smib.T, smib.get_values('omega'), label=f'$\omega$') axes[0,1].plot(smib.T, smib.get_values('v_t'), label=f'$v_t$') axes[1,0].plot(smib.T, smib.get_values('p_t'), label=f'$p_t$') axes[1,1].plot(smib.T, smib.get_values('q_t'), label=f'$q_t$') for ax in axes.flatten(): ax.legend() smib = smib_milano_ex8p1_4ord_avr_pss_class() events=[{'p_t':0.8, 'v_t':1.0, 'K_a':200, 'T_e':0.2, 'H':6, 'K_stab':0, 'T_1':0.1}] smib.initialize(events,xy_0_dict) ssa.eval_A(smib) ssa.damp_report(smib) ###Output _____no_output_____ ###Markdown Run in two time intervals ###Code events=[{'t_end':1.0}] syst.run(events) events=[{'t_end':2.0}] syst.run(events) syst.get_value('omega') events=[{'p_t':0.8, 'v_t':1.0, 'K_a':100, 'T_e':0.2, 'H':6, 'K_stab':0, 'T_1':0.1}] smib.initialize(events,xy0=1) ssa.eval_A(smib) ssa.damp_report(smib) ssa.participation(smib).abs().round(2) smib.report_params() Ts_control = 0.010 times = np.arange(0.0,10,Ts_control) # Calculate second references events=[{'P_t':0.9, 'Q_t':0.0}] syst.initialize(events,xy0=1.0) x_ref = np.copy(syst.struct[0].x) v_f_ref = syst.struct[0]['v_f'] p_m_ref = syst.struct[0]['p_m'] # Calculate initial references events=[{'P_t':0.0, 'Q_t':0.0}] syst.initialize(events,xy0=1.0) x_0 = np.copy(syst.struct[0].x) v_f_0 = syst.get_value('v_f') p_m_0 = syst.get_value('p_m') # Control design ssa.eval_ss(syst) Q = np.eye(syst.N_x)*100 R = np.eye(syst.N_u) K = ctrl.place(syst.A,syst.B,[-2.0+1j*6,-2.0-1j*6,-100,-101]) K,S,E = ctrl.lqr(syst.A,syst.B,Q,R) Ad,Bd = ssa.discretise_time(syst.A,syst.B,Ts_control) Kd,S,E = ssa.dlqr(Ad,Bd,Q,R) for t in times: x = np.copy(syst.struct[0].x) v_f = v_f_0 p_m = p_m_0 if t>1.0: u_ctrl = K*(x_ref - x) p_m = p_m_ref + u_ctrl[0] v_f = v_f_ref + u_ctrl[1] events=[{'t_end':t,'v_f':v_f,'p_m':p_m}] syst.run(events) syst.post(); plt.close('all') fig, axes = plt.subplots(nrows=2,ncols=2, figsize=(10, 5), frameon=False, dpi=50) axes[0,0].plot(syst.T, syst.get_values('omega'), label=f'$\omega$') axes[0,1].plot(syst.T, syst.get_values('v_1'), label=f'$v_1$') axes[1,0].plot(syst.T, syst.get_values('P_t'), label=f'$P_t$') axes[1,1].plot(syst.T, syst.get_values('Q_t'), label=f'$Q_t$') ssa.eval_ss(syst) from scipy.signal import ss2tf,lti,bode num,den =ss2tf(syst.A,syst.B,syst.C,syst.D,input=0) G = lti(num[1],den) w, mag, phase = G.bode() plt.figure() plt.semilogx(w, mag) # Bode magnitude plot plt.figure() plt.semilogx(w, phase) # Bode phase plot plt.show() events=[{'t_end':1.0,'P_t':0.8, 'Q_t':0.5}, {'t_end':10.0, 'p_m':0.9} ] syst.simulate(events,xy0=1.0); syst.inputs_run_list 0.01/6 syst.B syst.struct[0]['Fu'] ###Output _____no_output_____
utils/notebooks/model_full.ipynb
###Markdown Shuffle the dataset. ###Code from sklearn.utils import shuffle processed_data = shuffle(processed_data) X = processed_data[:,:-1].astype(float) y = processed_data[:,-1].astype(int) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) Xtrain[0].shape[0] print(Xtrain.dtype) print(Ytrain) ###Output [0 0 0 ... 0 0 0] ###Markdown Fully connected neural network model with 3 hidden layers: ###Code import tensorflow as tf model = tf.keras.models.Sequential([ tf.keras.Input(shape=(X_train[0].shape[0],)), #Xtrain[0].shape[0] = 108 -> input size tf.keras.layers.Dense(15, activation='relu'), #represents 1st hidden layer tf.keras.layers.Dropout(0.2), # dropout regularization with dropout probability 20% percent tf.keras.layers.Dense(7, activation='relu'), #represents the 2nd hidden layer tf.keras.layers.Dropout(0.2), # dropout regularization with dropout probability 20% percent tf.keras.layers.Dense(4, activation='relu'), #represents the 3rd hidden layer tf.keras.layers.Dropout(0.2), # dropout regularization with dropout probability 20% percent tf.keras.layers.Dense(1, activation='sigmoid') # sigmoid activation at output since it is binary classification ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.summary() ###Output Model: "sequential_7" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_28 (Dense) (None, 15) 1635 _________________________________________________________________ dropout_21 (Dropout) (None, 15) 0 _________________________________________________________________ dense_29 (Dense) (None, 7) 112 _________________________________________________________________ dropout_22 (Dropout) (None, 7) 0 _________________________________________________________________ dense_30 (Dense) (None, 4) 32 _________________________________________________________________ dropout_23 (Dropout) (None, 4) 0 _________________________________________________________________ dense_31 (Dense) (None, 1) 5 ================================================================= Total params: 1,784 Trainable params: 1,784 Non-trainable params: 0 _________________________________________________________________ ###Markdown Train the model with 10 epochs: ###Code r2 = model.fit(X_train, y_train, epochs=150) ###Output Epoch 1/150 101/101 [==============================] - 1s 1ms/step - loss: 145.9402 - accuracy: 0.8358 Epoch 2/150 101/101 [==============================] - 0s 1ms/step - loss: 30.3910 - accuracy: 0.7783 Epoch 3/150 101/101 [==============================] - 0s 960us/step - loss: 20.8436 - accuracy: 0.8890 Epoch 4/150 101/101 [==============================] - 0s 960us/step - loss: 12.8123 - accuracy: 0.8991 Epoch 5/150 101/101 [==============================] - 0s 990us/step - loss: 11.4324 - accuracy: 0.9137 Epoch 6/150 101/101 [==============================] - 0s 1ms/step - loss: 4.3560 - accuracy: 0.9117 Epoch 7/150 101/101 [==============================] - 0s 1000us/step - loss: 2.3523 - accuracy: 0.9109 Epoch 8/150 101/101 [==============================] - 0s 1ms/step - loss: 3.8448 - accuracy: 0.9153 Epoch 9/150 101/101 [==============================] - 0s 1ms/step - loss: 1.5151 - accuracy: 0.9146 Epoch 10/150 101/101 [==============================] - 0s 1ms/step - loss: 1.0658 - accuracy: 0.9061 Epoch 11/150 101/101 [==============================] - 0s 1ms/step - loss: 0.6152 - accuracy: 0.9204: 0s - loss: 0.6139 - accuracy: 0.92 Epoch 12/150 101/101 [==============================] - 0s 1ms/step - loss: 0.7392 - accuracy: 0.9057 Epoch 13/150 101/101 [==============================] - 0s 1ms/step - loss: 1.3826 - accuracy: 0.9137 Epoch 14/150 101/101 [==============================] - 0s 1ms/step - loss: 0.5601 - accuracy: 0.9182 Epoch 15/150 101/101 [==============================] - 0s 1ms/step - loss: 0.4373 - accuracy: 0.9223 Epoch 16/150 101/101 [==============================] - 0s 950us/step - loss: 0.7177 - accuracy: 0.9190 Epoch 17/150 101/101 [==============================] - 0s 940us/step - loss: 0.3467 - accuracy: 0.9114 Epoch 18/150 101/101 [==============================] - 0s 940us/step - loss: 0.3273 - accuracy: 0.9154 Epoch 19/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3264 - accuracy: 0.9112 Epoch 20/150 101/101 [==============================] - 0s 920us/step - loss: 0.3304 - accuracy: 0.9062 Epoch 21/150 101/101 [==============================] - 0s 900us/step - loss: 0.3189 - accuracy: 0.9109 Epoch 22/150 101/101 [==============================] - 0s 890us/step - loss: 0.3067 - accuracy: 0.9160 Epoch 23/150 101/101 [==============================] - 0s 910us/step - loss: 0.3122 - accuracy: 0.9112 Epoch 24/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3101 - accuracy: 0.9113 Epoch 25/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2955 - accuracy: 0.9180 Epoch 26/150 101/101 [==============================] - 0s 960us/step - loss: 0.2911 - accuracy: 0.9191 Epoch 27/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3017 - accuracy: 0.9128 Epoch 28/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2881 - accuracy: 0.9190 Epoch 29/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3068 - accuracy: 0.9093 Epoch 30/150 101/101 [==============================] - 0s 910us/step - loss: 0.2924 - accuracy: 0.9161 Epoch 31/150 101/101 [==============================] - 0s 910us/step - loss: 0.2855 - accuracy: 0.9190 Epoch 32/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3017 - accuracy: 0.9110 Epoch 33/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2944 - accuracy: 0.9142 Epoch 34/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3004 - accuracy: 0.9112 Epoch 35/150 101/101 [==============================] - 0s 960us/step - loss: 0.2884 - accuracy: 0.9165 Epoch 36/150 101/101 [==============================] - 0s 990us/step - loss: 0.2977 - accuracy: 0.9123 Epoch 37/150 101/101 [==============================] - 0s 910us/step - loss: 0.2839 - accuracy: 0.9183 Epoch 38/150 101/101 [==============================] - 0s 910us/step - loss: 0.3008 - accuracy: 0.9105 Epoch 39/150 101/101 [==============================] - 0s 830us/step - loss: 0.2925 - accuracy: 0.9144 Epoch 40/150 101/101 [==============================] - 0s 830us/step - loss: 0.2934 - accuracy: 0.9140 Epoch 41/150 101/101 [==============================] - 0s 820us/step - loss: 0.2894 - accuracy: 0.9157 Epoch 42/150 101/101 [==============================] - 0s 850us/step - loss: 0.2849 - accuracy: 0.9174 Epoch 43/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2896 - accuracy: 0.9154 Epoch 44/150 101/101 [==============================] - 0s 950us/step - loss: 0.2937 - accuracy: 0.9136 Epoch 45/150 101/101 [==============================] - 0s 940us/step - loss: 0.3066 - accuracy: 0.9080 Epoch 46/150 101/101 [==============================] - 0s 890us/step - loss: 0.3024 - accuracy: 0.9099 Epoch 47/150 101/101 [==============================] - 0s 900us/step - loss: 0.2744 - accuracy: 0.9218 Epoch 48/150 101/101 [==============================] - 0s 917us/step - loss: 0.2914 - accuracy: 0.9146 Epoch 49/150 101/101 [==============================] - 0s 842us/step - loss: 0.2777 - accuracy: 0.9204 Epoch 50/150 101/101 [==============================] - 0s 884us/step - loss: 0.3010 - accuracy: 0.9104 Epoch 51/150 101/101 [==============================] - 0s 844us/step - loss: 0.2773 - accuracy: 0.9205 Epoch 52/150 101/101 [==============================] - 0s 906us/step - loss: 0.2917 - accuracy: 0.9144 Epoch 53/150 101/101 [==============================] - 0s 854us/step - loss: 0.2798 - accuracy: 0.9196 Epoch 54/150 101/101 [==============================] - 0s 888us/step - loss: 0.2918 - accuracy: 0.9144 Epoch 55/150 101/101 [==============================] - 0s 940us/step - loss: 0.2983 - accuracy: 0.9116 Epoch 56/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2943 - accuracy: 0.9135 Epoch 57/150 101/101 [==============================] - 0s 980us/step - loss: 0.3071 - accuracy: 0.9079 Epoch 58/150 101/101 [==============================] - 0s 879us/step - loss: 0.2840 - accuracy: 0.9178 Epoch 59/150 101/101 [==============================] - 0s 860us/step - loss: 0.3051 - accuracy: 0.9087 Epoch 60/150 101/101 [==============================] - 0s 842us/step - loss: 0.2954 - accuracy: 0.9129 Epoch 61/150 101/101 [==============================] - 0s 845us/step - loss: 0.2985 - accuracy: 0.9115 Epoch 62/150 101/101 [==============================] - 0s 853us/step - loss: 0.2796 - accuracy: 0.9194 Epoch 63/150 101/101 [==============================] - 0s 833us/step - loss: 0.2559 - accuracy: 0.9297 Epoch 64/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2882 - accuracy: 0.9159 Epoch 65/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3027 - accuracy: 0.9097 Epoch 66/150 101/101 [==============================] - 0s 880us/step - loss: 0.2836 - accuracy: 0.9179 Epoch 67/150 101/101 [==============================] - 0s 840us/step - loss: 0.2836 - accuracy: 0.9179 Epoch 68/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2792 - accuracy: 0.9198 Epoch 69/150 101/101 [==============================] - 0s 1ms/step - loss: 0.3025 - accuracy: 0.9099 Epoch 70/150 101/101 [==============================] - 0s 850us/step - loss: 0.3135 - accuracy: 0.9052 Epoch 71/150 101/101 [==============================] - 0s 863us/step - loss: 0.2897 - accuracy: 0.9153 Epoch 72/150 101/101 [==============================] - 0s 839us/step - loss: 0.2944 - accuracy: 0.9133 Epoch 73/150 101/101 [==============================] - 0s 894us/step - loss: 0.2931 - accuracy: 0.9139 Epoch 74/150 101/101 [==============================] - 0s 852us/step - loss: 0.3052 - accuracy: 0.9087 Epoch 75/150 101/101 [==============================] - 0s 900us/step - loss: 0.2947 - accuracy: 0.9132 Epoch 76/150 101/101 [==============================] - 0s 890us/step - loss: 0.2757 - accuracy: 0.9212 Epoch 77/150 101/101 [==============================] - 0s 880us/step - loss: 0.2985 - accuracy: 0.9116 Epoch 78/150 101/101 [==============================] - 0s 1ms/step - loss: 0.2873 - accuracy: 0.9163 Epoch 79/150 101/101 [==============================] - 0s 910us/step - loss: 0.3000 - accuracy: 0.9109 ###Markdown Plot the losses: ###Code plt.plot(r2.history['loss'], label='loss') #plt.plot(r2.history['val_loss'], label='val_loss') plt.legend() ###Output _____no_output_____ ###Markdown Plot the accuracies: ###Code plt.plot(r2.history['accuracy'], label='acc') #plt.plot(r2.history['val_accuracy'], label='val_acc') plt.legend() print(model.evaluate(X_test, y_test)) model.save_weights('./weights/model_systolic_diastolic_excluded/') ###Output _____no_output_____ ###Markdown **Applying this dataset on different models to create benchmarks to compare with Fully Connected model:** *Logistic Regression* **(linear classifier):** ###Code from sklearn.linear_model import LogisticRegression model =LogisticRegression() model.fit(X_train, y_train) print(model.score(X_train, y_train)) print(model.score(X_test,y_test)) for i in range(X_train[0].shape[0]): print("weight for the feature",i,":",model.coef_[0][i]) model.coef_[0].sort() print("sorted list, positive weights contribute MORE TO DETERMINE potential hypertension case and negative features conribute more to make prediction as NOT hypertension. So we can say 0 valued weights do not contribute to anything:",model.coef_[0]) ###Output weight for the feature 0 : -0.002204197745180158 weight for the feature 1 : -0.0020580556545120496 weight for the feature 2 : -0.0018476029920989035 weight for the feature 3 : -0.0017392015573981473 weight for the feature 4 : -0.001309569884951161 weight for the feature 5 : -0.0012986945766602534 weight for the feature 6 : -0.0012558997868359195 weight for the feature 7 : -0.001044450183718869 weight for the feature 8 : -0.0010411694398086097 weight for the feature 9 : -0.001003031407691053 weight for the feature 10 : -0.0009978758145447076 weight for the feature 11 : -0.0008635668161326685 weight for the feature 12 : -0.0008060209811952334 weight for the feature 13 : -0.0007723014259508736 weight for the feature 14 : -0.00043181865850317993 weight for the feature 15 : -0.00036305971840124495 weight for the feature 16 : -0.00034605420873229067 weight for the feature 17 : -0.0003215899842853878 weight for the feature 18 : -0.00029768026994142743 weight for the feature 19 : -0.00021503252902479187 weight for the feature 20 : -0.00018414498287057135 weight for the feature 21 : -0.00015214187901898255 weight for the feature 22 : -0.00013145456687364403 weight for the feature 23 : -9.131808199608684e-05 weight for the feature 24 : -9.069291103926271e-05 weight for the feature 25 : -6.26050637143378e-05 weight for the feature 26 : -5.234520575306838e-05 weight for the feature 27 : -4.733510538892756e-05 weight for the feature 28 : -2.7441116057177076e-05 weight for the feature 29 : -2.112005390565407e-05 weight for the feature 30 : -1.9644759250143093e-05 weight for the feature 31 : -1.6648835251829046e-05 weight for the feature 32 : -1.438450096272556e-05 weight for the feature 33 : -1.4192585289277e-05 weight for the feature 34 : -1.4041359495178202e-05 weight for the feature 35 : -1.2957218149275538e-05 weight for the feature 36 : -1.2701743479999902e-05 weight for the feature 37 : -1.2260372977818067e-05 weight for the feature 38 : -1.2089988823209605e-05 weight for the feature 39 : -1.1456858760496845e-05 weight for the feature 40 : -1.1426565738571777e-05 weight for the feature 41 : -1.1100513127682143e-05 weight for the feature 42 : -1.1045382641201871e-05 weight for the feature 43 : -1.0900586338660222e-05 weight for the feature 44 : -1.0646041057854768e-05 weight for the feature 45 : -8.895829558217836e-06 weight for the feature 46 : -8.467076640820137e-06 weight for the feature 47 : -8.46683230710532e-06 weight for the feature 48 : -7.464918992053486e-06 weight for the feature 49 : -6.660404497702645e-06 weight for the feature 50 : -6.660404497702637e-06 weight for the feature 51 : -5.585068607032158e-06 weight for the feature 52 : -5.585068607032158e-06 weight for the feature 53 : -5.085869355470354e-06 weight for the feature 54 : -3.940612734408723e-06 weight for the feature 55 : -3.684987853060102e-06 weight for the feature 56 : -3.5138101710966967e-06 weight for the feature 57 : -3.433581989436847e-06 weight for the feature 58 : -2.8597817095667753e-06 weight for the feature 59 : -2.3503274583278408e-06 weight for the feature 60 : -2.3302029746963264e-06 weight for the feature 61 : -1.9198180225464525e-06 weight for the feature 62 : -1.7098052967395282e-06 weight for the feature 63 : -1.1475896612664792e-06 weight for the feature 64 : -1.127629282336915e-06 weight for the feature 65 : -1.0988664126315144e-06 weight for the feature 66 : -9.187410055737733e-07 weight for the feature 67 : -8.706546627976764e-07 weight for the feature 68 : -7.266318166202316e-07 weight for the feature 69 : -5.991694140895009e-07 weight for the feature 70 : -5.591708630871402e-07 weight for the feature 71 : -5.270349995785656e-07 weight for the feature 72 : -5.270349995785654e-07 weight for the feature 73 : -5.127387071059556e-07 weight for the feature 74 : -4.1192352710556633e-07 weight for the feature 75 : -3.4481447533078734e-07 weight for the feature 76 : -3.194320807046258e-07 weight for the feature 77 : -2.9422528169894045e-07 weight for the feature 78 : -2.2621897169226073e-07 weight for the feature 79 : -1.9729710334979552e-07 weight for the feature 80 : -9.22755470703345e-08 weight for the feature 81 : 4.9322132183351365e-08 weight for the feature 82 : 2.269975263746754e-07 weight for the feature 83 : 2.955866648387692e-07 weight for the feature 84 : 4.3215383668249797e-07 weight for the feature 85 : 4.3215383668249797e-07 weight for the feature 86 : 4.5196322290104333e-07 weight for the feature 87 : 4.562703771415081e-07 weight for the feature 88 : 6.443546015296859e-07 weight for the feature 89 : 6.502938593458788e-07 weight for the feature 90 : 7.117450453589198e-07 weight for the feature 91 : 8.54650329545992e-07 weight for the feature 92 : 9.64787197472597e-07 weight for the feature 93 : 1.0149093497867197e-06 weight for the feature 94 : 1.0262422297789211e-06 weight for the feature 95 : 1.1670970349930403e-06 weight for the feature 96 : 1.3989427603701783e-06 weight for the feature 97 : 1.6152415296342415e-06 weight for the feature 98 : 1.6152415296342415e-06 weight for the feature 99 : 1.7844959395724763e-06 weight for the feature 100 : 1.9143781245295206e-06 weight for the feature 101 : 2.1390278579975307e-06 weight for the feature 102 : 2.195553946908131e-06 weight for the feature 103 : 2.9235156724174116e-06 weight for the feature 104 : 3.484529034590651e-06 weight for the feature 105 : 4.617190687997532e-06 weight for the feature 106 : 7.909793602692546e-06 weight for the feature 107 : 9.036461893761524e-06 sorted list, positive weights contribute MORE TO DETERMINE potential fraud case and negative features conribute to make prediction as NOT FRAUD. So we can say 0 valued weights do not contribute to anything: [-2.20419775e-03 -2.05805565e-03 -1.84760299e-03 -1.73920156e-03 -1.30956988e-03 -1.29869458e-03 -1.25589979e-03 -1.04445018e-03 -1.04116944e-03 -1.00303141e-03 -9.97875815e-04 -8.63566816e-04 -8.06020981e-04 -7.72301426e-04 -4.31818659e-04 -3.63059718e-04 -3.46054209e-04 -3.21589984e-04 -2.97680270e-04 -2.15032529e-04 -1.84144983e-04 -1.52141879e-04 -1.31454567e-04 -9.13180820e-05 -9.06929110e-05 -6.26050637e-05 -5.23452058e-05 -4.73351054e-05 -2.74411161e-05 -2.11200539e-05 -1.96447593e-05 -1.66488353e-05 -1.43845010e-05 -1.41925853e-05 -1.40413595e-05 -1.29572181e-05 -1.27017435e-05 -1.22603730e-05 -1.20899888e-05 -1.14568588e-05 -1.14265657e-05 -1.11005131e-05 -1.10453826e-05 -1.09005863e-05 -1.06460411e-05 -8.89582956e-06 -8.46707664e-06 -8.46683231e-06 -7.46491899e-06 -6.66040450e-06 -6.66040450e-06 -5.58506861e-06 -5.58506861e-06 -5.08586936e-06 -3.94061273e-06 -3.68498785e-06 -3.51381017e-06 -3.43358199e-06 -2.85978171e-06 -2.35032746e-06 -2.33020297e-06 -1.91981802e-06 -1.70980530e-06 -1.14758966e-06 -1.12762928e-06 -1.09886641e-06 -9.18741006e-07 -8.70654663e-07 -7.26631817e-07 -5.99169414e-07 -5.59170863e-07 -5.27035000e-07 -5.27035000e-07 -5.12738707e-07 -4.11923527e-07 -3.44814475e-07 -3.19432081e-07 -2.94225282e-07 -2.26218972e-07 -1.97297103e-07 -9.22755471e-08 4.93221322e-08 2.26997526e-07 2.95586665e-07 4.32153837e-07 4.32153837e-07 4.51963223e-07 4.56270377e-07 6.44354602e-07 6.50293859e-07 7.11745045e-07 8.54650330e-07 9.64787197e-07 1.01490935e-06 1.02624223e-06 1.16709703e-06 1.39894276e-06 1.61524153e-06 1.61524153e-06 1.78449594e-06 1.91437812e-06 2.13902786e-06 2.19555395e-06 2.92351567e-06 3.48452903e-06 4.61719069e-06 7.90979360e-06 9.03646189e-06] ###Markdown *Decision Tree* ###Code from sklearn.tree import DecisionTreeClassifier model =DecisionTreeClassifier() model.fit(X_train, y_train) print(model.score(X_train, y_train)) print(model.score(X_test,y_test)) ###Output 1.0 1.0 ###Markdown *AdaBoost* ###Code from sklearn.ensemble import AdaBoostClassifier model =AdaBoostClassifier() model.fit(X_train, y_train) print(model.score(X_train, y_train)) print(model.score(X_test,y_test)) # Visualize the data (tsne is great but slow.) from sklearn.manifold import TSNE tsne = TSNE(n_components=2) transformed = tsne.fit_transform(X_train) #visualize in the 2d plt.scatter(transformed[:,0], transformed[:,1], c=y_train) #take first two columns in order to get 2d plot. plt.show() transformed = tsne.fit_transform(X_test) # visualize the clouds in 2-D plt.scatter(transformed[:,0], transformed[:,1], c=y_test) #take first two columns in order to get 2d plot. plt.show() ###Output _____no_output_____
temp/HowToBreakIntoTheField.ipynb
###Markdown ScreencastIn the previous video, I brought a few questions we will be exploring throughout this lesson. First, let's take a look at the data, and see how we might answer the first question about how to break into the field of becoming a software developoer according to the survey results.To get started, let's read in the necessary libraries we will need to wrangle our data: pandas and numpy. If we decided to build some basic plots, matplotlib might prove useful as well. ###Code import numpy as np import pandas as pd from collections import defaultdict import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('./Part I/stackoverflow/survey_results_public.csv') df.head() ###Output _____no_output_____ ###Markdown Now to look at our first question of interest: What do those employed in the industry suggest to help others enter the field? Looking at the `CousinEducation` field, you can see what these individuals would suggest to help others break into their field. Below you can take a look at the full field that survey participants would see. ###Code df2 = pd.read_csv('./Part I/stackoverflow/survey_results_schema.csv') list(df2[df2.Column == 'CousinEducation']['Question']) #Let's have a look at what the participants say study = df['CousinEducation'].value_counts().reset_index() study.head() # Oh this isn't what I was expecting, it is grouping items together if a participant provided # more than just one answer. Let's see if we can clean this up. # first to change this index column to a more appropriate name study.rename(columns={'index': 'method', 'CousinEducation': 'count'}, inplace=True) study.head() ###Output _____no_output_____ ###Markdown A quick look through data, allows us to create a list of all of the individual methods marked by a user. ###Code # Here is a list of the different answers provided possible_vals = ["Take online courses", "Buy books and work through the exercises", "None of these", "Part-time/evening courses", "Return to college", "Contribute to open source", "Conferences/meet-ups", "Bootcamp", "Get a job as a QA tester", "Participate in online coding competitions", "Master's degree", "Participate in hackathons", "Other"] #Now we want to see how often each of these individual values appears - I wrote # this function to assist with process - it isn't the best solution, but it gets # the job done and our dataset isn't large enough to computationally hurt us too much. def total_count(df, col1, col2, look_for): ''' INPUT: df - the pandas dataframe you want to search col1 - the column name you want to look through col2 - the column you want to count values from look_for - a list of strings you want to search for in each row of df[col] OUTPUT: new_df - a dataframe of each look_for with the count of how often it shows up ''' new_df = defaultdict(int) for val in look_for: for idx in range(df.shape[0]): if val in df[col1][idx]: new_df[val] += int(df[col2][idx]) new_df = pd.DataFrame(pd.Series(new_df)).reset_index() new_df.columns = [col1, col2] new_df.sort_values('count', ascending=False, inplace=True) return new_df # Now we can use our function and take a look at the results # Looks like good news for Udacity - most individuals think that you # should take online courses study_df = total_count(study, 'method', 'count', possible_vals) study_df # We might also look at the percent study_df['perc'] = study_df['count']/np.sum(study_df['count']) study_df ###Output _____no_output_____ ###Markdown We might want to take this one step further and say we care more about the methods that are suggested by those who earn more, or those who have higher job satisfaction. Let's take a stab at incorporating that into this analysis. ###Code # let's rewrite part of this function to get the mean salary for each method def mean_amt(df, col_name, col_mean, look_for): ''' INPUT: df - the pandas dataframe you want to search col_name - the column name you want to look through col_count - the column you want to count values from col_mean - the column you want the mean amount for look_for - a list of strings you want to search for in each row of df[col] OUTPUT: df_all - holds sum, square, total, mean, variance, and standard deviation for the col_mean ''' new_df = defaultdict(int) squares_df = defaultdict(int) denoms = dict() for val in look_for: denoms[val] = 0 for idx in range(df.shape[0]): if df[col_name].isnull()[idx] == False: if val in df[col_name][idx] and df[col_mean][idx] > 0: new_df[val] += df[col_mean][idx] squares_df[val] += df[col_mean][idx]**2 #Needed to understand the spread denoms[val] += 1 # Turn into dataframes new_df = pd.DataFrame(pd.Series(new_df)).reset_index() squares_df = pd.DataFrame(pd.Series(squares_df)).reset_index() denoms = pd.DataFrame(pd.Series(denoms)).reset_index() # Change the column names new_df.columns = [col_name, 'col_sum'] squares_df.columns = [col_name, 'col_squares'] denoms.columns = [col_name, 'col_total'] # Merge dataframes df_means = pd.merge(new_df, denoms) df_all = pd.merge(df_means, squares_df) # Additional columns needed for analysis df_all['mean_col'] = df_means['col_sum']/df_means['col_total'] df_all['var_col'] = df_all['col_squares']/df_all['col_total'] - df_all['mean_col']**2 df_all['std_col'] = np.sqrt(df_all['var_col']) df_all['lower_95'] = df_all['mean_col'] - 1.96*df_all['std_col']/np.sqrt(df_all['col_total']) df_all['upper_95'] = df_all['mean_col'] + 1.96*df_all['std_col']/np.sqrt(df_all['col_total']) return df_all df_all = mean_amt(df, 'CousinEducation', 'Salary', possible_vals) # To get a simple answer to our questions - see these two tables. df_all.sort_values('mean_col', ascending=False) study_df ###Output _____no_output_____ ###Markdown Although we can see the mean salary is highest for the individuals who say that you should contribute to open source, you might be asking - is that really a significant difference? The salary differences don't see that large...By the Central Limit Theorem, we know that the mean of any set of data will follow a normal distribution with a standard deviation equal to the standard deviation of the original data divided by the square root of the sample size, as long as we collect a large enough sample size. With that in mind, we can consider two salaries significantly different if a second salary is two standard deviations or more away from the other.Using the lower and upper bound components, we can get an idea of the salaries that are significantly different from one another. ###Code # Quiz - perform a similar analysis looking at career and job satisfaction for this individuals # to determine which you want to be like df_jobsat = mean_amt(df, 'CousinEducation', 'JobSatisfaction', possible_vals) df_jobsat.sort_values('mean_col', ascending=False) pd.DataFrame(np.hstack([df_jobsat, df_all])) pd.DataFrame? df_jobsat.col_total df_dotplot = pd.DataFrame(np.array(['Method', "At least Master's", "Less Than Master's", "Master's Degree",0.0589517,0.0293459, "Bootcamp",0.0746172,0.071824, "Become QA Tester",0.0484688,0.0457388, "Buy Books",0.162073,0.161205, "None of these",0.00836278,0.00827705, "Part Time Courses",0.103298,0.103248, "Return to College",0.0687279,0.0689754, "Online Courses",0.207892,0.2099, "Contribute to Opensource",0.097821,0.10323, "Coding Competitions",0.0453475,0.0508806, "Other",0.0269729,0.0338607, "Hackathons", 0.0316254,0.0395937, "Conferences", 0.0658422, 0.0739201]).reshape((14, 3))) df_dotplot.columns = df_dotplot.iloc[0] df_dotplot.drop(0, inplace=True) import seaborn as sns df_dotplot.prop = df_dotplot.prop.astype(float) df_dotplot = df_dotplot.melt(id_vars='Method', value_name='prop', var_name='status') sns.pointplot(data=df_dotplot, x='status', y='prop', hue='Method'); for idx, row in df_dotplot.iterrows(): plt.plot([0,1],[row["At least Master's"], row["Less Than Master's"]]); plt.text(1.05, row["Less Than Master's"], row['Method']); plt.xticks([0,1], ["At least Master's", "Less Than Master's"]); for row in df_dotplot: print(row) ###Output Method At least Master's Less Than Master's
SpeedDatingAnalysis/Project_Assignment.ipynb
###Markdown Speed Dating Data Analysis Team Members: Onyinye Ihedero, Sai Manoj Gaddipati, Esha Somavarapu Source of Data: www.kaggle.com Packages Used : Numpy, Pandas, Tabpy(not full fledged) Softwares Used: Anaconda, Jupyter Notebook in Anaconda, Tableau Software, MS-Office. ###Code import numpy as np import pandas as pd data=pd.read_table("speedData.csv", sep=',') data_reqRow=data[['age', 'gender', 'field_cd', 'race', 'imprace', 'imprelig', 'income', 'goal','date','samerace' , 'race_o', 'go_out', 'career_c', 'attr1_1', 'sinc1_1', 'intel1_1', 'fun1_1', 'amb1_1', 'shar1_1', 'satis_2', 'attr7_2', 'sinc7_2', 'intel7_2', 'fun7_2', 'amb7_2', 'shar7_2', 'attr1_s', 'sinc1_s', 'intel1_s', 'fun1_s', 'amb1_s', 'shar1_s', 'you_call', 'them_cal', 'date_3', 'num_in_3', 'attr7_3', 'sinc7_3', 'intel7_3', 'fun7_3', 'amb7_3', 'shar7_3']] import numpy as np data_reqRow = data_reqRow[np.logical_not(np.isnan(data_reqRow.attr1_s))] data_reqRow = data_reqRow.reset_index(drop=True) data_reqRow #To output to .csv do this data_reqRow.to_csv('OutputFinal.csv', index=False) #doing group by ages and getting the count for each one data_count_age=data_reqRow.groupby('age').agg('count').reset_index() data_count_age#.head() #notes for the output below: #we can see that the attendance is more for ages between 22 and 30. The population for ages beyond that is sparse. #doing group by gender and getting the count for each one data_count_gender=data_reqRow.groupby('gender').agg('count').reset_index() data_count_gender#.head() #notes: #number of females=4141 #number of males=4174 #doing group by race and getting the count for each one data_count_race=data_reqRow.groupby('race').agg('count').reset_index() data_count_race#.head() #notes on results: #heres the race description: #Black/African American=1 (420) #European/Caucasian-American=2 (4727) #Latino/Hispanic American=3 (664) #Asian/Pacific Islander/Asian-American=4 (1982) #Native American=5 (0) #Other=6 (522) #it can be noted that the population of Native Americans is 0, no one attended. #doing group by categorised careers and getting the count for each one data_count_career=data_reqRow.groupby('career_c').agg('count').reset_index() data_count_career#.head() #the count results are written in brackets #classification details for career: #1= Lawyer #2= Academic/Research #3= Psychologist #4= Doctor/Medicine #5=Engineer #6= Creative Arts/Entertainment #7= Banking/Consulting/Finance/Marketing/ # Business/CEO/Entrepreneur/Admin #8= Real Estate #9= International/Humanitarian Affairs #10= Undecided #11=Social Work #12=Speech Pathology #13=Politics #14=Pro sports/Athletics #15=Other #16=Journalism #17=Architecture ###Output _____no_output_____ ###Markdown I am adding samerace and race_o back into the dataset at the beginning itself. ###Code #doing group by "if preferring partner from same race" and getting the count for each one data_count_samerace=data_reqRow.groupby('samerace').agg('count').reset_index() data_count_samerace#.head() #notes: # #doing group by categorised careers and getting the count for each one data_count_partner_race=data_reqRow.groupby('race_o').agg('count').reset_index() data_count_partner_race#.head() #which race thinks it is more important to date the same race: res=data_reqRow.pivot_table(index='race', values='imprace', aggfunc=np.mean) print(res) res.to_csv('raceVimprace.csv') #Note on Results: #no race thinks it is extremely important to date someone form the same race. #the only race that feels more important to date their same race is: #European-Caucasian/American with an average imprace of 4.29 #which age thinks it is more important to date the same race: res2=data_reqRow.pivot_table(index='age', values='imprace', aggfunc=np.mean) res2.to_csv('ageVimprace.csv') res2 #there is a strong response from ages 35, 37, and 42 #although the number of people who participated is less for these age groups #which age thinks it is more important to date the same race: res3=data_reqRow.pivot_table(index='race', values='imprelig', aggfunc=np.mean) res3.to_csv('ageVimprace.csv') res3 #which age thinks it is more important to date people from same religion: res4=data_reqRow.pivot_table(index='age', values='imprelig', aggfunc=np.mean) res4.to_csv('ageVimprelig.csv') res4 res6=data_reqRow.pivot_table(index='gender', values=['attr1_1', 'sinc1_1', 'intel1_1', 'fun1_1', 'amb1_1', 'shar1_1'], aggfunc=np.mean) res5.to_csv('start.csv') res6 res5=data_reqRow.pivot_table(index='gender', values=['attr7_2', 'sinc7_2', 'intel7_2', 'fun7_2', 'amb7_2', 'shar7_2'], aggfunc=np.mean) res5.to_csv('after.csv') res5 #we can do the same thing for which race prefers which race but I am a little confused about which variable is the preferred race varaiable4 # here are the variables I am confused about: #samerace: participant and the partner were the same race. 1= yes, 0=no #age_o: age of partner #race_o: race of partner #pf_o_att: partner’s stated preference at Time 1 (attr1_1) for all 6 attributes data_reqRow.to_csv('data_with.csv') ###Output _____no_output_____
notebooks/PhysionetCharacterization/Explore Physionet CTG Outcome Metadata Apgar 1.ipynb
###Markdown Explore Physionet CTG Outcome Metadata Apgar 1see: https://physionet.org/physiobank/database/ctu-uhb-ctgdb/Includes:- Plots of various outcome metrics vs apgar 1- Regression models to predict apgar1 from other outcome metrics ###Code import config_local from config_common import * import wfdb import os from pprint import pprint import numpy as np import matplotlib.pyplot as plt import scipy import scipy.signal from sklearn import svm from sklearn.decomposition import PCA import math import collections from ctg_utils import get_all_recno, parse_meta_comments import random ###Output _____no_output_____ ###Markdown Config Code ###Code def jitter(x, w=2): return x + (random.random()-0.5)/w def display_metric_vs_apgar(metric, apgar, title='', xlabel='', ylabel='', limits=None, thresh=None): plt.figure(figsize=(5,5)) if title: plt.title(title) plt.scatter(metric, [jitter(x) for x in apgar], s=3) if thresh: plt.plot([thresh, thresh], [0, 10], 'r--') plt.ylim(0, 10) if limits: plt.plot(limits, [7, 7], 'r--') plt.xlim(*limits) if ylabel: plt.ylabel(ylabel) if apgar: plt.xlabel(xlabel) plt.show() def display_predictions(actual, pred, title=None, xlabel='Apgar 5'): all_error = [abs(val-pred[i]) for i, val in enumerate(actual)] print('Error -- mean: {:0.2f} std: {:0.2f}'.format(np.mean(all_error), np.std(all_error))) plt.figure(figsize=(5,5)) if title: plt.title(title) plt.scatter([jitter(x) for x in actual], [x for x in pred], s=3) plt.ylim(0, 10) plt.xlim(0, 10) plt.plot([0,10], [0, 10], 'g--', alpha=0.25) plt.plot([0,9.5], [0.5, 10], 'r--', alpha=0.25) plt.plot([0.5,10], [0, 9.5], 'r--', alpha=0.25) plt.plot([7,7], [0, 10], 'r--', alpha=0.25) plt.plot([0, 10], [7,7], 'r--', alpha=0.25) plt.ylabel('Predicted {}'.format(xlabel)) plt.xlabel(xlabel) plt.show() ###Output _____no_output_____ ###Markdown Gather All Recording Metadata ###Code all_meta = {} all_error = [] for recno in sorted(get_all_recno(media_recordings_dir_full)): recno_full = os.path.join(media_recordings_dir_full, recno) #print('Record: {}'.format(recno)) try: all_sig, meta = wfdb.io.rdsamp(recno_full) meta['comments'] = parse_meta_comments(meta['comments']) all_meta[recno] = meta['comments'] except Exception as e: print(' Error: {}'.format(e)) all_error.append(recno) ###Output _____no_output_____ ###Markdown Filter nan values ###Code for recno in sorted(all_meta.keys()): entry = all_meta[recno]['Outcome'] if math.isnan(entry['BDecf']): print('{}: Recording contains NaN'.format(recno)) del all_meta[recno] ###Output 1044: Recording contains NaN 1070: Recording contains NaN 1211: Recording contains NaN 1215: Recording contains NaN 1356: Recording contains NaN 1373: Recording contains NaN 1383: Recording contains NaN 1419: Recording contains NaN 2006: Recording contains NaN 2034: Recording contains NaN 2046: Recording contains NaN ###Markdown Outcomes ###Code for recno in sorted(all_meta.keys()): # recno = '1001' entry = all_meta[recno]['Outcome'] print('{:4}: pH:{:5.2f} BDecf: {:5.2f} pCO2: {:5.2f} BE: {:6.2f} Apgar1: {:2} Apgar5: {:2}'.format( recno, entry['pH'], entry['BDecf'], entry['pCO2'], entry['BE'], entry['Apgar1'], entry['Apgar5'])) all_pH = [entry['Outcome']['pH'] for entry in all_meta.values()] all_BDecf = [entry['Outcome']['BDecf'] for entry in all_meta.values()] all_pCO2 = [entry['Outcome']['pCO2'] for entry in all_meta.values()] all_BE = [entry['Outcome']['BE'] for entry in all_meta.values()] all_Apgar1 = [entry['Outcome']['Apgar1'] for entry in all_meta.values()] all_Apgar5 = [entry['Outcome']['Apgar5'] for entry in all_meta.values()] all_pH_lin = [10**(entry['Outcome']['pH']-7) for entry in all_meta.values()] ###Output _____no_output_____ ###Markdown Show pH vs Apgar1 ###Code display_metric_vs_apgar(all_pH, all_Apgar1, limits=[6.5, 7.5],thresh=7, title='pH vs Apgar1', xlabel='pH', ylabel='Apgar 1') display_metric_vs_apgar(all_pH_lin, all_Apgar1, limits=[0,3], thresh=1, title='linearized pH vs Apgar1', xlabel='linearized pH', ylabel='Apgar 1') ###Output _____no_output_____ ###Markdown Show BDecf vs Apgar1 ###Code print(np.min(all_BDecf), np.max(all_BDecf)) display_metric_vs_apgar(all_BDecf, all_Apgar1, limits=[-5, 30], thresh=12, title='BDecf vs Apgar1', xlabel='BDecf', ylabel='Apgar 1') ###Output -3.4 26.11 ###Markdown Drilldown: BDecf vs Apgar1 for pH normal and abnormal pH ###Code idx_subset = [i for i, x in enumerate(all_pH) if x <= 7] display_metric_vs_apgar([all_BDecf[i] for i in idx_subset], [all_Apgar1[i] for i in idx_subset], limits=[-5, 30], thresh=12, title='pH vs Apgar1 when pH < 7', xlabel='BDecf', ylabel='Apgar 1') idx_subset = [i for i, x in enumerate(all_pH) if x > 7] display_metric_vs_apgar([all_BDecf[i] for i in idx_subset], [all_Apgar1[i] for i in idx_subset], limits=[-5, 30], thresh=12, title='pH vs Apgar1 when pH > 7', xlabel='BDecf', ylabel='Apgar 1') ###Output _____no_output_____ ###Markdown Show BE vs Apgar1 ###Code print(np.min(all_BE), np.max(all_BE)) display_metric_vs_apgar(all_BE, all_Apgar1, limits=[-30, 0], thresh=-8, title='BE vs Apgar1', xlabel='BE', ylabel='Apgar 1') ###Output -26.8 -0.2 ###Markdown Drilldown: BE vs Apgar1 for pH normal and abnormal pH ###Code idx_subset = [i for i, x in enumerate(all_pH) if x <= 7] display_metric_vs_apgar([all_BE[i] for i in idx_subset], [all_Apgar1[i] for i in idx_subset], limits=[-30, 0], thresh=-8, title='BE vs Apgar1 when pH < 7', xlabel='BE', ylabel='Apgar 1') idx_subset = [i for i, x in enumerate(all_pH) if x > 7] display_metric_vs_apgar([all_BE[i] for i in idx_subset], [all_Apgar1[i] for i in idx_subset], limits=[-30, 0], thresh=-8, title='BE vs Apgar1 when pH > 7', xlabel='BE', ylabel='Apgar 1') ###Output _____no_output_____ ###Markdown PCA ###Code all_features = list(zip(all_Apgar1, all_BE, all_pH_lin, all_pH)) # Determine feature count by APGAR counts = collections.defaultdict(int) feature_by_apgar = collections.defaultdict(list) for i, x in enumerate(all_Apgar1): counts[x] += 1 feature_by_apgar[x].append(all_features[i]) for k in sorted(counts.keys()): print(k, counts[k]) # equalize feature set without replace max_entries = 14 train_features = [] train_labels = [] for k, v in feature_by_apgar.items(): if len(v) <= max_entries: train_features += v train_labels += [k] * len(v) else: train_labels += [k] * max_entries for i in np.random.choice(np.arange(len(v)), size=max_entries, replace=False): train_features.append(v[i]) train_features = np.vstack(train_features) n_components = 1 pca = PCA(n_components=n_components) pca.fit(train_features) predict = pca.inverse_transform((pca.transform(train_features))) display_predictions(train_labels, [x[0] for x in predict], title='predict vs Apgar1', xlabel='Apgar 1') pca.components_ pca.explained_variance_ratio_ print(' all_Apgar1, all_BE, all_pH_lin all_pH') print(pca.get_covariance()) ###Output all_Apgar1, all_BE, all_pH_lin all_pH [[ 2.36527923 2.94616761 0.20461864 0.06199188] [ 2.94616761 18.88614959 1.182813 0.35834858] [ 0.20461864 1.182813 1.93776148 0.0248882 ] [ 0.06199188 0.35834858 0.0248882 1.86315239]] ###Markdown Try again ignoring pH (log version) ###Code # strip pH from training set train_features = [x[:-1] for x in train_features] n_components = 1 pca = PCA(n_components=n_components) pca.fit(train_features) predict = pca.inverse_transform((pca.transform(train_features))) display_predictions(train_labels, [x[0] for x in predict], title='predict vs Apgar1', xlabel='Apgar 1') pca.components_ pca.explained_variance_ratio_ print(' all_Apgar1, all_BE, all_pH_lin') print(pca.get_covariance()) ###Output all_Apgar1, all_BE, all_pH_lin [[ 3.26447128 2.79037673 0.19376297] [ 2.79037673 18.91680422 1.12040301] [ 0.19376297 1.12040301 2.85970282]] ###Markdown Modeling: Extimate Apgar1 using Outcome Metrics ###Code all_features = list(zip(all_pH, all_BDecf, all_pCO2, all_BE, all_pH_lin)) ###Output _____no_output_____ ###Markdown SVM Regression 1Without Replacement (limit number of features by apgar) ###Code # Determine feature count by APGAR counts = collections.defaultdict(int) feature_by_apgar1 = collections.defaultdict(list) for i, x in enumerate(all_Apgar1): counts[x] += 1 feature_by_apgar1[x].append(all_features[i]) for k in sorted(counts.keys()): print(k, counts[k]) max_entries = 14 train_features = [] train_labels = [] for k, v in feature_by_apgar1.items(): print(k, len(v)) if len(v) <= max_entries: train_features += v train_labels += [k] * len(v) else: train_labels += [k] * max_entries for i in np.random.choice(np.arange(len(v)), size=max_entries, replace=False): train_features.append(v[i]) train_features = np.vstack(train_features) train_features.shape, len(train_labels) clf = svm.LinearSVR(max_iter=100000) clf.fit(train_features, train_labels) pred_train = clf.predict(train_features) pred_test = clf.predict(all_features) display_predictions(train_labels, pred_train, title='Training Apgar Predictions', xlabel='Apgar 1') display_predictions(all_Apgar1, pred_test, title='All Apgar Predictions', xlabel='Apgar 1') ###Output Error -- mean: 1.80 std: 1.23 ###Markdown SVM Regression 2With Replacement (feature set for sames features for each apgar score) ###Code # Trtaining Set Using Replacement max_entries = 50 train_features = [] train_labels = [] for k, v in feature_by_apgar1.items(): train_labels += [k] * max_entries for i in np.random.choice(np.arange(len(v)), size=max_entries, replace=True): train_features.append(v[i]) train_features = np.vstack(train_features) train_features.shape, len(train_labels) #clf = svm.LinearSVR(max_iter=100000) clf = svm.SVR(max_iter=100000, gamma='scale') clf.fit(train_features, train_labels) pred_train = clf.predict(train_features) pred_test = clf.predict(all_features) display_predictions(all_Apgar1, pred_test, title='All Apgar Predictions', xlabel='Apgar 1') ###Output Error -- mean: 1.92 std: 1.47
CNN scratch.ipynb
###Markdown Splitting Train, Validation, Test Data ###Code train_dir = 'training_data' val_dir = 'validation_data' test_dir = 'test_data' train_files = np.concatenate([cat_train, dog_train]) validate_files = np.concatenate([cat_val, dog_val]) test_files = np.concatenate([cat_test, dog_test]) os.mkdir(train_dir) if not os.path.isdir(train_dir) else None os.mkdir(val_dir) if not os.path.isdir(val_dir) else None os.mkdir(test_dir) if not os.path.isdir(test_dir) else None for fn in train_files: shutil.copy(fn, train_dir) for fn in validate_files: shutil.copy(fn, val_dir) for fn in test_files: shutil.copy(fn, test_dir) #!rm -r test_data/ training_data/ validation_data/ from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img IMG_DIM = (150,150) train_files = glob.glob('training_data/*') train_imgs = [];train_labels = [] for file in train_files: try: train_imgs.append( img_to_array(load_img( file,target_size=IMG_DIM )) ) train_labels.append(file.split('/')[1].split('_')[0]) except: pass train_imgs = np.array(train_imgs) validation_files = glob.glob('validation_data/*') validation_imgs = [];validation_labels = [] for file in validation_files: try: validation_imgs.append( img_to_array(load_img( file,target_size=IMG_DIM )) ) validation_labels.append(file.split('/')[1].split('_')[0]) except: pass train_imgs = np.array(train_imgs) validation_imgs = np.array(validation_imgs) print('Train dataset shape:', train_imgs.shape, '\tValidation dataset shape:', validation_imgs.shape) # encode text category labels from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(train_labels) train_labels_enc = le.transform(train_labels) validation_labels_enc = le.transform(validation_labels) ###Output _____no_output_____ ###Markdown Image Augmentation ###Code train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, rotation_range=50, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, horizontal_flip=True, fill_mode='nearest') val_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow(train_imgs, train_labels_enc, batch_size=30) val_generator = val_datagen.flow(validation_imgs, validation_labels_enc, batch_size=20) ###Output _____no_output_____ ###Markdown Keras Model ###Code from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input from keras.models import Model from keras import optimizers input_shape = (150, 150, 3) input_l = Input((150,150,3)) l1_conv = Conv2D(16, kernel_size=(3, 3), activation='relu')(input_l) l1_pool = MaxPooling2D(pool_size=(2, 2))(l1_conv) l2_conv = Conv2D(64, kernel_size=(3, 3), activation='relu')(l1_pool) l2_pool = MaxPooling2D(pool_size=(2, 2))(l2_conv) l3_conv = Conv2D(128, kernel_size=(3, 3), activation='relu')(l2_pool) l3_pool = MaxPooling2D(pool_size=(2, 2))(l3_conv) l4 = Flatten()(l3_pool) l4_dropout = Dropout(0.3)(l4) l5 = Dense(512, activation='relu')(l4_dropout) l5_dropout = Dropout(0.3)(l5) output = Dense(1, activation='sigmoid')(l5_dropout) model = Model(input_l, output) model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(), metrics=['accuracy']) model.summary() history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=val_generator, validation_steps=50, verbose=2) ###Output WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. Epoch 1/100 - 17s - loss: 0.8622 - acc: 0.5310 - val_loss: 0.6788 - val_acc: 0.5240 Epoch 2/100 - 13s - loss: 0.6918 - acc: 0.5479 - val_loss: 0.6593 - val_acc: 0.5730 Epoch 3/100 - 13s - loss: 0.6772 - acc: 0.5933 - val_loss: 0.5895 - val_acc: 0.6900 Epoch 4/100 - 13s - loss: 0.6583 - acc: 0.6218 - val_loss: 0.6041 - val_acc: 0.6760 Epoch 5/100 - 13s - loss: 0.6430 - acc: 0.6293 - val_loss: 0.5745 - val_acc: 0.6990 Epoch 6/100 - 13s - loss: 0.6190 - acc: 0.6515 - val_loss: 0.5982 - val_acc: 0.6750 Epoch 7/100 - 14s - loss: 0.6172 - acc: 0.6640 - val_loss: 0.5325 - val_acc: 0.7120 Epoch 8/100 - 13s - loss: 0.6209 - acc: 0.6582 - val_loss: 0.5567 - val_acc: 0.7320 Epoch 9/100 - 13s - loss: 0.6211 - acc: 0.6560 - val_loss: 0.5010 - val_acc: 0.7410 Epoch 10/100 - 13s - loss: 0.5903 - acc: 0.6806 - val_loss: 0.5094 - val_acc: 0.7390 Epoch 11/100 - 13s - loss: 0.6082 - acc: 0.6700 - val_loss: 0.5429 - val_acc: 0.7120 Epoch 12/100 - 13s - loss: 0.5843 - acc: 0.6872 - val_loss: 0.5129 - val_acc: 0.7510 Epoch 13/100 - 14s - loss: 0.5839 - acc: 0.6810 - val_loss: 0.4997 - val_acc: 0.7640 Epoch 14/100 - 13s - loss: 0.5899 - acc: 0.6836 - val_loss: 0.5882 - val_acc: 0.7130 Epoch 15/100 - 13s - loss: 0.5805 - acc: 0.7000 - val_loss: 0.7053 - val_acc: 0.6550 Epoch 16/100 - 13s - loss: 0.5820 - acc: 0.6992 - val_loss: 0.4845 - val_acc: 0.7650 Epoch 17/100 - 13s - loss: 0.5752 - acc: 0.7017 - val_loss: 0.5363 - val_acc: 0.7270 Epoch 18/100 - 13s - loss: 0.5657 - acc: 0.7129 - val_loss: 0.4494 - val_acc: 0.7830 Epoch 19/100 - 14s - loss: 0.5787 - acc: 0.6917 - val_loss: 0.5283 - val_acc: 0.7290 Epoch 20/100 - 14s - loss: 0.5658 - acc: 0.7089 - val_loss: 0.4581 - val_acc: 0.7770 Epoch 21/100 - 14s - loss: 0.5553 - acc: 0.7147 - val_loss: 0.6111 - val_acc: 0.6850 Epoch 22/100 - 14s - loss: 0.5580 - acc: 0.7242 - val_loss: 0.5054 - val_acc: 0.7480 Epoch 23/100 - 13s - loss: 0.5588 - acc: 0.7100 - val_loss: 0.4720 - val_acc: 0.7730 Epoch 24/100 - 13s - loss: 0.5505 - acc: 0.7212 - val_loss: 0.5123 - val_acc: 0.7470 Epoch 25/100 - 15s - loss: 0.5712 - acc: 0.7073 - val_loss: 0.4787 - val_acc: 0.7610 Epoch 26/100 - 13s - loss: 0.5408 - acc: 0.7316 - val_loss: 0.4961 - val_acc: 0.7530 Epoch 27/100 - 13s - loss: 0.5300 - acc: 0.7393 - val_loss: 0.4686 - val_acc: 0.7830 Epoch 28/100 - 13s - loss: 0.5505 - acc: 0.7199 - val_loss: 0.5242 - val_acc: 0.7460 Epoch 29/100 - 13s - loss: 0.5271 - acc: 0.7457 - val_loss: 0.4545 - val_acc: 0.7900 Epoch 30/100 - 13s - loss: 0.5384 - acc: 0.7260 - val_loss: 0.4610 - val_acc: 0.7870 Epoch 31/100 - 14s - loss: 0.5223 - acc: 0.7367 - val_loss: 0.4424 - val_acc: 0.7960 Epoch 32/100 - 13s - loss: 0.5512 - acc: 0.7213 - val_loss: 0.4779 - val_acc: 0.7780 Epoch 33/100 - 13s - loss: 0.5463 - acc: 0.7433 - val_loss: 0.4244 - val_acc: 0.8020 Epoch 34/100 - 13s - loss: 0.5385 - acc: 0.7302 - val_loss: 0.5564 - val_acc: 0.7410 Epoch 35/100 - 13s - loss: 0.5427 - acc: 0.7340 - val_loss: 0.8722 - val_acc: 0.6250 Epoch 36/100 - 13s - loss: 0.5305 - acc: 0.7402 - val_loss: 0.4386 - val_acc: 0.8110 Epoch 37/100 - 14s - loss: 0.5184 - acc: 0.7457 - val_loss: 0.4450 - val_acc: 0.7910 Epoch 38/100 - 13s - loss: 0.5441 - acc: 0.7332 - val_loss: 0.4206 - val_acc: 0.8070 Epoch 39/100 - 13s - loss: 0.5285 - acc: 0.7407 - val_loss: 0.4497 - val_acc: 0.7910 Epoch 40/100 - 13s - loss: 0.5281 - acc: 0.7376 - val_loss: 0.4420 - val_acc: 0.8000 Epoch 41/100 - 13s - loss: 0.5231 - acc: 0.7410 - val_loss: 0.4106 - val_acc: 0.8160 Epoch 42/100 - 13s - loss: 0.5220 - acc: 0.7436 - val_loss: 0.5312 - val_acc: 0.7590 Epoch 43/100 - 15s - loss: 0.5149 - acc: 0.7517 - val_loss: 0.4484 - val_acc: 0.7830 Epoch 44/100 - 14s - loss: 0.5223 - acc: 0.7432 - val_loss: 0.4120 - val_acc: 0.8120 Epoch 45/100 - 14s - loss: 0.5195 - acc: 0.7400 - val_loss: 0.4429 - val_acc: 0.7960 Epoch 46/100 - 13s - loss: 0.5246 - acc: 0.7466 - val_loss: 0.4041 - val_acc: 0.8090 Epoch 47/100 - 13s - loss: 0.5075 - acc: 0.7553 - val_loss: 0.4265 - val_acc: 0.8250 Epoch 48/100 - 13s - loss: 0.5156 - acc: 0.7583 - val_loss: 0.4795 - val_acc: 0.7750 Epoch 49/100 - 14s - loss: 0.5120 - acc: 0.7517 - val_loss: 0.4283 - val_acc: 0.8020 Epoch 50/100 - 13s - loss: 0.5255 - acc: 0.7409 - val_loss: 0.4847 - val_acc: 0.7830 Epoch 51/100 - 13s - loss: 0.5193 - acc: 0.7490 - val_loss: 0.4578 - val_acc: 0.7940 Epoch 52/100 - 13s - loss: 0.5122 - acc: 0.7469 - val_loss: 0.4558 - val_acc: 0.8020 Epoch 53/100 - 13s - loss: 0.5049 - acc: 0.7603 - val_loss: 0.4554 - val_acc: 0.7800 Epoch 54/100 - 13s - loss: 0.5097 - acc: 0.7569 - val_loss: 0.4381 - val_acc: 0.7890 Epoch 55/100 - 15s - loss: 0.5139 - acc: 0.7637 - val_loss: 0.4017 - val_acc: 0.8140 Epoch 56/100 - 13s - loss: 0.5099 - acc: 0.7560 - val_loss: 0.4347 - val_acc: 0.7940 Epoch 57/100 - 13s - loss: 0.4980 - acc: 0.7530 - val_loss: 0.4394 - val_acc: 0.7860 Epoch 58/100 - 13s - loss: 0.5130 - acc: 0.7589 - val_loss: 0.4424 - val_acc: 0.7960 Epoch 59/100 - 13s - loss: 0.4981 - acc: 0.7733 - val_loss: 0.4552 - val_acc: 0.7710 Epoch 60/100 - 13s - loss: 0.4991 - acc: 0.7599 - val_loss: 0.4227 - val_acc: 0.8080 Epoch 61/100 - 15s - loss: 0.4875 - acc: 0.7707 - val_loss: 0.4253 - val_acc: 0.8080 Epoch 62/100 - 13s - loss: 0.4981 - acc: 0.7632 - val_loss: 0.5508 - val_acc: 0.7510 Epoch 63/100 - 13s - loss: 0.5062 - acc: 0.7603 - val_loss: 0.4149 - val_acc: 0.8180 Epoch 64/100 - 13s - loss: 0.5008 - acc: 0.7655 - val_loss: 0.3925 - val_acc: 0.8360 Epoch 65/100 - 14s - loss: 0.4924 - acc: 0.7760 - val_loss: 0.4087 - val_acc: 0.8190 Epoch 66/100 - 13s - loss: 0.4925 - acc: 0.7642 - val_loss: 0.4290 - val_acc: 0.8010 Epoch 67/100 - 15s - loss: 0.4722 - acc: 0.7770 - val_loss: 0.3828 - val_acc: 0.8220 Epoch 68/100 - 14s - loss: 0.5055 - acc: 0.7606 - val_loss: 0.4122 - val_acc: 0.8120 Epoch 69/100 - 13s - loss: 0.4900 - acc: 0.7737 - val_loss: 0.4063 - val_acc: 0.8290 Epoch 70/100 - 13s - loss: 0.4993 - acc: 0.7636 - val_loss: 0.4151 - val_acc: 0.8010 Epoch 71/100 - 13s - loss: 0.5020 - acc: 0.7690 - val_loss: 0.4158 - val_acc: 0.7990 Epoch 72/100 - 13s - loss: 0.4955 - acc: 0.7653 - val_loss: 0.4049 - val_acc: 0.8310 Epoch 73/100 - 14s - loss: 0.4823 - acc: 0.7830 - val_loss: 0.4336 - val_acc: 0.8050 Epoch 74/100 - 13s - loss: 0.4804 - acc: 0.7819 - val_loss: 0.3934 - val_acc: 0.8180 Epoch 75/100 - 13s - loss: 0.5065 - acc: 0.7643 - val_loss: 0.4974 - val_acc: 0.7810 Epoch 76/100 - 13s - loss: 0.4888 - acc: 0.7779 - val_loss: 0.4695 - val_acc: 0.7960 Epoch 77/100 - 13s - loss: 0.4895 - acc: 0.7730 - val_loss: 0.4161 - val_acc: 0.8160 Epoch 78/100 - 13s - loss: 0.4820 - acc: 0.7790 - val_loss: 0.3894 - val_acc: 0.8220 Epoch 79/100 - 14s - loss: 0.4907 - acc: 0.7703 - val_loss: 0.3769 - val_acc: 0.8350 Epoch 80/100 - 13s - loss: 0.4794 - acc: 0.7779 - val_loss: 0.4107 - val_acc: 0.8180 Epoch 81/100 - 13s - loss: 0.4800 - acc: 0.7823 - val_loss: 0.4767 - val_acc: 0.7850 Epoch 82/100 - 13s - loss: 0.4937 - acc: 0.7699 - val_loss: 0.4065 - val_acc: 0.8190 Epoch 83/100 - 13s - loss: 0.4650 - acc: 0.7860 - val_loss: 0.3732 - val_acc: 0.8380 Epoch 84/100 - 13s - loss: 0.4981 - acc: 0.7692 - val_loss: 0.4256 - val_acc: 0.8300 Epoch 85/100 - 14s - loss: 0.5049 - acc: 0.7670 - val_loss: 0.3864 - val_acc: 0.8290 Epoch 86/100 - 13s - loss: 0.4730 - acc: 0.7830 - val_loss: 0.4212 - val_acc: 0.8200 Epoch 87/100 - 13s - loss: 0.4796 - acc: 0.7730 - val_loss: 0.4310 - val_acc: 0.8160 Epoch 88/100 - 14s - loss: 0.4944 - acc: 0.7702 - val_loss: 0.3845 - val_acc: 0.8290 Epoch 89/100 - 13s - loss: 0.4922 - acc: 0.7790 - val_loss: 0.3772 - val_acc: 0.8360 Epoch 90/100 - 13s - loss: 0.4921 - acc: 0.7816 - val_loss: 0.3902 - val_acc: 0.8320 Epoch 91/100 - 15s - loss: 0.4711 - acc: 0.7860 - val_loss: 0.4081 - val_acc: 0.8130 Epoch 92/100 - 13s - loss: 0.5064 - acc: 0.7709 - val_loss: 0.3651 - val_acc: 0.8450 Epoch 93/100 - 13s - loss: 0.4929 - acc: 0.7687 - val_loss: 0.3481 - val_acc: 0.8420 Epoch 94/100 - 13s - loss: 0.4720 - acc: 0.7796 - val_loss: 0.4129 - val_acc: 0.8060 Epoch 95/100 - 13s - loss: 0.4835 - acc: 0.7820 - val_loss: 0.5525 - val_acc: 0.7710 Epoch 96/100 - 13s - loss: 0.4742 - acc: 0.7709 - val_loss: 0.4102 - val_acc: 0.8290 Epoch 97/100 - 15s - loss: 0.4675 - acc: 0.7807 - val_loss: 0.5125 - val_acc: 0.7810 Epoch 98/100 - 13s - loss: 0.4692 - acc: 0.7786 - val_loss: 0.3939 - val_acc: 0.8340 Epoch 99/100 - 13s - loss: 0.4961 - acc: 0.7790 - val_loss: 0.4290 - val_acc: 0.8240 Epoch 100/100 - 13s - loss: 0.4662 - acc: 0.7876 - val_loss: 0.4970 - val_acc: 0.7820 ###Markdown Model Performance ###Code %matplotlib inline import matplotlib.pyplot as plt f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) t = f.suptitle('Basic CNN Performance', fontsize=12) f.subplots_adjust(top=0.85, wspace=0.3) epoch_list = list(range(1,101)) ax1.plot(epoch_list, history.history['acc'], label='Train Accuracy') ax1.plot(epoch_list, history.history['val_acc'], label='Validation Accuracy') ax1.set_xticks(np.arange(0, 101, 5)) ax1.set_ylabel('Accuracy Value') ax1.set_xlabel('Epoch') ax1.set_title('Accuracy') l1 = ax1.legend(loc="best") ax2.plot(epoch_list, history.history['loss'], label='Train Loss') ax2.plot(epoch_list, history.history['val_loss'], label='Validation Loss') ax2.set_xticks(np.arange(0, 101, 5)) ax2.set_ylabel('Loss Value') ax2.set_xlabel('Epoch') ax2.set_title('Loss') l2 = ax2.legend(loc="best") if not os.path.exists('saved_models'): os.mkdir('saved_models') model.save('models/cnn scratch.h5') ###Output _____no_output_____
vae_coordconv.ipynb
###Markdown Variational Autoencoder CoordConv filters ###Code from keras.utils.vis_utils import plot_model from keras_visualizer import visualizer from keras.callbacks import EarlyStopping, TensorBoard from keras.preprocessing.image import ImageDataGenerator import numpy as np import matplotlib.pyplot as plt from autoencoders.VAE import VAECoordConv as VAE DATASET_SIZE = 25084 INPUT_SHAPE = (40, 40, 1) import tensorflow as tf devices = tf.config.list_physical_devices('GPU') if len(devices) < 1: raise Exception("Cannot initialize GPU") print("GPU configured correctly") datagen = ImageDataGenerator( rescale=1./255, validation_split=0.3, horizontal_flip=True, vertical_flip=True ) # Allow horizontal flip and vertical flip as a mirror image in both axes of a game is a valid game state train_datagen = datagen.flow_from_directory( 'images_trans/', target_size=(INPUT_SHAPE[0], INPUT_SHAPE[1]), color_mode='grayscale', class_mode='input', shuffle=True, subset='training' ) val_datagen = datagen.flow_from_directory( 'images_trans/', target_size=(INPUT_SHAPE[0], INPUT_SHAPE[1]), color_mode='grayscale', class_mode='input', shuffle=True, subset='validation' ) vae = VAE( layers=5, latent_size=16, kernel_size=3, input_shape=INPUT_SHAPE, filters=16, name="VAE" ) vae.summary() plot_model(vae.decoder, to_file='coord_dec.png', show_shapes=True) callbacks = [ EarlyStopping(monitor='val_loss', patience=40), TensorBoard( log_dir='./logs', histogram_freq=1 ) ] history = vae.train( train_datagen, val_datagen, epochs=75, callbacks=callbacks ) val_rec_loss = history.history['val_reconstruction_loss'] rec_loss = history.history['reconstruction_loss'] epochs = range(1, len(val_rec_loss) + 1) plt.figure(figsize=(8,6), dpi=80) plt.plot(epochs, val_rec_loss, 'r', label='Val Reconstruction loss') plt.plot(epochs, rec_loss, 'b', label='Reconstruction loss') plt.title('CoordConv training') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array import random n = 10 images = np.empty((n, *INPUT_SHAPE)) for i in range(n): rand_img = random.randint(0, DATASET_SIZE) img = img_to_array(load_img(f"images_trans/pong_trans_{rand_img}.png", color_mode='grayscale')) images[i] = img decoded_imgs = vae.predict(images) latent = vae.encoder.predict(images) #print(latent[:][2]) decoded_imgs = vae.decoder.predict(latent[:][2]) plt.figure(figsize=(20, 4)) for i in range(1, n+1): # Display original ax = plt.subplot(2, n, i) plt.imshow(images[i-1].reshape(INPUT_SHAPE[0], INPUT_SHAPE[1])) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # Display reconstruction ax = plt.subplot(2, n, i + n) plt.imshow(decoded_imgs[i-1].reshape(INPUT_SHAPE[0], INPUT_SHAPE[1])) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() import random def plot_latent_space(vae, n=15, figsize=25): # display a n*n 2D manifold of digits x_input_size = INPUT_SHAPE[0] y_input_size = INPUT_SHAPE[1] scale = 100.0 figure = np.zeros((x_input_size * n + n - 1, y_input_size * n + n - 1)) # linearly spaced coordinates corresponding to the 2D plot # of digit classes in the latent space grid_x = np.linspace(-scale, scale, n) grid_y = np.linspace(-scale, scale, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): rest = rest = [i * 10 for i in range(-7, 7)] # missing = -2.9679005e+00, -1.7151514e+01 z_sample = np.array([[xi, yi] + rest]) #z_sample = np.array([[random.randint(-scale, scale) for i in range(16)]]) x_decoded = vae.decoder.predict(z_sample) digit = x_decoded[0].reshape(x_input_size, y_input_size) figure[ i * x_input_size + i: (i + 1) * x_input_size + i, j * y_input_size + j: (j + 1) * y_input_size + j, ] = digit if i != len(grid_x) - 1: figure[ (i + 1) * x_input_size + i, j * y_input_size + j: (j + 1) * y_input_size + j, ] = np.array([1] * y_input_size) if j != len(grid_y) - 1: figure[ i * x_input_size + i: (i + 1) * x_input_size + i, (j + 1) * y_input_size + j, ] = np.array([1] * x_input_size) plt.figure(figsize=(figsize, figsize)) plt.imshow(figure, cmap="Greys_r") plt.show() plot_latent_space(vae) ###Output _____no_output_____
Issues/algorithms/Bit Manipulation.ipynb
###Markdown 5.1 Insertion:You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a methodto insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j throughi have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fullyfit between bit 3 and bit 2. ###Code bit = 0xFFFF M = 0x5 N = 0xF00F def insertion(M, N, i, j): ALL = 0xFFFFFFFF left_mask = ALL << j + 1 print(bin(ALL)) print("left_mask:" + bin(left_mask)) right_mask = ALL >> (32 - i) mask = left_mask|right_mask print(bin(mask)) M_ = (M << i) ret = (N&mask) | M_ print(bin(M_)) print(bin(ret)) return ret print(bin(insertion(M, N, 3, 5))) ###Output 0b11111111111111111111111111111111 left_mask:0b11111111111111111111111111111111000000 0b11111111111111111111111111111111000111 0b101000 0b1111000000101111 0b1111000000101111 ###Markdown 5.2 Binary to String: Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print"ERROR:' ###Code def bin_to_str(number): strs = [] remain = number for i in range(1, 31): if remain == 0: break elif remain - 0.5**i >= 0: remain = remain - 0.5**i strs.append(str(1)) else: strs.append(str(0)) print(remain, 0.5**i) if remain > 0: return "ERROR" else: return "0." + "".join(strs) print(bin_to_str(0.875)) ###Output 0.375 0.5 0.125 0.25 0.0 0.125 0.111
_notebooks/2022-03-15-Assignment07.ipynb
###Markdown "Stats & Modeling with Romeo and Juliet"> "This is assignment 7 from DH 140 with Professor Benjamin Winjum at UCLA for Winter Quarter 2022. It employs methods to run analysis on the play and output some exploratory analysis. The second part of the assignment look at a test dataset to introduce how to employ a Linear Regression model using the dataframes provided and ways to select a good feature for model training."- toc:true- branch: master- badges: true- comments: true- author: Anh Mac- categories: [fastpages, jupyter, Shakespeare, machinelearning] Shakespeare play from Week 6- Tokenize the words, remove stopwords, stem or lemmatize the words, and calculate the word frequencies- For the word frequencies, calculate the mean, median, mode, and trimmed mean.- For the trimmed mean, you can choose what to trim, but comment on the number used for trimming.- Plot a histogram of the word frequency data and comment on the relative locations of the mean, median, mode, and trimmed mean- Calculate the standard deviation and the interquartile range (the difference of the 75% and 25% quantile)- Comment as well on how they compare to each other and to the histogram plot. ###Code #hide import nltk from nltk.tokenize import word_tokenize, sent_tokenize nltk.download('punkt') # Read the file that contains text of Romeo and Julie f = open("romeo-and-juliet.txt", "r") text = f.read() ###Output _____no_output_____ ###Markdown Tokenize words ###Code # Tokenize the words sent = sent_tokenize(text) print(word_tokenize(sent[1])) words = [] for s in sent: for w in word_tokenize(s): words.append(w) ###Output _____no_output_____ ###Markdown Remove stopwords ###Code # remove stopwords from nltk.corpus import stopwords from string import punctuation nltk.download('stopwords') myStopWords = list(punctuation) + stopwords.words('english') + ['’'] wordsNoStop = [w for w in words if w not in myStopWords] ###Output _____no_output_____ ###Markdown Stem the words ###Code #hide from nltk.stem.lancaster import LancasterStemmer wordLancasterStems = [LancasterStemmer().stem(w) for w in wordsNoStop] ###Output _____no_output_____ ###Markdown Calculate frequencies ###Code #hide import collections wordCount = collections.Counter(wordLancasterStems) frequencies = wordCount.most_common() frequencies[0:5] ###Output _____no_output_____ ###Markdown Calculate mean/median/mode/trimmed mean ###Code import pandas as pd df = pd.DataFrame(frequencies, columns=["text", "frequency"]) #collapse-hide print("MEAN: ", df["frequency"].mean()) print("MEDIAN:", df["frequency"].median()) print("MODE: ", df["frequency"].mode()) df2 = df.sort_values(by="frequency",ignore_index=True).copy() df2 ###Output _____no_output_____ ###Markdown I chose to trim 20% of the data since the outliers look like it's only the higher numbers like 314 and 647, and there also seems to be a lot of 1's, so remove some would not skewed our data too much. I mostly want to remove the higher outliers. ###Code print("TRIMMED MEAN:", df2.loc[int(0.2*3053):int(0.8*3053),'frequency'].mean()) ###Output TRIMMED MEAN: 2.0845608292416804 ###Markdown Histogram ###Code df["frequency"].plot.hist(title='Words frequencies in Romeo & Juliet') ###Output _____no_output_____ ###Markdown **Comment on histogram:**- Most of the values are 1, so the Mode being 1 makes sense.- Median of 2 also makes sense as most of the data seems to be between 0-50, and as we can see from a preview of the dataframe that most of these numbers would be between 1-2, and the middle number should be around there as well.- The original mean of 6.188932547478716 seems a bit high when looking at the distribution, so our trimmed mean of 2.0845608292416804 seems to make more sense with the outliers above 300 removed. Standard Deviation & Interquartile range ###Code print("STD: ", df["frequency"].std()) df["frequency"].quantile(0.75) - df["frequency"].quantile(0.25) ###Output _____no_output_____ ###Markdown **Comment on std and interquartile range:**- The STD of 19.957504689286747 makes sense considering our small Mode, Median, and larger outliers to the right. The standard deviation calculates the distance between every data point so the large outliers skewed this number to be larger.- The interquartile range of 3.0 also makes sense as our most of our data has smaller frequency, and the plot is heavily skewed left, so the interquartile range signifies that most of our data are close together in distance. The interquartile range calculate the distance between the 50% middle data points, so in terms of the distribution of our histogram, this value makes sense. Foray into machine learning- Import scikit-learn's example diabetes dataset as a Panda's dataframe with the following code:from sklearn import datasetsdf = datasets.load_diabetes(as_frame=True) features_df = df.datatarget_df = df.target- Use the following code to view a description of the dataset:print(df.DESCR)- Do some exploratory data analysis of the features, including getting summary statistical information- Find the column in features_df that has the highest correlation coefficient with the target values in target_df- Make a scatter plot of the target values vs this feature column's values and comment on how the plotted points match up with the correlation coefficient- Using this feature and target, perform linear regression with sklearn's LinearRegression- Print the coefficients of the model- Plot the linear fit on top of the scatter plot- Calculate (or output) the mean squared error and R-squared values for your fit- Try doing linear regression with another variable and check how the new fit's mean squared error and R-squared values change. ###Code from sklearn import datasets df = datasets.load_diabetes(as_frame=True) features_df = df.data target_df = df.target print(df.DESCR) ###Output .. _diabetes_dataset: Diabetes dataset ---------------- Ten baseline variables, age, sex, body mass index, average blood pressure, and six blood serum measurements were obtained for each of n = 442 diabetes patients, as well as the response of interest, a quantitative measure of disease progression one year after baseline. **Data Set Characteristics:** :Number of Instances: 442 :Number of Attributes: First 10 columns are numeric predictive values :Target: Column 11 is a quantitative measure of disease progression one year after baseline :Attribute Information: - age age in years - sex - bmi body mass index - bp average blood pressure - s1 tc, total serum cholesterol - s2 ldl, low-density lipoproteins - s3 hdl, high-density lipoproteins - s4 tch, total cholesterol / HDL - s5 ltg, possibly log of serum triglycerides level - s6 glu, blood sugar level Note: Each of these 10 feature variables have been mean centered and scaled by the standard deviation times `n_samples` (i.e. the sum of squares of each column totals 1). Source URL: https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html For more information see: Bradley Efron, Trevor Hastie, Iain Johnstone and Robert Tibshirani (2004) "Least Angle Regression," Annals of Statistics (with discussion), 407-499. (https://web.stanford.edu/~hastie/Papers/LARS/LeastAngle_2002.pdf) ###Markdown Exploratory Data Analysis ###Code features_df.describe() features_df[features_df.columns[:]].hist(figsize=(20, 20)) ###Output _____no_output_____ ###Markdown Find column with highest correlation ###Code col=list(features_df.columns) df2=features_df.copy() df2["target"] = list(target_df.values) for c in col: print(df2[[c,'target']].corr()) ###Output age target age 1.000000 0.187889 target 0.187889 1.000000 sex target sex 1.000000 0.043062 target 0.043062 1.000000 bmi target bmi 1.00000 0.58645 target 0.58645 1.00000 bp target bp 1.000000 0.441484 target 0.441484 1.000000 s1 target s1 1.000000 0.212022 target 0.212022 1.000000 s2 target s2 1.000000 0.174054 target 0.174054 1.000000 s3 target s3 1.000000 -0.394789 target -0.394789 1.000000 s4 target s4 1.000000 0.430453 target 0.430453 1.000000 s5 target s5 1.000000 0.565883 target 0.565883 1.000000 s6 target s6 1.000000 0.382483 target 0.382483 1.000000 ###Markdown Column with highest correlation to **target_df** is **bmi**. Scatter plot ###Code df2.plot.scatter(y='target',x='bmi') ###Output _____no_output_____ ###Markdown **Comment on scatter plot:**- The plotted points does show somewhat of a linear trend upward that matches up with the correlation coefficient.- We can vaguely observe a diagonal line through the points Linear Regression ###Code import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score X = np.array(df2['bmi']) y = np.array(df2['target']) reg = LinearRegression().fit(X.reshape(-1, 1), y) ###Output _____no_output_____ ###Markdown Coefficient ###Code coef = reg.coef_ coef ###Output _____no_output_____ ###Markdown Linear fit ###Code ytrain = reg.intercept_ + reg.coef_ * X plt.plot(X,y,'ro',X,ytrain,'b-'); ###Output _____no_output_____ ###Markdown Calculate Mean-Squared-Error and R^2 ###Code mean_squared_error(y, ytrain) r2_score(y, ytrain) ###Output _____no_output_____ ###Markdown Linear Regression with s5 ###Code df2.plot.scatter(y='target',x='s5') X = np.array(df2['s5']) y = np.array(df2['target']) reg = LinearRegression().fit(X.reshape(-1, 1), y) ytrain = reg.intercept_ + reg.coef_ * X plt.plot(X,y,'ro',X,ytrain,'b-'); mean_squared_error(y, ytrain) r2_score(y, ytrain) ###Output _____no_output_____
example/03_peak-search/peak-search-python.ipynb
###Markdown How to find peaks of impedance curve It is quite easy using scipy.signal . ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt # module to do peak search from scipy.signal import argrelextrema # read data dd = pd.read_csv('side-hole.imp',header=0) ###Output _____no_output_____ ###Markdown This impedance curve is a weird to do peak search due to side-hole. ###Code p1 = dd.plot(x = 'freq', y = 'imp.mag') ###Output _____no_output_____ ###Markdown Pick up ndarray from dataframe to use argrelextrema. ###Code y = dd.iloc[:,3].values type(y) ###Output _____no_output_____ ###Markdown Find peaks location. Easy. ###Code idx = argrelextrema(y, np.greater); idx y[idx] x = dd.iloc[:,0].values x[idx] ###Output _____no_output_____ ###Markdown To super impose peaks, using normal matplot function is better. ###Code plt.scatter(x[idx],y[idx],color='r') plt.plot(x,y) ###Output _____no_output_____ ###Markdown In case of searching local minima, use np.less. ###Code i2 = argrelextrema(y,np.less) x2 = x[i2] y2 = y[i2] plt.plot(x,y) plt.scatter(x2,y2,s = 50,color = 'green', marker = '+') ###Output _____no_output_____
experiments/baseline_ptn_32bit/oracle.run1/trials/0/trial.ipynb
###Markdown PTN TemplateThis notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get started with that workflow. ###Code %load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network from steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper from steves_utils.iterable_aggregator import Iterable_Aggregator from steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig from steves_utils.torch_sequential_builder import build_sequential from steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader from steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path) from steves_utils.PTN.utils import independent_accuracy_assesment from steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory from steves_utils.ptn_do_report import ( get_loss_curve, get_results_table, get_parameters_table, get_domain_accuracies, ) from steves_utils.transforms import get_chained_transform ###Output _____no_output_____ ###Markdown Required ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean ###Code required_parameters = { "experiment_name", "lr", "device", "seed", "dataset_seed", "labels_source", "labels_target", "domains_source", "domains_target", "num_examples_per_domain_per_label_source", "num_examples_per_domain_per_label_target", "n_shot", "n_way", "n_query", "train_k_factor", "val_k_factor", "test_k_factor", "n_epoch", "patience", "criteria_for_best", "x_transforms_source", "x_transforms_target", "episode_transforms_source", "episode_transforms_target", "pickle_name", "x_net", "NUM_LOGS_PER_EPOCH", "BEST_MODEL_PATH", "torch_default_dtype" } standalone_parameters = {} standalone_parameters["experiment_name"] = "STANDALONE PTN" standalone_parameters["lr"] = 0.0001 standalone_parameters["device"] = "cuda" standalone_parameters["seed"] = 1337 standalone_parameters["dataset_seed"] = 1337 standalone_parameters["num_examples_per_domain_per_label_source"]=100 standalone_parameters["num_examples_per_domain_per_label_target"]=100 standalone_parameters["n_shot"] = 3 standalone_parameters["n_query"] = 2 standalone_parameters["train_k_factor"] = 1 standalone_parameters["val_k_factor"] = 2 standalone_parameters["test_k_factor"] = 2 standalone_parameters["n_epoch"] = 100 standalone_parameters["patience"] = 10 standalone_parameters["criteria_for_best"] = "target_accuracy" standalone_parameters["x_transforms_source"] = ["unit_power"] standalone_parameters["x_transforms_target"] = ["unit_power"] standalone_parameters["episode_transforms_source"] = [] standalone_parameters["episode_transforms_target"] = [] standalone_parameters["torch_default_dtype"] = "torch.float32" standalone_parameters["x_net"] = [ {"class": "nnReshape", "kargs": {"shape":[-1, 1, 2, 256]}}, {"class": "Conv2d", "kargs": { "in_channels":1, "out_channels":256, "kernel_size":(1,7), "bias":False, "padding":(0,3), },}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features":256}}, {"class": "Conv2d", "kargs": { "in_channels":256, "out_channels":80, "kernel_size":(2,7), "bias":True, "padding":(0,3), },}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features":80}}, {"class": "Flatten", "kargs": {}}, {"class": "Linear", "kargs": {"in_features": 80*256, "out_features": 256}}, # 80 units per IQ pair {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm1d", "kargs": {"num_features":256}}, {"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}}, ] # Parameters relevant to results # These parameters will basically never need to change standalone_parameters["NUM_LOGS_PER_EPOCH"] = 10 standalone_parameters["BEST_MODEL_PATH"] = "./best_model.pth" # uncomment for CORES dataset from steves_utils.CORES.utils import ( ALL_NODES, ALL_NODES_MINIMUM_1000_EXAMPLES, ALL_DAYS ) standalone_parameters["labels_source"] = ALL_NODES standalone_parameters["labels_target"] = ALL_NODES standalone_parameters["domains_source"] = [1] standalone_parameters["domains_target"] = [2,3,4,5] standalone_parameters["pickle_name"] = "cores.stratified_ds.2022A.pkl" # Uncomment these for ORACLE dataset # from steves_utils.ORACLE.utils_v2 import ( # ALL_DISTANCES_FEET, # ALL_RUNS, # ALL_SERIAL_NUMBERS, # ) # standalone_parameters["labels_source"] = ALL_SERIAL_NUMBERS # standalone_parameters["labels_target"] = ALL_SERIAL_NUMBERS # standalone_parameters["domains_source"] = [8,20, 38,50] # standalone_parameters["domains_target"] = [14, 26, 32, 44, 56] # standalone_parameters["pickle_name"] = "oracle.frame_indexed.stratified_ds.2022A.pkl" # standalone_parameters["num_examples_per_domain_per_label_source"]=1000 # standalone_parameters["num_examples_per_domain_per_label_target"]=1000 # Uncomment these for Metahan dataset # standalone_parameters["labels_source"] = list(range(19)) # standalone_parameters["labels_target"] = list(range(19)) # standalone_parameters["domains_source"] = [0] # standalone_parameters["domains_target"] = [1] # standalone_parameters["pickle_name"] = "metehan.stratified_ds.2022A.pkl" # standalone_parameters["n_way"] = len(standalone_parameters["labels_source"]) # standalone_parameters["num_examples_per_domain_per_label_source"]=200 # standalone_parameters["num_examples_per_domain_per_label_target"]=100 standalone_parameters["n_way"] = len(standalone_parameters["labels_source"]) # Parameters parameters = { "experiment_name": "baseline_ptn_32bit_oracle.run1", "lr": 0.001, "device": "cuda", "seed": 1337, "dataset_seed": 1337, "labels_source": [ "3123D52", "3123D65", "3123D79", "3123D80", "3123D54", "3123D70", "3123D7B", "3123D89", "3123D58", "3123D76", "3123D7D", "3123EFE", "3123D64", "3123D78", "3123D7E", "3124E4A", ], "labels_target": [ "3123D52", "3123D65", "3123D79", "3123D80", "3123D54", "3123D70", "3123D7B", "3123D89", "3123D58", "3123D76", "3123D7D", "3123EFE", "3123D64", "3123D78", "3123D7E", "3124E4A", ], "x_transforms_source": [], "x_transforms_target": [], "episode_transforms_source": [], "episode_transforms_target": [], "num_examples_per_domain_per_label_source": 1000, "num_examples_per_domain_per_label_target": 1000, "n_shot": 3, "n_way": 16, "n_query": 2, "train_k_factor": 1, "val_k_factor": 2, "test_k_factor": 2, "torch_default_dtype": "torch.float32", "n_epoch": 50, "patience": 3, "criteria_for_best": "target_loss", "x_net": [ {"class": "nnReshape", "kargs": {"shape": [-1, 1, 2, 256]}}, { "class": "Conv2d", "kargs": { "in_channels": 1, "out_channels": 256, "kernel_size": [1, 7], "bias": False, "padding": [0, 3], }, }, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features": 256}}, { "class": "Conv2d", "kargs": { "in_channels": 256, "out_channels": 80, "kernel_size": [2, 7], "bias": True, "padding": [0, 3], }, }, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm2d", "kargs": {"num_features": 80}}, {"class": "Flatten", "kargs": {}}, {"class": "Linear", "kargs": {"in_features": 20480, "out_features": 256}}, {"class": "ReLU", "kargs": {"inplace": True}}, {"class": "BatchNorm1d", "kargs": {"num_features": 256}}, {"class": "Linear", "kargs": {"in_features": 256, "out_features": 256}}, ], "NUM_LOGS_PER_EPOCH": 10, "BEST_MODEL_PATH": "./best_model.pth", "pickle_name": "oracle.Run1_10kExamples_stratified_ds.2022A.pkl", "domains_source": [8, 32, 50], "domains_target": [14, 20, 26, 38, 44], } # Set this to True if you want to run this template directly STANDALONE = False if STANDALONE: print("parameters not injected, running with standalone_parameters") parameters = standalone_parameters if not 'parameters' in locals() and not 'parameters' in globals(): raise Exception("Parameter injection failed") #Use an easy dict for all the parameters p = EasyDict(parameters) supplied_keys = set(p.keys()) if supplied_keys != required_parameters: print("Parameters are incorrect") if len(supplied_keys - required_parameters)>0: print("Shouldn't have:", str(supplied_keys - required_parameters)) if len(required_parameters - supplied_keys)>0: print("Need to have:", str(required_parameters - supplied_keys)) raise RuntimeError("Parameters are incorrect") ################################### # Set the RNGs and make it all deterministic ################################### np.random.seed(p.seed) random.seed(p.seed) torch.manual_seed(p.seed) torch.use_deterministic_algorithms(True) ########################################### # The stratified datasets honor this ########################################### torch.set_default_dtype(eval(p.torch_default_dtype)) ################################### # Build the network(s) # Note: It's critical to do this AFTER setting the RNG # (This is due to the randomized initial weights) ################################### x_net = build_sequential(p.x_net) start_time_secs = time.time() ################################### # Build the dataset ################################### if p.x_transforms_source == []: x_transform_source = None else: x_transform_source = get_chained_transform(p.x_transforms_source) if p.x_transforms_target == []: x_transform_target = None else: x_transform_target = get_chained_transform(p.x_transforms_target) if p.episode_transforms_source == []: episode_transform_source = None else: raise Exception("episode_transform_source not implemented") if p.episode_transforms_target == []: episode_transform_target = None else: raise Exception("episode_transform_target not implemented") eaf_source = Episodic_Accessor_Factory( labels=p.labels_source, domains=p.domains_source, num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_source, iterator_seed=p.seed, dataset_seed=p.dataset_seed, n_shot=p.n_shot, n_way=p.n_way, n_query=p.n_query, train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor), pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name), x_transform_func=x_transform_source, example_transform_func=episode_transform_source, ) train_original_source, val_original_source, test_original_source = eaf_source.get_train(), eaf_source.get_val(), eaf_source.get_test() eaf_target = Episodic_Accessor_Factory( labels=p.labels_target, domains=p.domains_target, num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_target, iterator_seed=p.seed, dataset_seed=p.dataset_seed, n_shot=p.n_shot, n_way=p.n_way, n_query=p.n_query, train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor), pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name), x_transform_func=x_transform_target, example_transform_func=episode_transform_target, ) train_original_target, val_original_target, test_original_target = eaf_target.get_train(), eaf_target.get_val(), eaf_target.get_test() transform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only train_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda) val_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda) test_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda) train_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda) val_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda) test_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda) datasets = EasyDict({ "source": { "original": {"train":train_original_source, "val":val_original_source, "test":test_original_source}, "processed": {"train":train_processed_source, "val":val_processed_source, "test":test_processed_source} }, "target": { "original": {"train":train_original_target, "val":val_original_target, "test":test_original_target}, "processed": {"train":train_processed_target, "val":val_processed_target, "test":test_processed_target} }, }) # Some quick unit tests on the data from steves_utils.transforms import get_average_power, get_average_magnitude q_x, q_y, s_x, s_y, truth = next(iter(train_processed_source)) assert q_x.dtype == eval(p.torch_default_dtype) assert s_x.dtype == eval(p.torch_default_dtype) print("Visually inspect these to see if they line up with expected values given the transforms") print('x_transforms_source', p.x_transforms_source) print('x_transforms_target', p.x_transforms_target) print("Average magnitude, source:", get_average_magnitude(q_x[0].numpy())) print("Average power, source:", get_average_power(q_x[0].numpy())) q_x, q_y, s_x, s_y, truth = next(iter(train_processed_target)) print("Average magnitude, target:", get_average_magnitude(q_x[0].numpy())) print("Average power, target:", get_average_power(q_x[0].numpy())) ################################### # Build the model ################################### model = Steves_Prototypical_Network(x_net, device=p.device, x_shape=(2,256)) optimizer = Adam(params=model.parameters(), lr=p.lr) ################################### # train ################################### jig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device) jig.train( train_iterable=datasets.source.processed.train, source_val_iterable=datasets.source.processed.val, target_val_iterable=datasets.target.processed.val, num_epochs=p.n_epoch, num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH, patience=p.patience, optimizer=optimizer, criteria_for_best=p.criteria_for_best, ) total_experiment_time_secs = time.time() - start_time_secs ################################### # Evaluate the model ################################### source_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test) target_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test) source_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val) target_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val) history = jig.get_history() total_epochs_trained = len(history["epoch_indices"]) val_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val)) confusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl) per_domain_accuracy = per_domain_accuracy_from_confusion(confusion) # Add a key to per_domain_accuracy for if it was a source domain for domain, accuracy in per_domain_accuracy.items(): per_domain_accuracy[domain] = { "accuracy": accuracy, "source?": domain in p.domains_source } # Do an independent accuracy assesment JUST TO BE SURE! # _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device) # _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device) # _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device) # _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device) # assert(_source_test_label_accuracy == source_test_label_accuracy) # assert(_target_test_label_accuracy == target_test_label_accuracy) # assert(_source_val_label_accuracy == source_val_label_accuracy) # assert(_target_val_label_accuracy == target_val_label_accuracy) experiment = { "experiment_name": p.experiment_name, "parameters": dict(p), "results": { "source_test_label_accuracy": source_test_label_accuracy, "source_test_label_loss": source_test_label_loss, "target_test_label_accuracy": target_test_label_accuracy, "target_test_label_loss": target_test_label_loss, "source_val_label_accuracy": source_val_label_accuracy, "source_val_label_loss": source_val_label_loss, "target_val_label_accuracy": target_val_label_accuracy, "target_val_label_loss": target_val_label_loss, "total_epochs_trained": total_epochs_trained, "total_experiment_time_secs": total_experiment_time_secs, "confusion": confusion, "per_domain_accuracy": per_domain_accuracy, }, "history": history, "dataset_metrics": get_dataset_metrics(datasets, "ptn"), } ax = get_loss_curve(experiment) plt.show() get_results_table(experiment) get_domain_accuracies(experiment) print("Source Test Label Accuracy:", experiment["results"]["source_test_label_accuracy"], "Target Test Label Accuracy:", experiment["results"]["target_test_label_accuracy"]) print("Source Val Label Accuracy:", experiment["results"]["source_val_label_accuracy"], "Target Val Label Accuracy:", experiment["results"]["target_val_label_accuracy"]) json.dumps(experiment) ###Output _____no_output_____
MNIST_neuralnetworks.ipynb
###Markdown Intro to Pattern Recognition Problem Set 4: Neural Networks M S Mohamed Fazil UB Id : mm549 IntroductionWe will be using neural networks to build a model that classifies hand written digits using thr MNIST database. The MNIST database (Modified National Institute of Standards and Technology Database) is a large collection of handwritten digits which happens to be a state of the art data set to train and test machine learning models using image processing.It consist of 60000 Training samples and 10000 Testing Samples. Each sample image consist of normalized $28X28$ pixels grayscale image stored as 784 dimensional vector for each sample.This is a way of dimension reduction done by the MNIST to use it for model developments. Libraries UsedFor loading the given MNIST datasets we will be using the mnist library to fetch the data.The MNIST() function will be used to fetch the datasets from the directory './data'. For the purpose of building neural networks and trainning we will be using Keras library which is backed by the Tensorflow. We will use OpenCv for the image processing applications. ###Code from keras.models import Sequential from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Dropout, Flatten from keras.callbacks import LambdaCallback,ModelCheckpoint from keras.utils import to_categorical from keras import optimizers,regularizers import numpy as np import cv2 import os from mnist.loader import MNIST import matplotlib.pyplot as plt import matplotlib.image as mpimg import random as rd os.environ["CUDA_VISIBLE_DEVICES"]="1" %matplotlib inline m = MNIST('./data') ###Output Using TensorFlow backend. ###Markdown 1. Neural Network to Maximize the log Likehood Minimization of Negative Log Likehood with Softmax Output LayerSoftmax is an activation function of a node which is commonly placed as the output layer of a Neural Network. It is mostly used in multiclass classification problems. The Function is defined as \begin{equation}S(V_i) = \frac{e^{V_i}}{\sum_je^{V_i}}\\end{equation}The softmax function squashes the input vector values between 0 to 1 and because of the normalization of exponential , the sum of the values in the vector tends to be 1. The output values of a Softmax function can be interpretted as a probabilities of the different labels present in the multiclass.In our case the Softmax outputs a vector of 10 values corresponding to the class labels.Negative Log-Likehood is a loss function (aka criterion function) which is used with the Softmax activation function to minimize the criterion function. It is given as \begin{equation}J_0 = -log\,p(D;w) = -log\,p(\{(x_n,t_n):n=1,2,4,...\};w)\end{equation}\begin{equation}J_0 =-log\prod_n\prod_{m=0}^9p(t_n=m|x_n;w)\end{equation}To minimize the criterion function we must differentiate the softmax function with respect to the Negative Log Likehood function. Neural Network to Maximize the Posterior Likehood by Minimizing Criterion Function with L2 RegularizationLet us assume that a Gaussion Prior of the weight distribution is given with the $\alpha$.\begin{equation}p(w;\alpha)=N(N,\alpha l)\end{equation}Regularization is used to avoid overfitting of the traning datasets into the model.Therefore depending on the gradient of the weights between the epochs a part of the weights is subtracted by the regularization component determined with the regularization parameter $\alpha$. The Gaussian Prior function can be used in par with the L2 regularization during the minimization of the Criterion function which will maximize the Posterior Likehood. The combined loss function can be given as \begin{equation}J(w) = J_0(w)-log\,p(w;\alpha^{-1})\end{equation} Preparing the DatasetsWe prepare a dataset which will consist of 1000 training samples with labels where 100 images for each digit and another 1000 testing samples with label where 100 images for each digit. The target consist of a class with ten classification labels. ###Code classes = [0,1,2,3,4,5,6,7,8,9] xtrain,ytrain = m.load_training() xtest,ytest = m.load_testing() # Divide the given datasets to 1000 training dataset and 1000 testing dataset xtrain = xtrain[0:1000] ytrain = ytrain[0:1000] xtest = xtest[0:1000] ytest = ytest[0:1000] xtrain = np.asarray(xtrain).astype(np.float32) ytrain = np.asarray(ytrain).astype(np.float32) xtest = np.asarray(xtest).astype(np.float32) ytest = np.asarray(ytest).astype(np.float32) n_classes = len(classes) #0-1 Hot encoding label_train = np.zeros((ytrain.shape[0], n_classes)) a = np.arange(ytrain.shape[0], dtype=np.int64) b = np.array(ytrain, dtype=np.int64).reshape((ytrain.shape[0],)) label_train[a, b] = 1 label_test = np.zeros((ytest.shape[0], n_classes)) c = np.arange(ytest.shape[0], dtype=np.int64) d = np.array(ytest, dtype=np.int64).reshape((ytest.shape[0],)) label_test[c, d] = 1 ###Output _____no_output_____ ###Markdown Function to Plot the Results of a Training ModelThis fuction plots the Traing and Testing's loss,criterion function, accuracy and the learning speed of each hidden layer with respect to each epoch during training phase. The learning Speed is the measure of the speed of change of weights after every epoch. ###Code def plot_model_result(history,weights,final_w): plt.plot(history.history['loss'], label='Training data') plt.plot(history.history['val_loss'], label='Testing data') plt.legend(['train', 'test'], loc='upper left') plt.title('Loss of Training and Testing Data (Criterion Function)') plt.ylabel('MAE value') plt.xlabel('No. epoch') plt.show() plt.plot(history.history['accuracy'], label='Training data') plt.plot(history.history['val_accuracy'], label='Testing data') plt.legend(['train', 'test'], loc='upper left') plt.title('Accuracy of Training and Testing Data') plt.ylabel('Accuracy value') plt.xlabel('No. epoch') plt.show() cnt = 0 ''' Plot the Learning Speed of the Model ''' np.seterr(divide='ignore', invalid='ignore') for i in range(0,len(weights)): w = weights[i] W = final_w[i] learning_speed = [0] for i in range(1,len(w)): wold = w[i-1] wnew = w[i] diff = wold-wnew d = wnew m = np.median(d[d>0]) d[d==0] = m diff = abs(diff)/d if diff.size: avg = abs(np.mean(diff)) else: avg = 0 learning_speed.append(avg) plt.plot(learning_speed, label='Learning Speed') cnt = cnt+1 plt.title('Learning Speed of Hidden Layer {}'.format(cnt)) plt.ylabel('Learning Speed') plt.xlabel('No. epoch') plt.show() print('Training Accuracy -',history.history['accuracy'][29]) print('Training Loss -',history.history['loss'][29]) print('Testing Accuracy -',history.history['val_accuracy'][29]) print('Testing Loss -',history.history['val_loss'][29]) ###Output _____no_output_____ ###Markdown 2(a). Neural Network with 1 Hidden Layer without regularization ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1])) model.add(Dense(10, activation='softmax')) weights = [] save_weights = LambdaCallback(on_epoch_end=lambda batch, logs: weights.append(model.layers[0].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights]) final_w = [model.layers[0].get_weights()[0]] weights = [weights] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 2(b). Neural Network with 2 Hidden Layer and 3 Hidden Layer 2 Hidden Layer without Regularization ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1])) model.add(Dense(30, activation='sigmoid')) model.add(Dense(10, activation='softmax')) weights1 = [] weights2 = [] save_weights1 = LambdaCallback(on_epoch_end=lambda batch, logs: weights1.append(model.layers[0].get_weights()[0])) save_weights2 = LambdaCallback(on_epoch_end=lambda batch, logs: weights2.append(model.layers[1].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights1,save_weights2]) final_w = [model.layers[0].get_weights()[0],model.layers[1].get_weights()[0]] weights = [weights1,weights2] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 3 Hidden Layer Without Regularization ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1])) model.add(Dense(30, activation='sigmoid')) model.add(Dense(30, activation='sigmoid')) model.add(Dense(10, activation='softmax')) weights1 = [] weights2 = [] weights3 = [] save_weights1 = LambdaCallback(on_epoch_end=lambda batch, logs: weights1.append(model.layers[0].get_weights()[0])) save_weights2 = LambdaCallback(on_epoch_end=lambda batch, logs: weights2.append(model.layers[1].get_weights()[0])) save_weights3 = LambdaCallback(on_epoch_end=lambda batch, logs: weights3.append(model.layers[1].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights1,save_weights2,save_weights3]) final_w = [model.layers[0].get_weights()[0],model.layers[1].get_weights()[0],model.layers[2].get_weights()[0]] weights = [weights1,weights2,weights3] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 1 Hidden layer with Regularization - l2(5) ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1], kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(10, activation='softmax', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) weights = [] save_weights = LambdaCallback(on_epoch_end=lambda batch, logs: weights.append(model.layers[0].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights]) final_w = [model.layers[0].get_weights()[0]] weights = [weights] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 2 Hidden Layer with Regularization - l2(5) ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1], kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(30, activation='sigmoid', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(10, activation='softmax', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) weights1 = [] weights2 = [] save_weights1 = LambdaCallback(on_epoch_end=lambda batch, logs: weights1.append(model.layers[0].get_weights()[0])) save_weights2 = LambdaCallback(on_epoch_end=lambda batch, logs: weights2.append(model.layers[1].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights1,save_weights2]) final_w = [model.layers[0].get_weights()[0],model.layers[1].get_weights()[0]] weights = [weights1,weights2] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 3 Hidden Layer with Regularization - l2(5) ###Code model = Sequential() model.add(Dense(30, activation='sigmoid', input_dim=xtrain.shape[1], kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(30, activation='sigmoid', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(30, activation='sigmoid', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) model.add(Dense(10, activation='softmax', kernel_regularizer=regularizers.l2(5), bias_regularizer=regularizers.l2(5))) weights1 = [] weights2 = [] weights3 = [] save_weights1 = LambdaCallback(on_epoch_end=lambda batch, logs: weights1.append(model.layers[0].get_weights()[0])) save_weights2 = LambdaCallback(on_epoch_end=lambda batch, logs: weights2.append(model.layers[1].get_weights()[0])) save_weights3 = LambdaCallback(on_epoch_end=lambda batch, logs: weights3.append(model.layers[1].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(xtrain, label_train,validation_data=(xtest, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights1,save_weights2,save_weights3]) final_w = [model.layers[0].get_weights()[0],model.layers[1].get_weights()[0],model.layers[2].get_weights()[0]] weights = [weights1,weights2,weights3] plot_model_result(history,weights,final_w) ###Output _____no_output_____ ###Markdown 2(c) . Construct and Train Convolutional Neural networkFor Convolutional Neural Networks we first change shape of th Datasets from set of array of 1 Dimensional array of $28x28$ image to a set of 3-Dimensinal Image with Value. ###Code x_train_imgs = xtrain.reshape(xtrain.shape[0],28,28,1) x_test_imgs = xtrain.reshape(xtest.shape[0],28,28,1) ###Output _____no_output_____ ###Markdown Preprocessing the Image :We use th ImageDataGenerator library from keras to generate a augumented form of out original training dataset. ###Code from keras.preprocessing.image import ImageDataGenerator aug_data = ImageDataGenerator(rotation_range=3, width_shift_range=0.25, # 0.25 * 28 = 8 pixels approx height_shift_range=0.25, # 0.25 * 28 = 8 pixels approx horizontal_flip=True, fill_mode="nearest") aug_data.fit(x_train_imgs) n = 0 for x_batch, y_batch in aug_data.flow(x_train_imgs, label_train, batch_size=1000): x_batch = np.reshape(x_batch, [-1, 28*28]) model.fit(x_batch, y_batch) n += 1 if n >= len(x_train_imgs) / 1000: break x_batch = x_batch.reshape(x_batch.shape[0],28,28,1) ###Output Epoch 1/1 1000/1000 [==============================] - 0s 78us/step - loss: 0.3252 - accuracy: 0.9000 ###Markdown Now we build the Convolutional Neutral Network and feed the Augumented Training Dataset to our model. ###Code model = Sequential() model.add(Conv2D(30, activation='sigmoid',kernel_size=(5, 5), input_shape=(28,28,1))) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(10, activation='softmax')) weights = [] save_weights = LambdaCallback(on_epoch_end=lambda batch, logs: weights.append(model.layers[0].get_weights()[0])) sgd = optimizers.SGD(learning_rate=0.1) model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(x_batch, y_batch,validation_data=(x_test_imgs, label_test), epochs=30, batch_size=10, shuffle = False,callbacks = [save_weights]) final_w = [model.layers[0].get_weights()[0]] weights = [weights] plot_model_result(history,weights,final_w) ###Output _____no_output_____
notebooks/currents.ipynb
###Markdown Strengths of currentsThe notebook calculates the strength of the California Current and California Undercurrent for a domain similar to "A climatology of the California CurrentSystem from a network of underwater gliders" (Rudnick, 2017). The following figures are created in this notebook:- Figure A.9 California Current and Undercurrent strength ###Code import sys sys.path.append('/nfs/kryo/work/maxsimon/master-thesis/scripts/') import os import xarray as xr import numpy as np from matplotlib import pyplot as plt plt.rcParams.update({'font.size': 12}) from romstools.romsrun import RomsRun from romstools.plot import plot_data from romstools.utils import p, cache, np_rolling_mean from romstools.cmap import DIFF, DIFF_r, W2G, W2G_r, G2R, G2R_r, get_step_cmap from romstools.dataset import open_dataset import scipy.signal as sig import scipy.stats as stat import cartopy.crs as ccrs import warnings from datetime import timedelta as tdelta import matplotlib.animation as animation from matplotlib import rc from matplotlib.cm import get_cmap ###Output _____no_output_____ ###Markdown Load Data ###Code ### pactcs30 meso = RomsRun('/nfs/kryo/work/maxsimon/data/pactcs30/grid.nc') # add location of zlevels meso.add_data('/nfs/kryo/work/maxsimon/data/pactcs30/z/z_levels.nc') # add horizontal velocities meso.add_data('/nfs/kryo/work/maxsimon/data/pactcs30/climatologies/z_vel-1d.nc') # add density meso.add_data('/nfs/kryo/work/maxsimon/data/pactcs30/climatologies/z_data-1d.nc') # add additional grid data data = np.load('/nfs/kryo/work/maxsimon/data/pactcs30/grid.npz', allow_pickle=True) meso.distance_map = data['distance_map'] meso.distance_lines = data['distance_lines'] meso.gruber_mask = data['gruber_mask'] ### pactcs15 subm = RomsRun('/nfs/kryo/work/maxsimon/data/pactcs15/grid.nc') # add location of zlevels subm.add_data('/nfs/kryo/work/maxsimon/data/pactcs15/z/z_levels.nc') # add horizontal velocities subm.add_data('/nfs/kryo/work/maxsimon/data/pactcs15/climatologies/z_vel-1d.nc') # add density subm.add_data('/nfs/kryo/work/maxsimon/data/pactcs15/climatologies/z_data-1d.nc') # add additional grid data data = np.load('/nfs/kryo/work/maxsimon/data/pactcs15/grid.npz', allow_pickle=True) subm.distance_map = data['distance_map'] subm.distance_lines = data['distance_lines'] subm.gruber_mask = data['gruber_mask'] runs = { 'pactcs15': subm, 'pactcs30': meso } ###Output _____no_output_____ ###Markdown SubdomainThe subdomain is defined such that it corresponds to> Rudnick, Daniel L. et al. (May 2017). “A climatology of the California CurrentSystem from a network of underwater gliders.”, Figure 4.2.3.1 ###Code SLICE_SUBM_1 = (slice(None, None), slice(640, 720)) SLICE_MESO_1 = (slice(None, None), slice(261, 296)) vertical_sections = { 'pactcs30': SLICE_MESO_1, 'pactcs15': SLICE_SUBM_1 } # Plot subdomain def plot_run_slices(run, ax, slices): for s in slices: plot_data(run.grid, run.distance_map, ax=ax, highlight_subdomain=s, lon_name='lon_rho', lat_name='lat_rho', as_contourfill=True, cbar_label='Distance [km]', cmap='Blues', highlight_subdomain_alpha=0.0, colorbar=False); for line in run.distance_lines: ax.plot(line[0], line[1], color='white', transform=ccrs.PlateCarree()) ax.set_ylim(24, 42) ax.set_xlim(-136, -120) fig, ax = plt.subplots(1, 2, figsize=(20, 10), subplot_kw={'projection': ccrs.PlateCarree()}) plot_run_slices(subm, ax[0], [SLICE_SUBM_1]) plot_run_slices(meso, ax[1], [SLICE_MESO_1]) plt.show() ###Output /nfs/kryo/work/maxsimon/master-thesis/scripts/romstools/plot.py:123: RuntimeWarning: invalid value encountered in greater data_main[data_main > vmax] = vmax /nfs/kryo/work/maxsimon/master-thesis/scripts/romstools/plot.py:124: RuntimeWarning: invalid value encountered in less data_main[data_main < vmin] = vmin /nfs/kryo/work/maxsimon/master-thesis/scripts/romstools/plot.py:128: RuntimeWarning: invalid value encountered in greater data_subd[data_subd > vmax] = vmax /nfs/kryo/work/maxsimon/master-thesis/scripts/romstools/plot.py:129: RuntimeWarning: invalid value encountered in less data_subd[data_subd < vmin] = vmin ###Markdown Plotting and interpolation ###Code # see eddy_quenching for an analysis of this interp_points = { 'pactcs15': 200, 'pactcs30': 100 } ## This is a copy from eddy_quenching. ## TODO: move to external module def fix_nan_contour(func, distance_map, depth_values, data, **kwargs): # matplotlibs contour plots can not handle NaNs # this function fixes this xx, yy = None, None if len(distance_map.shape) == 2: print('WARNING :: DISTANCE MAP ON SECTION SLICE?') contour_x = np.mean(distance_map, axis=1) x_1 = np.argmin(np.isnan(contour_x[::-1])) xx, yy = np.meshgrid(contour_x[:-x_1], -depth_values) else: contour_x = distance_map xx, yy = np.meshgrid(contour_x, -depth_values) return func(xx[:data.shape[0]], yy[:data.shape[0]], data, **kwargs) def interpolate_to_dist(data, name, num_interp_points, distance_map=None): # interpolate data on rho grid to a grid with distance to coast as the main axis. # get run and distance map run = runs[name] dmap = run.distance_map[vertical_sections[name]] if distance_map is None else distance_map # set up bins distances = np.linspace(0, 900, num_interp_points) # and result array result = np.empty((data.shape[0], distances.shape[0] - 1)) centers = [] # loop bins for dist_idx in range(distances.shape[0] - 1): # create mask mask = np.logical_and( dmap >= distances[dist_idx], dmap < distances[dist_idx + 1] ) # calculate the value as average over all points belonging to the bin value = np.nanmean( data[:, mask], axis=1 ) # assign value to result result[:, dist_idx] = value # save the bin center for x coordinates centers.append(distances[dist_idx] + (distances[dist_idx + 1] - distances[dist_idx])/2) return np.array(centers), result def plot_vertical(self, ax, distances, values, vmin=None, vmax=None, num_levels=30, num_levels_lines=10, cmap=None, colorbar_label='', contour_lines=None, colorbar=True): # set limits ax.set_xlim(900, 0) # use number of levels or contstruct levels from vmin and vmax levels = num_levels if vmin is None or vmax is None else np.linspace(vmin, vmax, num_levels) # plot data cax = fix_nan_contour(ax.contourf, distances, self.z_level, values, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, extend='both') # get data for contours contour_values = contour_lines if contour_lines is not None else values # plot contours if num_levels_lines > 0: cax2 = fix_nan_contour(ax.contour, distances, self.z_level, contour_values, levels=num_levels_lines, colors='k', extend='both') ax.clabel(cax2, cax2.levels, inline=True, fontsize=10) # labels ax.set_xlabel('Distance to coast [km]') ax.set_ylabel('Depth [m]') # colorbar ticks = None # if vmin and vmax is provided, set up ticks for colorbar manually if vmin is not None and vmax is not None: ticks = np.linspace(vmin, vmax, 11) if colorbar: plt.colorbar(cax, ticks=ticks, label=colorbar_label, ax=ax) return cax ###Output _____no_output_____ ###Markdown Calculate Velocity ###Code def calc_u_vertical(self, section_slice, time_slice, name, var_contour='u_b'): """ Calculate a vertical section of u (parrallel to coast) for a given xi-section and time slice """ num_interp_points = interp_points[name] # calculate u values in cm/s u_b_values = self['u_b'].isel(xi_rho=section_slice[1], doy=time_slice).mean(dim=['doy']).values * 100 # calculate contour values values_contour = None if var_contour == 'u_b' else self[var_contour].isel(xi_rho=section_slice[1], doy=time_slice).mean(dim=['doy']).values # interpolate data to distance to coast space u_b_interpolated = interpolate_to_dist(u_b_values, name, num_interp_points, distance_map=self.distance_map[section_slice]) # u_b_interpolated = interpolate_to_dist(u_b_values, self.distance_map[section_slice], distances=np.linspace(0, 900, num_interp_points)) # interpolate contours to distance from coast space # contour_interpolated = None if var_contour == 'u_b' else interpolate_to_dist(values_contour, self.distance_map[section_slice], distances=np.linspace(0, 900, num_interp_points)) contour_interpolated = None if var_contour == 'u_b' else interpolate_to_dist(values_contour, name, num_interp_points, distance_map=self.distance_map[section_slice]) return u_b_interpolated, contour_interpolated def calc_vertical_comparison(slices, tslice): """ Calculate the vertical section for both, pactcs15 and pactcs30 """ res = {} for i, slice in enumerate(slices): res[i] = { 'subm': calc_u_vertical(subm, slice[0], tslice, 'pactcs15', var_contour='rho_b'), 'meso': calc_u_vertical(meso, slice[1], tslice, 'pactcs30', var_contour='rho_b'), } return res # set up doys all_year = np.arange(365) t0 = all_year[30:90] # february and march t1 = all_year[180:270] # june to august # calculate u-component for t0 res_t0 = calc_vertical_comparison([ (SLICE_SUBM_1, SLICE_MESO_1) ], t0) # calculate u-component for t1 res_t1 = calc_vertical_comparison([ (SLICE_SUBM_1, SLICE_MESO_1) ], t1) # join to dictionary res = { 0: res_t0[0], 1: res_t1[0] } def plot_precalculated_comparison(res, path='', captions=[]): fig, ax = plt.subplots(len(res), 2, figsize=(15, 5*len(res)), sharex=True, sharey=True) # lets us use indexing on ax even for a single item if len(res) == 1: ax = np.array([ax]) # loop the results to compare for i in range(len(res)): add_caption = '' if len(captions) == 0 else ' - '+captions[i] # get values f_b_interpolated, contour_interpolated = res[i]['meso'] # plot plot_vertical(meso, ax[i, 0], f_b_interpolated[0], f_b_interpolated[1], vmin=-25, vmax=25, cmap='bwr_r', contour_lines=contour_interpolated[1], colorbar=False) # add title and extent ax[i, 0].set_title('MR' + add_caption) ax[i, 0].set_xlim(600, 0) # get values f_b_interpolated, contour_interpolated = res[i]['subm'] # plot cax = plot_vertical(subm, ax[i, 1], f_b_interpolated[0], f_b_interpolated[1], vmin=-25, vmax=25, cmap='bwr_r', contour_lines=contour_interpolated[1], colorbar=False) # add title and extent ax[i, 1].set_title('HR' + add_caption) ax[i, 1].set_xlim(600, 0) # set xlim and ylim ax[i, 0].set_xlim(250, 0) ax[i, 1].set_xlim(250, 0) ax[i, 0].set_ylim(-500, 0) ax[i, 1].set_ylim(-500, 0) # add or remove labels ax[i, 1].set_ylabel('') if i != len(res) - 1: ax[i, 0].set_xlabel('') ax[i, 1].set_xlabel('') # colorbar colorbar_label = 'North u [cm / s] South' plt.colorbar(cax, ax=ax, label=colorbar_label, location='bottom', ticks=[-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25]) if path != '': plt.savefig(path) plt.show() plot_precalculated_comparison(res, captions=['February to March', 'June to August'], path='figures/result_undercurrent.pdf') ###Output _____no_output_____
spot/tests/python/ltsmin-dve.ipynb
###Markdown There are two ways to load a DiVinE model: from a file or from a cell. Loading from a file-------------------We will first start with the file version, however because this notebook should also be a self-contained test case, we start by writing a model into a file. ###Code !rm -f test1.dve %%file test1.dve int a = 0, b = 0; process P { state x; init x; trans x -> x { guard a < 3 && b < 3; effect a = a + 1; }, x -> x { guard a < 3 && b < 3; effect b = b + 1; }; } process Q { state wait, work; init wait; trans wait -> work { guard b > 1; }, work -> wait { guard a > 1; }; } system async; ###Output Writing test1.dve ###Markdown The `spot.ltsmin.load` function compiles the model using the `ltlmin` interface and load it. This should work with DiVinE models if `divine --LTSmin` works, and with Promela models if `spins` is installed. ###Code m = spot.ltsmin.load('test1.dve') ###Output _____no_output_____ ###Markdown Compiling the model creates all several kinds of files. The `test1.dve` file is converted into a C++ source code `test1.dve.cpp` which is then compiled into a shared library `test1.dve2c`. Becauce `spot.ltsmin.load()` has already loaded this shared library, all those files can be erased. If you do not erase the files, `spot.ltsmin.load()` will use the timestamps to decide whether the library should be recompiled or not everytime you load the library.For editing and loading DVE file from a notebook, it is a better to use the `%%dve` as shown next. ###Code !rm -f test1.dve test1.dve.cpp test1.dve2C ###Output _____no_output_____ ###Markdown Loading from a notebook cell----------------------------The `%%dve` cell magic implements all of the above steps (saving the model into a temporary file, compiling it, loading it, erasing the temporary files). The variable name that should receive the model (here `m`) should be indicated on the first line, after `%dve`. ###Code %%dve m int a = 0, b = 0; process P { state x; init x; trans x -> x { guard a < 3 && b < 3; effect a = a + 1; }, x -> x { guard a < 3 && b < 3; effect b = b + 1; }; } process Q { state wait, work; init wait; trans wait -> work { guard b > 1; }, work -> wait { guard a > 1; }; } system async; ###Output _____no_output_____ ###Markdown Working with an ltsmin model----------------------------Printing an ltsmin model shows some information about the variables it contains and their types, however the `info()` methods provide the data in a map that is easier to work with. ###Code m sorted(m.info().items()) ###Output _____no_output_____ ###Markdown To obtain a Kripke structure, call `kripke` and supply a list of atomic propositions to observe in the model. ###Code k = m.kripke(["a<1", "b>2"]) k k.show('.<15') k.show('.<0') # unlimited output a = spot.translate('"a<1" U "b>2"'); a spot.otf_product(k, a) ###Output _____no_output_____ ###Markdown If we want to create a `model_check` function that takes a model and formula, we need to get the list of atomic propositions used in the formula using `atomic_prop_collect()`. This returns an `atomic_prop_set`: ###Code a = spot.atomic_prop_collect(spot.formula('"a < 2" W "b == 1"')); a def model_check(f, m): f = spot.formula(f) ss = m.kripke(spot.atomic_prop_collect(f)) nf = spot.formula_Not(f).translate() return spot.otf_product(ss, nf).is_empty() model_check('"a<1" R "b > 1"', m) ###Output _____no_output_____ ###Markdown Instead of `otf_product(x, y).is_empty()` we prefer to call `!x.intersects(y)`. There is also `x.intersecting_run(y)` that can be used to return a counterexample. ###Code def model_debug(f, m): f = spot.formula(f) ss = m.kripke(spot.atomic_prop_collect(f)) nf = spot.formula_Not(f).translate() return ss.intersecting_run(nf) run = model_debug('"a<1" R "b > 1"', m); run ###Output _____no_output_____ ###Markdown This accepting run can be represented as an automaton (the `True` argument requires the state names to be preserved). This can be more readable. ###Code run.as_twa(True) ###Output _____no_output_____
soln/glucose_soln.ipynb
###Markdown Modeling and Simulation in PythonChapter 18Copyright 2017 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ###Code # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * ###Output _____no_output_____ ###Markdown Code from the previous chapterRead the data. ###Code data = pd.read_csv('data/glucose_insulin.csv', index_col='time'); ###Output _____no_output_____ ###Markdown Interpolate the insulin data. ###Code I = interpolate(data.insulin) ###Output _____no_output_____ ###Markdown Initialize the parameters ###Code G0 = 290 k1 = 0.03 k2 = 0.02 k3 = 1e-05 ###Output _____no_output_____ ###Markdown To estimate basal levels, we'll use the concentrations at `t=0`. ###Code Gb = data.glucose[0] Ib = data.insulin[0] ###Output _____no_output_____ ###Markdown Create the initial condtions. ###Code init = State(G=G0, X=0) ###Output _____no_output_____ ###Markdown Make the `System` object. ###Code t_0 = get_first_label(data) t_end = get_last_label(data) system = System(G0=G0, k1=k1, k2=k2, k3=k3, init=init, Gb=Gb, Ib=Ib, I=I, t_0=t_0, t_end=t_end, dt=2) def update_func(state, t, system): """Updates the glucose minimal model. state: State object t: time in min system: System object returns: State object """ G, X = state k1, k2, k3 = system.k1, system.k2, system.k3 I, Ib, Gb = system.I, system.Ib, system.Gb dt = system.dt dGdt = -k1 * (G - Gb) - X*G dXdt = k3 * (I(t) - Ib) - k2 * X G += dGdt * dt X += dXdt * dt return State(G=G, X=X) def run_simulation(system, update_func): """Runs a simulation of the system. system: System object update_func: function that updates state returns: TimeFrame """ t_0, t_end, dt = system.t_0, system.t_end, system.dt frame = TimeFrame(columns=init.index) frame.row[t_0] = init ts = linrange(t_0, t_end, dt) for t in ts: frame.row[t+dt] = update_func(frame.row[t], t, system) return frame results = run_simulation(system, update_func); ###Output _____no_output_____ ###Markdown Numerical solutionIn the previous chapter, we approximated the differential equations with difference equations, and solved them using `run_simulation`.In this chapter, we solve the differential equation numerically using `run_ode_solver`, which is a wrapper for the SciPy ODE solver.Instead of an update function, we provide a slope function that evaluates the right-hand side of the differential equations. We don't have to do the update part; the solver does it for us. ###Code def slope_func(state, t, system): """Computes derivatives of the glucose minimal model. state: State object t: time in min system: System object returns: derivatives of G and X """ G, X = state k1, k2, k3 = system.k1, system.k2, system.k3 I, Ib, Gb = system.I, system.Ib, system.Gb dGdt = -k1 * (G - Gb) - X*G dXdt = k3 * (I(t) - Ib) - k2 * X return dGdt, dXdt ###Output _____no_output_____ ###Markdown We can test the slope function with the initial conditions. ###Code slope_func(init, 0, system) ###Output _____no_output_____ ###Markdown Here's how we run the ODE solver. ###Code results2, details = run_ode_solver(system, slope_func, t_eval=data.index); ###Output _____no_output_____ ###Markdown `details` is a `ModSimSeries` object with information about how the solver worked. ###Code details ###Output _____no_output_____ ###Markdown `results` is a `TimeFrame` with one row for each time step and one column for each state variable: ###Code results2 ###Output _____no_output_____ ###Markdown Plotting the results from `run_simulation` and `run_ode_solver`, we can see that they are not very different. ###Code plot(results.G, '-') plot(results2.G, '-') plot(data.glucose, 'bo') ###Output _____no_output_____ ###Markdown The differences in `G` are less than 1%. ###Code diff = results.G - results2.G percent_diff = diff / results2.G * 100 percent_diff.dropna() ###Output _____no_output_____ ###Markdown Optimization Now let's find the parameters that yield the best fit for the data. We'll use these values as an initial estimate and iteratively improve them. ###Code params = Params(G0 = 290, k1 = 0.03, k2 = 0.02, k3 = 1e-05) ###Output _____no_output_____ ###Markdown `make_system` takes the parameters and actual data and returns a `System` object. ###Code def make_system(params, data): """Makes a System object with the given parameters. params: sequence of G0, k1, k2, k3 data: DataFrame with `glucose` and `insulin` returns: System object """ # params might be a Params object or an array, # so we have to unpack it like this G0, k1, k2, k3 = params Gb = data.glucose[0] Ib = data.insulin[0] I = interpolate(data.insulin) t_0 = get_first_label(data) t_end = get_last_label(data) init = State(G=G0, X=0) return System(G0=G0, k1=k1, k2=k2, k3=k3, init=init, Gb=Gb, Ib=Ib, I=I, t_0=t_0, t_end=t_end, dt=2) system = make_system(params, data) ###Output _____no_output_____ ###Markdown `error_func` takes the parameters and actual data, makes a `System` object, and runs `odeint`, then compares the results to the data. It returns an array of errors. ###Code system = make_system(params, data) results, details = run_ode_solver(system, slope_func, t_eval=data.index) details def error_func(params, data): """Computes an array of errors to be minimized. params: sequence of parameters data: DataFrame of values to be matched returns: array of errors """ print(params) # make a System with the given parameters system = make_system(params, data) # solve the ODE results, details = run_ode_solver(system, slope_func, t_eval=data.index) # compute the difference between the model # results and actual data errors = results.G - data.glucose return errors ###Output _____no_output_____ ###Markdown When we call `error_func`, we provide a sequence of parameters as a single object. Here's how that works: ###Code error_func(params, data) ###Output G0 290.00000 k1 0.03000 k2 0.02000 k3 0.00001 dtype: float64 ###Markdown `leastsq` is a wrapper for `scipy.optimize.leastsq` Here's how we call it. ###Code best_params, fit_details = leastsq(error_func, params, data) ###Output [2.9e+02 3.0e-02 2.0e-02 1.0e-05] [2.9e+02 3.0e-02 2.0e-02 1.0e-05] [2.9e+02 3.0e-02 2.0e-02 1.0e-05] [2.90000004e+02 3.00000000e-02 2.00000000e-02 1.00000000e-05] [2.90000000e+02 3.00000004e-02 2.00000000e-02 1.00000000e-05] [2.90000000e+02 3.00000000e-02 2.00000003e-02 1.00000000e-05] [2.90000000e+02 3.00000000e-02 2.00000000e-02 1.00000001e-05] ###Markdown The first return value is a `Params` object with the best parameters: ###Code best_params ###Output _____no_output_____ ###Markdown The second return value is a `ModSimSeries` object with information about the results. ###Code fit_details ###Output _____no_output_____ ###Markdown Now that we have `best_params`, we can use it to make a `System` object and run it. ###Code system = make_system(best_params, data) results, details = run_ode_solver(system, slope_func, t_eval=data.index) details.message ###Output _____no_output_____ ###Markdown Here are the results, along with the data. The first few points of the model don't fit the data, but we don't expect them to. ###Code plot(results.G, label='simulation') plot(data.glucose, 'bo', label='glucose data') decorate(xlabel='Time (min)', ylabel='Concentration (mg/dL)') savefig('figs/chap08-fig04.pdf') ###Output Saving figure to file figs/chap08-fig04.pdf ###Markdown Interpreting parametersBased on the parameters of the model, we can estimate glucose effectiveness and insulin sensitivity. ###Code def indices(params): """Compute glucose effectiveness and insulin sensitivity. params: sequence of G0, k1, k2, k3 data: DataFrame with `glucose` and `insulin` returns: State object containing S_G and S_I """ G0, k1, k2, k3 = params return State(S_G=k1, S_I=k3/k2) ###Output _____no_output_____ ###Markdown Here are the results. ###Code indices(best_params) ###Output _____no_output_____ ###Markdown Under the hoodHere's the source code for `run_ode_solver` and `leastsq`, if you'd like to know how they work. ###Code source_code(run_ode_solver) source_code(leastsq) ###Output def leastsq(error_func, x0, *args, **options): """Find the parameters that yield the best fit for the data. `x0` can be a sequence, array, Series, or Params Positional arguments are passed along to `error_func`. Keyword arguments are passed to `scipy.optimize.leastsq` error_func: function that computes a sequence of errors x0: initial guess for the best parameters args: passed to error_func options: passed to leastsq :returns: Params object with best_params and ModSimSeries with details """ # override `full_output` so we get a message if something goes wrong options['full_output'] = True # run leastsq t = scipy.optimize.leastsq(error_func, x0=x0, args=args, **options) best_params, cov_x, infodict, mesg, ier = t # pack the results into a ModSimSeries object details = ModSimSeries(infodict) details.set(cov_x=cov_x, mesg=mesg, ier=ier) # if we got a Params object, we should return a Params object if isinstance(x0, Params): best_params = Params(Series(best_params, x0.index)) # return the best parameters and details return best_params, details
lecture03-python-introduction/lecture03-with-solutions.ipynb
###Markdown Review exercise 1 menti.com 52 00 21 Review exercise 2 menti.com 74 95 17 Review exercise 3 ###Code def squared(x): return x**2 ###Output _____no_output_____ ###Markdown Write a function ```pythonderivative(x, h, f)```which calculates the first numerical derivative of an arbitrary function $f(x)$. Use the formula $\frac{f(x + h) -f(x - h)}{2 h}$.Note: in Python you can pass a function as an argument of another function!Test it using parameters $x = 4$, $h = 0.0001$ and the function ```squared```defined above. ###Code def derivative(x, h, f): return (f(x+h) - f(x - h)) / (2 * h) derivative(4, 0.0001, squared) ###Output _____no_output_____ ###Markdown Lecture 3 - continuing the introduction to Python Data types in Python ###Code type(1) type(1.1) type(1 + 2j) type(True) type("Hello World") a = 1 type(a) b = 1.1 type(b) c = a + b ###Output _____no_output_____ ###Markdown What is the type of c? ###Code type(c) d = 2 type(d) e = a + d ###Output _____no_output_____ ###Markdown What is the type of e? ###Code type(e) f = a / d ###Output _____no_output_____ ###Markdown _Warning: Python 2 behaves differently here, but Python 2 is not relevant anylonger (unsupported since 1.1.2020)._ What is the type of f? ###Code type(f) ###Output _____no_output_____ ###Markdown Hints Integer overflowsInteger variables cannot overflow in Python, i.e. you can have an arbitrarily high Integer number. This is different to other programming languages such as C, where the size of an Integer number is fixed. If you do not know, what any of this means, it will be explained later when talking about numpy as numpy integers can overflow. Floating point precisionFloating point numbers have limited precision (53 bits or 16 digits). A number can become arbitrarily high, but it has limited precisions. This is due to how internally, floating points are stored in memory. More details on [wikipedia](https://en.wikipedia.org/wiki/Floating-point_arithmetic) and a tutorial can be found [here](http://cstl-csm.semo.edu/xzhang/Class%20Folder/CS280/Workbook_HTML/FLOATING_tut.htm)![Floating point precision](https://upload.wikimedia.org/wikipedia/commons/9/98/A_number_line_representing_single-precision_floating_point%27s_numbers_and_numbers_that_it_cannot_display.png)Attribution: Joeleoj123 / CC BY-SA (https://creativecommons.org/licenses/by-sa/4.0) Why is this relevant? ###Code a_large_number = 10**12 + 0.1 a_large_number a_small_number = 0.0000001 many_times = 10000000 for i in range(0, many_times): a_large_number = a_large_number + a_small_number a_large_number a_large_number = a_large_number + many_times * a_small_number a_large_number ###Output _____no_output_____ ###Markdown Whaaaaaaaaat?Well - limited precisions.```pythona_large_number + a_small_number```is, due to limited precision, calculated to be```pythona_large_number + a_small_number``` String operations String is text. A new string is simply started by enclosing text in " ###Code 'This is a string' ###Output _____no_output_____ ###Markdown Double quotes " and single quotes ' are equivalent Python, there is no syntactic difference. [A very popular convention](https://stackoverflow.com/a/56190/859591) is to use single quotes for constants and double quotes for human readable text or sentances. A different popular convention is to use only [only double quotes](https://black.readthedocs.io/en/stable/the_black_code_style.htmlstrings). ###Code x = 7 f'The value of x is {x}' import math y = 6.589309493 f'The value of y is {round(y)}' a_lot_of_text = ( 'line1' 'line2' 'line3') a_lot_of_text ###Output _____no_output_____ ###Markdown But... ###Code a_lot_of_text = """ line1 line2 line3""" a_lot_of_text ###Output _____no_output_____ ###Markdown Why is there a \n? Exercise 1Write code which shows the following text 'PI is '. Substitute by the value of PI. Hint: ```Pythonmath.pi```returns pi ###Code import math f"PI is {math.pi}" ###Output _____no_output_____ ###Markdown Multiple assignments and return values ###Code a, b = 1, 2 a b ###Output _____no_output_____ ###Markdown Functions with multiple return values ###Code import math def calculate_growth_doubling_time(value_t1, value_t2, time_diff): growth_rate = (value_t2 / value_t1)**(1 / time_diff) - 1 doubling_time = math.log(2) / math.log(growth_rate + 1) return growth_rate, doubling_time growth_rate, doubling_time = calculate_growth_doubling_time(1, 1.2, 1) print(growth_rate) print(doubling_time) ###Output 0.19999999999999996 3.8017840169239308 ###Markdown Exercise 2Write a function that calculates the growth_rate, the doubling time, and the relative growth_rate given by $\frac{\textrm{value_t2} - \textrm{value_t1}}{\textrm{value_t1}}$. Use the upper function calculate_growth_doubling_time for that purpose. Return all three values. The function should be called ```pythongrowth_parameters(value_t1, value_t2, time_diff)``` ###Code def growth_parameters(value_t1, value_t2, time_diff): return (value_t2 - value_t1) / value_t1 growth_parameters(1, 1.2, 1) ###Output _____no_output_____ ###Markdown Some basic data structures in Python Lists ###Code l = [1, 2, 3] l l[1] ###Output _____no_output_____ ###Markdown Important: different to R, an index in Python starts with 0, not with 1. So the first element of a list is 0! ###Code l[0] ###Output _____no_output_____ ###Markdown What will happen here? ###Code l[3] l[0:2] l = [1, 2, 3, 4, 5, 6] l[1:5] len(l) ###Output _____no_output_____ ###Markdown Exercise 3Write a function named ```pythonlist_info(l)```that takes a list and returns the length of the list, the first element and the last element. Test the code with the list```python[7, 14, 21, 43]``` ###Code def list_info(l): return len(l), l[0], l[-1] list_info([7, 14, 21, 43]) ###Output _____no_output_____ ###Markdown Operators on lists ###Code [1, 2] * 2 [1, 2] + [2] [1, 2] + 2 ###Output _____no_output_____ ###Markdown Control structures: loopsLoops allow to repeat things. We will see that they become obsolete in many cases, when working with the scientific packages in Python (such as numpy), but we still introduce them. ###Code for x in range(3): print(x) for x in range(17, 19): print(x) ###Output 17 18 ###Markdown What will happen here? ###Code for x in range(19, 17): print(x) l = [1, 2, 3] for v in l: print(v) # other programing languages do it like this, in Python you never need this! for k in range(0, len(l)): print(l[k]) ###Output 1 2 3 ###Markdown Pro: this may become important - if you do not understand it now, don't worry.Lists are passed by reference - whatever you do to a list in function, will also affect the list outside of the function. Watch! ###Code def change_list(l): l1 = l l1[0] = 43 return l1 l = [1, 2, 3] result = change_list(l) print(l) print(result) def do_not_change_list(l): l1 = l.copy() l1[0] = 43 return l1 l = [1, 2, 3] result = do_not_change_list(l) print(l) print(result) ###Output [1, 2, 3] [43, 2, 3] ###Markdown List comprehensionsTo work with lists and for loops is not very Pythonic. In many cases list comprehensions are much more convenient: ###Code l = [1, 10, 100] # Take log10 of all list elements: [math.log(i, 10) for i in l] ###Output _____no_output_____ ###Markdown Exercise 4Write a function ```pythonlog10_list(l)```which calculates the logarithmus with basis 10 of all elements in that list and returns the resulting list. Test it on the list```pythonl = [1, 10, 100, 1000]```Print ```pythonl```before and after calling your function. ###Code def log10_list(l): return [math.log(i, 10) for i in l] l = [1, 10, 100, 1000] print("Before:", l) result = log10_list(l) print("After:", l) print("Result: ", result) ###Output Before: [1, 10, 100, 1000] After: [1, 10, 100, 1000] Result: [0.0, 1.0, 2.0, 2.9999999999999996] ###Markdown Reading dataWe will read data from disk. This is just to make things more interesting. Do not worry about the details now. ###Code import csv with open('austria_covid_19_data.csv', 'r') as read_obj: # pass the file object to reader() to get the reader object csv_reader = csv.reader(read_obj) # Pass reader object to list() to get a list of lists list_of_rows = list(csv_reader) list_of_rows ### get second column infected_cases = [i[1] for i in list_of_rows] infected_cases ### remove first line, as it contains header infected_cases = infected_cases[1:] infected_cases ### convert to integer, as it is string infected_cases = [int(i) for i in infected_cases] infected_cases ###Output _____no_output_____ ###Markdown Plotting data with matplotlib ###Code import math import matplotlib.pyplot as plt plt.plot(infected_cases, label = 'infections') plt.plot([math.log(i, 10) for i in infected_cases], label = 'log(infections)') plt.plot([infected_cases[0] * 1.28**i for i in range(len(infected_cases))], label = 'exponential with growth rate 28%') plt.xlabel('Time') plt.ylabel('Infections') plt.title('Infections') plt.legend() plt.show() import matplotlib.pyplot as plt import math plt.plot([math.log(i, 10) for i in infected_cases], label = 'log(infections)') plt.xlabel('Time') plt.ylabel('log(infections)') plt.title('Log(infections)') plt.legend() plt.show() ###Output _____no_output_____ ###Markdown Exercise 5Calculate the daily growth rate for all time steps and the doubling time for all time steps and plot both in one extra figure, i.e. one figure showing the growth rate, the other one showing the doubling time. For that purpose you can use the function```calculate_growth_doubling_time(value_t1, value_t2, time_diff)```defined above.Note: A very Pythonic way to achieve this involes zusing `zip()` and parameter unpacking using `*`. This a bit beyond scope of this excercise, a non-Pythonic way is perfectly fine for now. ###Code calculate_growth_doubling_time(infected_cases[0], infected_cases[1], time_diff=1) [x + 10 for x, y in [(1,2), (3,4), (5,6)] ] list(zip(*[(1,2), (3,4), (5,6)])) [(1,2), (3,4), (5,6)] growth_rates, doubling_times = zip(*[calculate_growth_doubling_time(value_t1, value_t2, 1) for value_t1, value_t2 in zip(infected_cases[:-1], infected_cases[1:])]) growth_rates, doubling_times = zip(*[calculate_growth_doubling_time(value_t1, value_t2, 1) for value_t1, value_t2 in zip(infected_cases[:-1], infected_cases[1:])]) import matplotlib.pyplot as plt import math plt.plot(growth_rates, label = 'Daily growth rates') plt.xlabel('Time') plt.ylabel('Ratio') plt.title('Daily growth rates') plt.legend() plt.show() import matplotlib.pyplot as plt import math plt.plot(doubling_times, label = 'Doubling time') plt.xlabel('Time') plt.ylabel('Days') plt.title('Doubling time') plt.legend() plt.show() ###Output _____no_output_____ ###Markdown Exercise 6Write a function which calculates the growth rate and doubling time for all time steps, i.e. similar to the code in Exercise 5. The function is defined as```growth_rate_doubling_time(l, interval)```Interval defines how many days are between the start and the end value (i.e. value_t1 and value_t2 in calculate_growth_doubling_time). Test the function by applying it to the infection data with an interval time of 7 and plotting the growth rate and the doubling time. ###Code def growth_rate_doubling_time(l, interval): return zip(*[calculate_growth_doubling_time(value_t1, value_t2, interval) for value_t1, value_t2 in zip(l[:-1], l[1:])]) # first test if the function does the same as before... growth_rates_, doubling_times_ = growth_rate_doubling_time(infected_cases, 1) growth_rates == growth_rates_, doubling_times == doubling_times_ # first test if the function does the same as before... growth_rates, doubling_times = growth_rate_doubling_time(infected_cases, 7) import matplotlib.pyplot as plt import math plt.plot(growth_rates, label = 'Weekly growth rates') plt.xlabel('Time') plt.ylabel('Ratio') plt.title('Weekly growth rates') plt.legend() plt.show() import matplotlib.pyplot as plt import math plt.plot(doubling_times, label = 'Doubling time') plt.xlabel('Time') plt.ylabel('Days') plt.title('Doubling time') plt.legend() plt.show() ###Output _____no_output_____
liabilities_funding_ratio.ipynb
###Markdown CIR Model to simulate changes in Interest Rates and Liability Hedging$$ dr_{t}=a(b-r_{t})\,dt+\sigma {\sqrt {r_{t}}}\,dW_{t} $$ ###Code def inst_to_ann(r): """ Converts short rate to an annualized rate :param r: :return: """ return np.expm1(r) def ann_to_inst(r): """ Convert annualized to a short rate :param r: :return: """ return np.log1p(r) %load_ext autoreload %autoreload 2 %matplotlib inline import pandas as pd import numpy as np import edhec_risk_kit as erk import math import matplotlib.pyplot as plt import ipywidgets as widgets from IPython.display import display def cir(n_years = 10, n_scenarios=1, a=0.05, b=0.03, sigma=0.05, steps_per_year=12, r_0=None): """ Generate random interest rate evolution over time using the CIR model b and r_0 are assumed to be the annualized rates, not the short rate and the returned values are the annualized rates as well """ if r_0 is None: r_0 = b r_0 = ann_to_inst(r_0) dt = 1/steps_per_year num_steps = int(n_years*steps_per_year) + 1 # because n_years might be a float shock = np.random.normal(0, scale=np.sqrt(dt), size=(num_steps, n_scenarios)) rates = np.empty_like(shock) rates[0] = r_0 ## For Price Generation h = math.sqrt(a**2 + 2*sigma**2) prices = np.empty_like(shock) #### def price(ttm, r): _A = ((2*h*math.exp((h+a)*ttm/2))/(2*h+(h+a)*(math.exp(h*ttm)-1)))**(2*a*b/sigma**2) _B = (2*(math.exp(h*ttm)-1))/(2*h + (h+a)*(math.exp(h*ttm)-1)) _P = _A*np.exp(-_B*r) return _P prices[0] = price(n_years, r_0) #### for step in range(1, num_steps): r_t = rates[step-1] d_r_t = a*(b-r_t)*dt + sigma*np.sqrt(r_t)*shock[step] rates[step] = abs(r_t + d_r_t) # generate prices at time t as well ... prices[step] = price(n_years-step*dt, rates[step]) rates = pd.DataFrame(data=inst_to_ann(rates), index=range(num_steps)) ### for prices prices = pd.DataFrame(data=prices, index=range(num_steps)) ### return rates, prices def show_cir_prices(r_0=0.03, a=0.5, b=0.03, sigma=0.05, n_scenarios=5): cir(r_0=r_0, a=a, b=b, sigma=sigma, n_scenarios=n_scenarios)[1].plot(legend=False, figsize=(12,5)) controls = widgets.interactive(show_cir_prices, r_0 = (0, .15, .01), a = (0, 1, .1), b = (0, .15, .01), sigma= (0, .1, .01), n_scenarios = (1, 100)) display(controls) a_0 = 0.75 rates, bond_prices = cir(r_0=0.03, b=0.03, n_scenarios=10, n_years=10) liabilities = bond_prices zc_0 = erk.pv(pd.Series(data=[1], index=[10]), r=0.03) n_bonds = a_0/zc_0 av_zc_bonds = n_bonds*bond_prices av_cash = a_0*(rates/12+1).cumprod() av_cash.plot(legend=False, figsize=(12, 6)) av_zc_bonds.plot(legend=False, figsize=(12, 6)) (av_cash/av_zc_bonds).pct_change().plot(title='Returns of Funding Ratio with Cash (10 Scenarios)', legend=False, figsize=(12, 6)) (av_zc_bonds/av_zc_bonds).pct_change().plot(title='Returns of Funding Ratio with Cash (10 Scenarios)', legend=False, figsize=(12, 6)) a_0 = 0.6 rates, bond_prices = cir(n_scenarios=10000, r_0=0.03, b=0.03) liabilities = bond_prices zc_0 = erk.pv(pd.Series(data=[1], index=[10]), 0.03) n_bonds = a_0/zc_0 av_zc_bonds = n_bonds*bond_prices av_cash = a_0*(rates/12+1).cumprod() tfr_cash = av_cash.iloc[-1]/liabilities.iloc[-1] tfr_zc_bond = av_zc_bonds.iloc[-1]/liabilities.iloc[-1] ax = tfr_cash.plot.hist(label='Cash', figsize=(15, 6), bins = 100, legend=True) tfr_zc_bond.plot.hist(ax=ax, label="ZC Bonds", bins=100, legend=True, secondary_y=True) ###Output _____no_output_____
analysis/figures/y4analysis.ipynb
###Markdown Octanol Learning ###Code loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/OctLearningTest-03_23_2022-12_05/YArenaInfo.mat" df1 = loadmat(loadmat_file)['YArenaInfo'] loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/OctLearningTest-03_23_2022-14_12/YArenaInfo.mat" df2 = loadmat(loadmat_file)['YArenaInfo'] histories1 = df1['FlyChoiceMatrix'][0][0].T schedules1 = np.concatenate([[df1['RewardStateTallyOdor1'][0][0]], [df1['RewardStateTallyOdor2'][0][0]]], axis=0).transpose((2, 1, 0)) histories2 = df2['FlyChoiceMatrix'][0][0].T[[0,2,3]] schedules2 = np.concatenate([[df2['RewardStateTallyOdor1'][0][0][:,[0,2,3]]], [df2['RewardStateTallyOdor2'][0][0][:,[0,2,3]]]], axis=0).transpose((2, 1, 0)) histories = np.concatenate([histories1, histories2], axis=0) schedules = np.concatenate([schedules1, schedules2], axis=0) import seaborn as sns sns.set(style="ticks") sns.set(font_scale=1.2) plt.figure(figsize=(7,7)) for n in range(7): plt.plot(np.cumsum(histories[n]==0),np.cumsum(histories[n]==1),'-',color=plt.cm.viridis(n/6),alpha=1,linewidth=1) plt.plot(np.cumsum(histories==0,axis=1).mean(axis=0),np.cumsum(histories==1,axis=1).mean(axis=0),linewidth=3,color='gray',label=f"Average") plt.plot([0,len(histories[0])//2],[0,len(histories[0])//2],linewidth=2,color='black',linestyle='--') plt.text(10,40,f"(n = {len(histories)} flies)",fontsize=14) plt.xlabel('Cumulative number of OCT choices') plt.ylabel('Cumulative number of MCH choices') plt.box(False) plt.gca().set_aspect('equal') plt.tight_layout() plt.savefig('OctLearningTest.png',dpi=300,transparent=True) plt.show() i = schedules[0] plt.figure(figsize=(8,2)) plt.plot(np.arange(i.shape[0])[i[:,0]==1],np.zeros(np.sum(i[:,0]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(np.arange(i.shape[0])[i[:,1]==1],np.ones(np.sum(i[:,1]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(histories.mean(axis=0),'-',color=plt.cm.viridis(0.8),linewidth=2) plt.yticks([0,1],["OCT","MCH"]) plt.xlim([0,i.shape[0]]) plt.axhline(0.5,linewidth=2,color='black',linestyle='--') plt.box(False) plt.xlabel('Trial') plt.ylabel('Odor Choice') plt.tight_layout() plt.savefig('OctLearningTest-schedules.png',dpi=300,transparent=True) plt.show() ###Output _____no_output_____ ###Markdown Methycyclohexanol Learning ###Code loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/MchLearningTest-03_23_2022-15_50/YArenaInfo.mat" df1 = loadmat(loadmat_file)['YArenaInfo'] loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/MchLearningTest-03_24_2022-10_35/YArenaInfo.mat" df2 = loadmat(loadmat_file)['YArenaInfo'] histories1 = df1['FlyChoiceMatrix'][0][0].T[[0,2]] schedules1 = np.concatenate([[df1['RewardStateTallyOdor1'][0][0][:,[0,2]]], [df1['RewardStateTallyOdor2'][0][0][:,[0,2]]]], axis=0).transpose((2, 1, 0)) histories2 = df2['FlyChoiceMatrix'][0][0].T[[0,2,3]] schedules2 = np.concatenate([[df2['RewardStateTallyOdor1'][0][0][:,[0,2,3]]], [df2['RewardStateTallyOdor2'][0][0][:,[0,2,3]]]], axis=0).transpose((2, 1, 0)) histories = np.concatenate([histories1, histories2], axis=0) schedules = np.concatenate([schedules1, schedules2], axis=0) import seaborn as sns sns.set(style="ticks") sns.set(font_scale=1.2) plt.figure(figsize=(7,7)) for n in range(5): plt.plot(np.cumsum(histories[n]==0),np.cumsum(histories[n]==1),'-',color=plt.cm.viridis(n/4),alpha=1,linewidth=1) plt.plot(np.cumsum(histories==0,axis=1).mean(axis=0),np.cumsum(histories==1,axis=1).mean(axis=0),linewidth=3,color='gray',label=f"Average") plt.plot([0,100//2],[0,100//2],linewidth=2,color='black',linestyle='--') plt.text(40,10,f"(n = {len(histories)} flies)",fontsize=14) plt.xlabel('Cumulative number of OCT choices') plt.ylabel('Cumulative number of MCH choices') plt.box(False) plt.gca().set_aspect('equal') plt.tight_layout() plt.savefig('MchLearningTest.png',dpi=300,transparent=True) plt.show() i = schedules[0] plt.figure(figsize=(8,2)) plt.plot(np.arange(i.shape[0])[i[:,0]==1],np.zeros(np.sum(i[:,0]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(np.arange(i.shape[0])[i[:,1]==1],np.ones(np.sum(i[:,1]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(histories.mean(axis=0),'-',color=plt.cm.viridis(0.8),linewidth=2) plt.yticks([0,1],["OCT","MCH"]) plt.xlim([0,i.shape[0]]) plt.axhline(0.5,linewidth=2,color='black',linestyle='--') plt.box(False) plt.xlabel('Trial') plt.ylabel('Odor Choice') plt.tight_layout() plt.savefig('MchLearningTest-schedules.png',dpi=300,transparent=True) plt.show() ###Output _____no_output_____ ###Markdown ACV Preference Experiments ###Code loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/ACVPreferenceTest-03_26_2022-10_41/YArenaInfo.mat" df1 = loadmat(loadmat_file)['YArenaInfo'] loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/ACVPreferenceTest-03_26_2022-13_00/YArenaInfo.mat" df2 = loadmat(loadmat_file)['YArenaInfo'] histories1 = df1['FlyChoiceMatrix'][0][0].T#[[0,2]] histories2 = df2['FlyChoiceMatrix'][0][0].T#[[0,2,3]] histories = np.concatenate([histories1, histories2], axis=0) import seaborn as sns sns.set(style="ticks") sns.set(font_scale=1.2) plt.figure(figsize=(7,7)) for n in range(8): plt.plot(np.cumsum(histories[n]==0),np.cumsum(histories[n]==1),'-',color=plt.cm.viridis(n/7),alpha=1,linewidth=1) plt.plot(np.cumsum(histories==0,axis=1).mean(axis=0),np.cumsum(histories==1,axis=1).mean(axis=0),linewidth=3,color='gray',label=f"Average") plt.plot([0,len(histories[0])//2],[0,len(histories[0])//2],linewidth=2,color='black',linestyle='--') plt.text(40,10,f"(n = {len(histories)} flies)",fontsize=14) plt.xlabel('Cumulative number of AIR choices') plt.ylabel('Cumulative number of ACV choices') plt.box(False) plt.gca().set_aspect('equal') plt.tight_layout() plt.savefig('ACVPreferenceTest.png',dpi=300,transparent=True) plt.show() plt.figure(figsize=(8,2)) plt.plot(histories.mean(axis=0),'-',color=plt.cm.viridis(0.8),linewidth=2) plt.yticks([0,1],["OCT","MCH"]) plt.xlim([0,i.shape[0]]) plt.axhline(0.5,linewidth=2,color='black',linestyle='--') plt.box(False) plt.xlabel('Trial') plt.ylabel('Odor Choice') plt.tight_layout() plt.savefig('ACVPreferenceTest-schedules.png',dpi=300,transparent=True) plt.show() ###Output _____no_output_____ ###Markdown Reversal Experiment ###Code loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/MchLearningTest-03_24_2022-10_35/YArenaInfo.mat" df1 = loadmat(loadmat_file)['YArenaInfo'] loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/MchUnlearningOctLearningTest-03_24_2022-11_32/YArenaInfo.mat" df2 = loadmat(loadmat_file)['YArenaInfo'] loadmat_file = "//dm11/turnerlab/Rishika/4Y-Maze/RunData/OctLearningAfterMCHUnlearningTest-03_24_2022-11_58/YArenaInfo.mat" df3 = loadmat(loadmat_file)['YArenaInfo'] histories1 = df1['FlyChoiceMatrix'][0][0].T[[0,2,3]] schedules1 = np.concatenate([[df1['RewardStateTallyOdor1'][0][0][:,[0,2,3]]], [df1['RewardStateTallyOdor2'][0][0][:,[0,2,3]]]], axis=0).transpose((2, 1, 0)) histories2 = df2['FlyChoiceMatrix'][0][0].T[[0,2,1]] schedules2 = np.concatenate([[df2['RewardStateTallyOdor1'][0][0][:,[0,2,1]]], [df2['RewardStateTallyOdor2'][0][0][:,[0,2,1]]]], axis=0).transpose((2, 1, 0)) histories3 = df3['FlyChoiceMatrix'][0][0].T[[0,2,1]] schedules3 = np.concatenate([[df3['RewardStateTallyOdor1'][0][0][:,[0,2,1]]], [df3['RewardStateTallyOdor2'][0][0][:,[0,2,1]]]], axis=0).transpose((2, 1, 0)) histories = np.concatenate([histories1, histories2, histories3], axis=1) schedules = np.concatenate([schedules1, schedules2, schedules3], axis=1) import seaborn as sns sns.set(style="ticks") sns.set(font_scale=1.2) plt.figure(figsize=(7,7)) for n in range(3): plt.plot(np.cumsum(histories[n]==0),np.cumsum(histories[n]==1),'-',color=plt.cm.viridis(n/2),alpha=1,linewidth=1) plt.plot(np.cumsum(histories==0,axis=1).mean(axis=0),np.cumsum(histories==1,axis=1).mean(axis=0),linewidth=3,color='gray',label=f"Average") plt.plot([0,len(histories[0])//2],[0,len(histories[0])//2],linewidth=2,color='black',linestyle='--') plt.text(40,10,f"(n = {len(histories)} flies)",fontsize=14) plt.xlabel('Cumulative number of OCT choices') plt.ylabel('Cumulative number of MCH choices') plt.box(False) plt.gca().set_aspect('equal') plt.tight_layout() plt.savefig('ReversalLearningTest.png',dpi=300,transparent=True) plt.show() i = schedules[0] plt.figure(figsize=(8,2)) plt.plot(np.arange(i.shape[0])[i[:,0]==1],np.zeros(np.sum(i[:,0]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(np.arange(i.shape[0])[i[:,1]==1],np.ones(np.sum(i[:,1]==1)),'o',color=plt.cm.viridis(0.6),linewidth=2) plt.plot(histories.mean(axis=0),'-',color=plt.cm.viridis(0.8),linewidth=2) plt.yticks([0,1],["OCT","MCH"]) plt.xlim([0,i.shape[0]]) plt.axhline(0.5,linewidth=2,color='black',linestyle='--') plt.box(False) plt.xlabel('Trial') plt.ylabel('Odor Choice') plt.tight_layout() plt.savefig('ReversalLearningTest-schedules.png',dpi=300,transparent=True) plt.show() ###Output _____no_output_____
SentinelHub/.ipynb_checkpoints/Untitled-checkpoint.ipynb
###Markdown script from https://mygeoblog.com/2017/10/06/from-gee-to-numpy-to-geotiff/ ###Code # get data into different arrays #data = np.array((ee.Array(latlon.get("nd")).getInfo())) B1 = np.array((ee.Array(latlon.get('B1')).getInfo())) B2 = np.array((ee.Array(latlon.get('B2')).getInfo())) B4 = np.array((ee.Array(latlon.get('B4')).getInfo())) B5 = np.array((ee.Array(latlon.get('B5')).getInfo())) B8 = np.array((ee.Array(latlon.get('B8')).getInfo())) B8A = np.array((ee.Array(latlon.get('B8A')).getInfo())) B9 = np.array((ee.Array(latlon.get('B9')).getInfo())) B10 = np.array((ee.Array(latlon.get('B10')).getInfo())) B11 = np.array((ee.Array(latlon.get('B11')).getInfo())) B12 = np.array((ee.Array(latlon.get('B12')).getInfo())) lats = np.array((ee.Array(latlon.get("latitude")).getInfo())) lons = np.array((ee.Array(latlon.get("longitude")).getInfo())) # get the unique coordinates uniqueLats = np.unique(lats) uniqueLons = np.unique(lons) # get number of columns and rows from coordinates ncols = len(uniqueLons) nrows = len(uniqueLats) # determine pixelsizes ys = uniqueLats[1] - uniqueLats[0] xs = uniqueLons[1] - uniqueLons[0] data = np.array((B1,B2,B4,B5,B8,B8A,B9,B10,B11,B12)) #for i in range(0,10): # print( i ) # create an array with dimensions of image (3D array, as it is a multiband image we want) # this has not worked properly - check script arr2 = np.zeros([nrows, ncols,10], np.float32) #-9999 counter2 =0 for y in range(0,len(arr2),1): for x in range(0,len(arr2[0]),1): for z in range(0,10): #put 10 here, as 10 bands are input (put 13 if all 13 are input etc) if lats[counter2] == uniqueLats[y] and lons[counter2] == uniqueLons[x] and counter2 < len(lats)-1: counter2+=1 arr2[len(uniqueLats)-1-y,x] = data[z][counter2] # we start from lower left corner import matplotlib.pyplot as plt plt.imshow(arr2[:,:,1]) plt.show() arr2[:,:,5] cloud_detector = S2PixelCloudDetector(threshold=0.4, average_over=4, dilation_size=2) cloud_probs = cloud_detector.get_cloud_probability_maps(arr2) cloud_masks = cloud_detector.get_cloud_masks(np.array(wcsbands)) ###Output _____no_output_____
docs/examples/xopt_parallel.ipynb
###Markdown Xopt Parallel ExamplesXopt provides methods to parallelize optimizations using Processes, Threads, MPI, and Dask using the `concurrent.futures` interface as defined in https://www.python.org/dev/peps/pep-3148/ . ###Code # Import the class from xopt import Xopt # Notebook printing output #from xopt import output_notebook #output_notebook() !mkdir temp ###Output _____no_output_____ ###Markdown The `Xopt` object can be instantiated from a JSON or YAML file, or a dict, with the proper structure.Here we will make one ###Code # Make a proper input file. YAML=""" xopt: output_path: temp algorithm: name: cnsga options: max_generations: 5 population_size: 128 show_progress: True simulation: name: test_TNK evaluate: xopt.tests.evaluators.TNK.evaluate_TNK vocs: variables: x1: [0, 3.14159] x2: [0, 3.14159] objectives: {y1: MINIMIZE, y2: MINIMIZE} constraints: c1: [GREATER_THAN, 0] c2: [LESS_THAN, 0.5] linked_variables: {x9: x1} constants: {a: dummy_constant} """ ###Output _____no_output_____ ###Markdown Processes ###Code from concurrent.futures import ProcessPoolExecutor X = Xopt(YAML) with ProcessPoolExecutor() as executor: X.run(executor=executor) ###Output _____no_output_____ ###Markdown ThreadsContinue running, this time with threads. ###Code from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as executor: X.run(executor=executor) ###Output _____no_output_____ ###Markdown MPI The `test.yaml` file completely defines the problem. We will also direct the logging to an `xopt.log` file. The following invocation recruits 4 MPI workers to solve this problem.We can also continue by calling `.save` with a JSON filename. This will write all of previous results into the file. ###Code # Write YAML text to a file # open('test.yaml', 'w').write(YAML) X.save('test.json') !mpirun -n 4 python -m mpi4py.futures -m xopt.mpi.run -vv --logfile xopt.log test.json ###Output Namespace(input_file='test.json', logfile='xopt.log', verbose=2) Parallel execution with 4 workers Loading from JSON file: test.json Loading config from dict. Loading config from dict. Loading config from dict. Loading config from dict. Specified both known algorithm `cnsga` and `function`. Using known algorithm function. Starting at time 2021-10-08T13:13:09-07:00 ▄████▄ ███▄ █ ██████ ▄████ ▄▄▄ ▒██▀ ▀█ ██ ▀█ █ ▒██ ▒ ██▒ ▀█▒▒████▄ ▒▓█ ▄ ▓██ ▀█ ██▒░ ▓██▄ ▒██░▄▄▄░▒██ ▀█▄ ▒▓▓▄ ▄██▒▓██▒ ▐▌██▒ ▒ ██▒░▓█ ██▓░██▄▄▄▄██ ▒ ▓███▀ ░▒██░ ▓██░▒██████▒▒░▒▓███▀▒ ▓█ ▓██▒ ░ ░▒ ▒ ░░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░▒ ▒ ▒▒ ▓▒█░ ░ ▒ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ▒ ▒▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ Continuous Non-dominated Sorting Genetic Algorithm Version 0.4.3+219.gfff1660.dirty Creating toolbox from vocs. Created toolbox with 2 variables, 2 constraints, and 2 objectives. Using selection algorithm: nsga2 Loading config from dict. Initializing with existing population, size 128 Maximum generations: 11 ____________________________________________________ 128 fitness calculations for initial generation done. Submitting first batch of children Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/initial_pop_6.json 129it [00:00, 2822.75it/s] Generation 6: 0%| | 0/128 [00:00<?, ?it/s]Generation 6 completed in 0.00117 minutes Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/gen_7.json Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/pop_7.json Generation 6: 100%|██████████| 128/128 [00:00<00:00, 715.93it/s] Generation 7: 0%| | 0/128 [00:00<?, ?it/s]Generation 7 completed in 0.00299 minutes Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/gen_8.json Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/pop_8.json Generation 7: 100%|██████████| 128/128 [00:00<00:00, 767.73it/s] Generation 8: 0%| | 0/128 [00:00<?, ?it/s]Generation 8 completed in 0.00279 minutes Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/gen_9.json Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/pop_9.json Generation 8: 100%|██████████| 128/128 [00:00<00:00, 806.00it/s] Generation 9: 0%| | 0/128 [00:00<?, ?it/s]Generation 9 completed in 0.00265 minutes Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/gen_10.json Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/pop_10.json Generation 9: 100%|██████████| 128/128 [00:00<00:00, 816.36it/s] Generation 10: 0%| | 0/128 [00:00<?, ?it/s]Generation 10 completed in 0.00262 minutes Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/gen_11.json Pop written to /Users/chrisonian/Code/GitHub/xopt/examples/basic/temp/pop_11.json Generation 10: 130it [00:00, 952.17it/s] ###Markdown Dask ###Code from dask.distributed import Client with Client() as executor: X.run(executor=executor) ###Output _____no_output_____ ###Markdown Load output into PandasThis algorithm writes two types of files: `gen_{i}.json` with all of the new individuals evaluated in a generation, and `pop_{i}.json` with the latest best population. Xopt provides some functions to load these easily into a Pandas dataframe for further analysis. ###Code from xopt.dataset import load_all_xopt_data from glob import glob %config InlineBackend.figure_format = 'retina' # Get a list of all of the gen files genfiles = glob('temp/gen_*json') df = load_all_xopt_data(genfiles) df # Plot the feasible ones feasible_df = df[df['feasible']] feasible_df.plot('y1', 'y2', kind='scatter').set_aspect('equal') # Plot the infeasible ones infeasible_df = df[~df['feasible']] infeasible_df.plot('y1', 'y2', kind='scatter').set_aspect('equal') # This is the final population df1 = load_all_xopt_data(['temp/pop_17.json']) df1.plot('y1', 'y2', kind='scatter').set_aspect('equal') ###Output _____no_output_____ ###Markdown matplotlib plottingYou can always use matplotlib for customizable plotting ###Code import matplotlib.pyplot as plt %matplotlib inline # Extract objectives from output k1, k2 = 'y1', 'y2' fig, ax = plt.subplots(figsize=(6,6)) ax.scatter(infeasible_df[k1], infeasible_df[k2],color='blue', marker='.', alpha=0.5, label='infeasible') ax.scatter(feasible_df[k1], feasible_df[k2],color='orange', marker='.', label='feasible') ax.scatter(df1[k1], df1[k2],color='red', marker='.', label='final population') ax.set_xlabel(k1) ax.set_ylabel(k2) ax.set_aspect('auto') ax.set_title(f" {X.simulation['name']} using Xopt's CNSGA algorithm" ) plt.legend() # Cleanup !rm -r dask-worker-space !rm -r temp !rm xopt.log !rm test.json ###Output _____no_output_____
assignments/homework_5.ipynb
###Markdown Homework Assignment 5 - Logistic Regression, MLP, and CNN with Torch In this assignment, we will solve the face recognition problem again. This time we will be using a multilayer perceptron (MLP) and a convolutional neural network (CNN). We will do so usign the PyTorch framework. Reminders- Start by making a copy of this notebook in order to be able to save it.- Use **Ctrl+[** to expend all cells. Tip of the day - Progress BarWhen running a long calculation, we would usually want to have a progress bar to track the progress of our process. One great python package for creating such a progress bar is [**tqdm**](https://github.com/tqdm/tqdm). This package is easy to use and offers a highly customizable progress bar. For example, to add a progress bar to an existing loop, simply surrounding the iterable which the loops run over with the **tqdm_notebook** command:```pythonimport tqdmfor x in tqdm.tqdm_notebook(some_list): some_long_running_function(x)```✍️ Add a progress bar to the following loop: ###Code import tqdm import time ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% for i in range(10): ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% print('Step {}'.format(i)) time.sleep(1) ###Output _____no_output_____ ###Markdown Your IDs✍️ Fill in your IDs in the cell below: ###Code ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% # Replace the IDs bellow with our own student1_id = '012345678' student2_id = '012345678' ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% print('Hello ' + student1_id + ' & ' + student2_id) ###Output _____no_output_____ ###Markdown Importing PackagesImporting the NumPy, Pandas and Matplotlib packages. ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt ## This line makes matplotlib plot the figures inside the notebook %matplotlib inline ## Set some default values of the the matplotlib plots plt.rcParams['figure.figsize'] = (8.0, 8.0) # Set default plot's sizes plt.rcParams['axes.grid'] = True # Show grid by default in figures ###Output _____no_output_____ ###Markdown Graphical Processing Unit (GPU)GPUs are special processing cards which were originally developed to for accelerating graphical related calculations such as 3D rendering and adujsting and playing a high-resolution video. Today these cards are also in use for a variety of tasks which are not necessarily graphic related, such as training neural networks.These GPUs are optimal for parallelizing simple operations on a large amount of data. The CPU (Central Processing Unit) is the computer's main processing unit and usually has a few fast and "strong" processing components called cores (usually up to tens of cores ). As opposed to it, a GPUs usually has many (usually thousands of) slower and "weaker" cores.When running a process which performs some mathematical operation to a large amount of data, for example calculating the $e^x$ for each element in a large matrix or multiplication between two matrices, we can speed up our process significantly by running it on a GPU.The GPU does not share the same memory space with the CPU and has its own memory. Therefore before performing any calculation using a GPU, we must first transfer our data to the GPU's memory. Colab and GPUsIn this assignment, we will train our network on a GPU. Colab offers free GPU support, but it is not enabled by default. To enable it, go to the menu bar, open **Runtime->Change runtime type** and change **hardware accelerator** to GPU. Click **save** to save your selection. You will see how we can tell our code to perform an operation on the GPU instead of on the CPU. PyTorchPyTorch is a framework (a collection of tools) which significantly simplify the process of building and training neural networks. This framework was initially developed and is currently backed by Facebook. PyTorch is only one of many great such frameworks which currently exist. For a list of some of the commonly used frameworks today, see workshop 9.Specifically, in this assignment, we will relay on PyTorch for the following features:- The package's ability to automatic calculate gradients (using back-propagation)- The package's ability to move a variable to the GPU and perform calculations on it.- The package's stochastic gradient descent optimization object.- The built-in objects/function for building and training models: - Linear layer - Convolutional layers - Relu - SoftMax - Minus-logLikelihood loss In this homework assignment, we will **not** cover all of what is needed for using PyTorch. It is aimed to show you the basics idea of what the framework has to offer. To better understand PyTorch, a good place to start are the great tutorials on the package's [website](https://pytorch.org/tutorials/index.html). The "60 Minute Blitz" along with the "Learning PyTorch with Examples" on the website provide a great starting point. TensorsThe basic PyTorch object is the tensor with has a very similar (but not exact) interface to that of the NumPy array. A few differences which are worth mentioning:- Tensors do not yet support the "@" operator of performing matrix multiplication. It is performed by using **torch.matmul(a_mat, b_mat)**.- The transpose of a matrix is given by **a_mat.t()** (instead of the **a_mat.T** method which is in use in numpy)For example: ###Code import torch ## importing PyTorch ## Defining a tensor from lists of numbers x1 = torch.tensor([[1.,2.], [3., 4.]]) print('x1=\n{}\n'.format(x1)) ## Creating a random tensor x2 = torch.randint(low=0, high=10, size=(2, 3)).float() print('x2=\n{}\n'.format(x2)) ## Multipliing tensors y = torch.matmul(x1.t(), x2) print('torch.matmul(x1.t(), x2)=\n{}'.format(y)) ###Output _____no_output_____ ###Markdown An Important Comment About Single & Double Precision & Fixed PointsBy default, numpy uses 64 bit to store floating point numbers. This representation is optimal for most CPUs. In contrast to that, PyTorch uses 32 bits, which is optimal for most GPUs. The 64-bit representation is called **double precision**, and the 32-bit is called **single precision**.Most of PyTorch's operations can only be performed only between two tensors of the same type. Therefore we will make sure that all of our tensors will be stored using single precision. You can convert a tensor to single precision representation by using the tensors **.float()** command.For some of the operations, we will also need to convert fixed point tensors (integers) to single precision. This is done in a similar way using the **.float()** command.For example: ###Code ## This is a fixed point tensor x_int = torch.tensor([4, 2, 3]) print('x_int=\n{}'.format(x_int)) print('x_int.dtype={}\n'.format(x_int.dtype)) ## Converting the tensor to single persicion x_single = x_int.float() print('x_single=\n{}'.format(x_single)) print('x_single.dtype={}\n'.format(x_single.dtype)) ## Converting the tensor to double persicion x_doubel = x_int.double() print('x_doubel=\n{}'.format(x_doubel)) print('x_doubel.dtype={}\n'.format(x_doubel.dtype)) ###Output _____no_output_____ ###Markdown PyTorch and GPUsPyTorch provides a simple way to copy a tensor to the GPU's memory. The GPUs In PyTorch are referred to as [**CUDA**](https://en.wikipedia.org/wiki/CUDA) devices. A tensor can be copied to the GPU's memory by using the tensor's **.cuda** command. All the mathematical operations can then be performed on the copied tensor in the same way as if it was in the regular memory. The result of a calculation which was performed on the GPU will be stored on the GPU's memory as well.A tensor can be copied back from the GPU's memory to the regular memory using the **.cpu** command. For example: ###Code ## Moving x1 to the GPU x1_gpu = x1.cuda() print('x1_gpu=\n{}\n'.format(x1_gpu)) ## Moving x2 to the GPU x2_gpu = torch.randint(low=0, high=10, size=(2, 3)).float().cuda() print('x2_gpu=\n{}\n'.format(x1_gpu)) ## Performing matrix multiplication on the GPU y = torch.matmul(x1_gpu.t(), x2_gpu) print('torch.matmul(x1_gpu.t(), x2_gpu)=\n{}\n'.format(y)) print('y.cpu()=\n{}'.format(y.cpu())) ###Output _____no_output_____ ###Markdown Notice the **device='cuda:0'** which is attached to the outputs of tensors which are stored on the GPU's memory. ✍️ Calculate the multiplication table (לוח הכפל ($\left[1,2,\ldots,10\right]^T\left[1,2,\ldots,10\right]$)) on the GPU, copy the result back to the CPU and print the result:- PYTorch cannot multiply fixed point tensor on the GPU. Therefore so make sure you convert the tensors to single precision tensors. ###Code ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% mult_table = ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% print(mult_table) ###Output _____no_output_____ ###Markdown Calculating gradientsOne of PyTorch's main features is its ability to automatically calculate gradients by using back-propagation.To calculate the gradient of a function, we need to preforme the following steps:1. Select the variables according to which we would want to calculate the derivative.2. Clear all previous gradient calculations.3. Calculate the result of the functions for a given set of variables. (the forward path)4. Run the back-propagation function starting from the calculated result of the function.Let us start with an example, and then explain it.The following code calculates the following derivative: $\left.\frac{\partial}{\partial x}x^2+5x+4\right|_{x=3}$: ###Code ## Define the variables which we would want to calculate the derivative according to x = torch.tensor(3).float() x.requires_grad = True ## Calculate the function's result y = x ** 2 + 5 * x + 4 ## Run back-propagation y.backward() ## Prin the result x_grad = x.grad print('The derivative is: {}'.format(x_grad)) ###Output _____no_output_____ ###Markdown In the above cell, we have performed the following steps:1. We have first defined a tensor **x**, and then marked be setting it's **.requires_grad** field to **True**. This tells PyTorch that we will later want to calculate the derivative according to it.2. We have calculated the function's result (this is the forward path).3. We have used the result of the function to initiate the back-propagation calculation by using the **.backword()** function of the result tensor.After the back-propagation step, the derivative of the function according to each one of the selected variables will be stored in the **.grad** field of each of the variables.In this case, we did not have to clear any previous calculation since we did yet run any backward calculation using these variables. ✍️ Calculate and plot the derivative of the sigmoid function $\frac{1}{1+e^{-x}}$ ###Code vals = np.arange(-10, 10, 0.1) res = np.zeros_like(vals) for i in range(len(vals)): ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% x = torch.tensor(vals[i]).float() ... res[i] = x.grad ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% fig, ax = plt.subplots() ax.plot(vals, res); ax.set_title('$\\frac{\\partial}{\\partial x}\\frac{1}{1+e^{-x}}$', fontsize=20) ax.set_xlabel('$x$'); ###Output _____no_output_____ ###Markdown Preparing the dataRepeat the preparation of the data in the same manner as in the last assignment, but this time **do not add the additional constant 1** to the features vector. ✍️ Complete the code below to load the data, split it, and extract the PCA features. ###Code from sklearn.datasets import fetch_lfw_people def load_lfw_dataset(): """ Loading the Labeled faces in the Wild dataset. Load only face of persons which appear at least 50 times in the dataset. Using: - N: The number of samples in the dataset. - H: the images' height - W: the images' width - K: The number of classes. Returns ------- x: ndarray The N x H x W array of images. y: ndarray The 1D array of length N of labels. n_classes: int The number of different classes, K. label_to_name_mapping: list A list of K strings containing the name related to each label. image_shape: list The image's shape as the list: [H, W] """ dataset = fetch_lfw_people(min_faces_per_person=50) ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% return x, y, n_classes, label_to_name_mapping, image_shape x, y, n_classes, label_to_name_mapping, image_shape = load_lfw_dataset() print('Number of images in the dataset: {}'.format(len(x))) print('Number of different persons in the dataset: {}'.format(n_classes)) print('Each images size is: {}'.format(image_shape)) _, images_per_class = np.unique(y, return_counts=True) fig, ax = plt.subplots() ax.bar(label_to_name_mapping, images_per_class) ax.set_xticklabels(label_to_name_mapping, rotation=-90); ax.set_title('Images per person') ax.set_ylabel('Number of images') fig, ax_array = plt.subplots(4, 5) for i, ax in enumerate(ax_array.flat): ax.imshow(x[i], cmap='gray') ax.set_ylabel(label_to_name_mapping[y[i]]) ax.set_yticks([]) ax.set_xticks([]) def split_dataset(x, y, train_fraction=0.6, validation_fraction=0.2): """ Split the data Parameters ---------- x: ndarray The N x H x W array of images. y: ndarray The 1D array of length N of labels. train_fraction: float The fraction of the dataset to use as the train set. validation_fraction: float The fraction of the dataset to use as the validation set. Returns ------- n_samples_train: int The number of train samples. x_train: ndarray The n_samples_train x H x W array of train images. y_train: ndarray The 1D array of length n_samples_train of train labels. n_samples_val: int The number of validation samples. x_val: ndarray The n_samples_val x H x W array of validation images. y_val: ndarray The 1D array of length n_samples_val of validation labels. n_samples_test: int The number of test samples. x_test: ndarray The n_samples_test x H x W array of test images. y_test: ndarray The 1D array of length n_samples_test of test labels. """ ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% ## Create a random generator using a fixed seed rand_gen = np.random.RandomState(0) ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% return n_samples_train, x_train, y_train, n_samples_val, x_val, y_val, n_samples_test, x_test, y_test n_samples_train, x_train, y_train, n_samples_val, x_val, y_val, n_samples_test, x_test, y_test = split_dataset(x, y) print('Number of training samples: {}'.format(n_samples_train)) print('Number of validation samples: {}'.format(n_samples_val)) print('Number of test samples: {}'.format(n_samples_test)) from sklearn.decomposition import PCA def generate_pca_object(x_train, n_pca_components=300): """ Generate a training sklearn.decomposition.PCA object. Using: - N: The number of samples in x_train. Parameters ---------- x_train: ndarray The N x H x W array of train images. n_pca_components: int The number of PCA components to use. Returns ------- pca: sklearn.decomposition.PCA The trained sklearn.decomposition.PCA object which can perform the PCA decomposition and reconstruction """ ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% return pca def extract_features(x, pca): """ Extract features from the images, which include the PCA elements and the constant 1. Using: - N: The number of samples in x. - D_PCA: The number of components. Parameters ---------- x: ndarray The N x H x W array of images (x can be either the train, validation, or test dataset). pca: sklearn.decomposition.PCA The trained sklearn.decomposition.PCA object which can perform the PCA decomposition and reconstruction Returns ------- features: ndarray The N x (D_PCA + 1) array of features. """ ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% return features pca = generate_pca_object(x_train) features_train = extract_features(x_train, pca) features_val = extract_features(x_val, pca) features_test = extract_features(x_test, pca) ## Ploting the reconstruction of the first 10 test images reconstructed_images_flat = pca.inverse_transform(features_test) reconstructed_images = reconstructed_images_flat.reshape(-1, *image_shape) fig, ax_array = plt.subplots(2, 10, figsize=(15, 4)) for i in range(10): ax_array[0][i].imshow(x_test[i], cmap='gray') ax_array[0][i].set_yticks([]) ax_array[0][i].set_xticks([]) ax_array[1][i].imshow(reconstructed_images[i], cmap='gray') ax_array[1][i].set_yticks([]) ax_array[1][i].set_xticks([]) ax_array[0][0].set_ylabel('Original') ax_array[1][0].set_ylabel('Reconstructed') fig.suptitle('Reconstructed image'); ###Output _____no_output_____ ###Markdown We will now convert all the data to tensors, transfer it to the GPU and to single precision: ###Code x_train_gpu = torch.tensor(x_train).float().cuda() features_train_gpu = torch.tensor(features_train).float().cuda() y_train_gpu = torch.tensor(y_train).cuda() x_val_gpu = torch.tensor(x_val).float().cuda() features_val_gpu = torch.tensor(features_val).float().cuda() y_val_gpu = torch.tensor(y_val).cuda() x_test_gpu = torch.tensor(x_test).float().cuda() features_test_gpu = torch.tensor(features_test).float().cuda() y_test_gpu = torch.tensor(y_test).cuda() ###Output _____no_output_____ ###Markdown Logistic RegressionWe will start by returning to the logistic regression model from last assignment.**Reminder**: We are modeling the conditional distribution of the labels as:$$p\left(y|\boldsymbol{x};\Theta\right)=\sigma\left(\Theta\boldsymbol{x},y\right)$$And our objective is to minimize the log likelihood of this probability:$$\boldsymbol{\theta}^* = \underset{\boldsymbol{\theta}}{\arg\min}-\frac{1}{N}\sum_i\log\left(\sigma\left(\Theta\boldsymbol{x}_i,y_i\right)\right)$$Where $\sigma$ is the softmax function:$$\sigma\left(\boldsymbol{q},k\right)=\frac{e^{q_k}}{\sum_{k'} e^{q_{k'}}}$$✍️ Complete the code below to define the same objective function we defined last time:$$g\left(\Theta;X,\boldsymbol{y}\right)=-\frac{1}{N}\sum_i\log\left(\sigma\left(\Theta\boldsymbol{x}_i,y_i\right)\right)$$This time, implement the function by using the two following function from torch:- [**torch.nn.functional.log_softmax**](https://pytorch.org/docs/stable/nn.htmltorch.nn.functional.log_softmax): which calculates the log of the softmax function. This function is similar to the softmax function which you have implemented in the last assignment with the addition of taking the log of the result.- [**torch.nn.functional.nll_loss**](https://pytorch.org/docs/stable/nn.htmltorch.nn.functional.nll_loss): Which calculates the negative log-likelihood of a matrix of log-probabilities, $P$, and a vector of labels, $\boldsymbol{y}$: $-\frac{1}{N}\sum_iP_{i,y_i}$ ###Code ## Define the objective function def g(theta, x, y): """ The objective function. Using: - N: The number of samples. - D: The number of features (n_pca_componens + 1). - K: The number of classes. Parameters ---------- theta: ndarray The K x D parameters matrix. x: ndarray The N x D features matrix. y: ndarray The 1D array of length N of labels. Returns ------- res: float The objective function evaluated at the given theta. """ ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% ... ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% return res ## Testing the function test_theta = torch.tensor([[1, -3, 2], [-2, 1, -1]]).float().cuda() test_x = torch.tensor([[0.1, 0.7, -0.2], [0.5, -0.2, 0.5]]).float().cuda() test_y = torch.tensor([1, 0]).cuda() print(float(g(test_theta, test_x, test_y))) ###Output _____no_output_____ ###Markdown Make sure the result you get is: $0.033094\ldots$ Doing it the PyTorch way - Using Torch.nn.Sequential and a Loss FunctionAn alternative way to define the model function, is by using the **[torch.nn.Sequential](https://pytorch.org/docs/stable/nn.htmltorch.nn.Sequential)** operator. The Senquential operator allows us to define a model by stacking together a chain of operators. This method is usefull when stacking layers of a neural-network model, as we will see later.In addition to the model, we need to also define our loss function between the output of the model and the labels. PyTorch offers a large variety of [such loss functions](https://pytorch.org/docs/stable/nn.htmlloss-functions).In the case of logistic regression, the model is simply a linear (fully connected) layer followed by a softmax operation. The loss function in our case is the minus log-likelihood function. Therefore, we can calculate the model in the following way: ###Code model = torch.nn.Sequential( torch.nn.Linear(in_features=3, out_features=2, bias=False), torch.nn.LogSoftmax(dim=1), ).cuda() loss_func = torch.nn.NLLLoss() ## Testing the function model[0].weight[:] = torch.tensor([[1, -3, 2], [-2, 1, -1]]).float().cuda() test_x = torch.tensor([[0.1, 0.7, -0.2], [0.5, -0.2, 0.5]]).float().cuda() test_y = torch.tensor([1, 0]).cuda() log_prob = model(test_x) loss = loss_func(log_prob, test_y) print(float(loss)) ###Output _____no_output_____ ###Markdown In the above code, we used have used the torch.nn.Sequential to stack together a [**torch.nn.Linear**](https://pytorch.org/docs/stable/nn.htmltorch.nn.Linear) layer and a [**torch.nn.LogSoftmax**](https://pytorch.org/docs/stable/nn.htmltorch.nn.LogSoftmax) layer. The linear layer is defined by the number of **input_features**, the number of **output_features** and a flag for optionally added a bias term.The log-softmax layer is defined by the dimension in which the softmax is calculated.Notice that we have used here [**torch.nn.LogSoftmax**](https://pytorch.org/docs/stable/nn.htmltorch.nn.LogSoftmax) to define an operator (rather then [**torch.nn.functional.log_softmax**](https://pytorch.org/docs/stable/nn.htmltorch.nn.functional.log_softmax) which is a function)In addition, notice that we have used the **.cuda** function to copy all the model parameters to the GPU.The parameters of each operator are automatically defined for each operator (which in this case, is the matrix $\Theta$ of the linear layer). They are stored as part of the model inside each of the operators. The Gradient Decent AlgorithmWe will use the following function for running the gradient descent algorithm with an L2 regularization.A few points which are worth mentioning regarding the code:1. It uses the built-in optimization object [**torch.optim.SGD**](https://pytorch.org/docs/stable/optim.htmltorch.optim.SGD) for performing the gradient step.2. We are using the weight decay option of torch.optim.SGD which is equivalet to adding an L2 regularization to the objective. ###Code def train_model(model, alpha, n_iters, x_train, y_train, x_val, y_val, llambda): ## Initialize lists to store intermidiate results for plotting objective_list_train = [] objective_list_val = [] ## Defining the loss function loss_func = torch.nn.NLLLoss() ## Defein Optimizer optimizer = torch.optim.SGD(params=model.parameters(), lr=alpha, weight_decay=2 * llambda) ## Perforing the update steps for i_iter in tqdm.tqdm_notebook(range(n_iters)): ## reseting all previous gradients optimizer.zero_grad() ## Forward path log_prob = model(x_train) log_prob = log_prob.view(log_prob.shape[0], log_prob.shape[1]) ## This is for later support for the CNNs loss = loss_func(log_prob, y_train) ## Backward path loss.backward() ## Optimization step optimizer.step() ## Store intermidiate results objective_list_train.append(float(loss)) with torch.no_grad(): ## This line is important and it tells PyTorch nit to calculate gradiants in this section log_prob = model(x_val) log_prob = log_prob.view(log_prob.shape[0], log_prob.shape[1]) ## This is for later support for the CNNs loss = loss_func(log_prob, y_val) objective_list_val.append(float(loss)) objectives_array_train = np.array(objective_list_train) objectives_array_val = np.array(objective_list_val) return objectives_array_train, objectives_array_val ###Output _____no_output_____ ###Markdown Training✍️ Complete the code below to define the logistig regression model and used the above function to train it: ###Code n_features = features_train_gpu.shape[1] ## The logistic regression model ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% model = torch.nn.Sequential( ... ).cuda() ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% ## To save you time, some optimal hyper-parameters were pre-selected. alpha = 1e-5 ## Learning rate parameter llambda = 100 ## L2 regularization parameter n_iters = 2000 objectives_array_train, objectives_array_val = train_model(model, alpha, n_iters, features_train_gpu, y_train_gpu, features_val_gpu, y_val_gpu, llambda) ## Plot the objective ## ================== fig, ax = plt.subplots() ax.plot(objectives_array_train, label='Train') ax.plot(objectives_array_val, label='Validation') ax.set_title('Otimization objective') ax.set_xlabel('Step') ax.set_xlabel('Objective') ax.set_ylim(0, 5) ax.legend(); with torch.no_grad(): y_hat_test = model(features_test_gpu).argmax(dim=1) empirical_risk_test = (y_hat_test != y_test_gpu).float().mean() print('The empirical risk (amount of misclassifications) on the test set is: {}'.format(empirical_risk_test)) ## Plot estimation ## =============== fig, ax_array = plt.subplots(4, 5) for i, ax in enumerate(ax_array.flat): ax.imshow(x_test[i], cmap='gray') ax.set_yticks([]) ax.set_xticks([]) ax.set_ylabel(label_to_name_mapping[y_hat_test[i]].split()[-1], color='black' if y_hat_test[i] == y_test[i] else 'red') fig.suptitle('Predicted Names; Incorrect Labels in Red', size=14); ###Output _____no_output_____ ###Markdown MLPNow that we have a training function and we know how to define models using PyTorch, we can start playing around with some neural-networks architectures. Specifically, we will run one MLP network and one CNN network.✍️ Complete the code below to define an MLP with 1 hidden layer of 1024 neurons and a ReLU activation function.I.e., build a network which with of the following layers:1. A fully connected (linear) layer with an input of the n_features and output of 1024.2. A ReLU layer3. A fully connected (linear) layer with an input of 1024 and output of n_classes.4. A log-softmax function.- Use [**torch.nn.ReLU**(https://pytorch.org/docs/stable/nn.htmltorch.nn.ReLU)] to define the ReLU layer. ###Code ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% model = torch.nn.Sequential( ... ).cuda() ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% ## We will use the following alpha = 1e-3 llambda = 0.1 n_iters = 20000 objectives_array_train, objectives_array_val = train_model(model, alpha, n_iters, features_train_gpu, y_train_gpu, features_val_gpu, y_val_gpu, llambda) ## Plot the objective ## ================== fig, ax = plt.subplots() ax.plot(objectives_array_train, label='Train') ax.plot(objectives_array_val, label='Validation') ax.set_title('Otimization objective') ax.set_xlabel('Step') ax.set_xlabel('Objective') ax.set_ylim(0, 5) ax.legend(); with torch.no_grad(): y_hat_test = model(features_test_gpu).argmax(dim=1) empirical_risk_test = (y_hat_test != y_test_gpu).float().mean() print('The empirical risk (amount of misclassifications) on the test set is: {}'.format(empirical_risk_test)) ###Output _____no_output_____ ###Markdown Make sure you get a test risk of about 16%. CNNAs opposed to using the PCA features as an input to our mode,l we can use the raw images directly, but for that, we will need a different architecture.✍️ Complete the code below to define a CNN which is composed of the following layers:1. A convolutional layer with a 4x4 kernel, 64 output channels, a stride of 2, and a padding of 2 on the vertical direction and 4 on the horizontal direction.2. A ReLU layer.3. A convolutional layer with a 4x4 kernel, 128 output channels, a stride of 2, and a padding of 1 in each direction.4. A ReLU layer.5. A convolutional layer with a 4x4 kernel, 256 output channels, a stride of 2, and a padding of 1 in each direction.6. A ReLU layer.7. A convolutional layer with a 4x4 kernel, 512 output channels, a stride of 2, and a padding of 1 in each direction.8. A ReLU layer.9. A convolutional layer (which is also a fully connected layer) with a 4x3 kernel and n_classes output channels (with no padding)10. A log-softmax layer.- Use [**torch.nn.MaxPool2d**(https://pytorch.org/docs/stable/nn.htmltorch.nn.MaxPool2d)] to define the max pooling layers. Oprn the documentation to check the function parameters.- Implement the fully connected layer using a convolutional layer with a kernel of size 1,- The learning rate, which was pre-selected for training the network, is a bit too high for the task and was chosen to produce reasonable results in reasonable time. Training the network with the given number of iteration should take about 5 minutes. - This architecture is very far from being optimal and was built to be simple, and with a reasonable training time. ###Code ## %%%%%%%%%%%%%%% Your code here - Begin %%%%%%%%%%%%%%% model = torch.nn.Sequential( torch.nn.Conv2d(in_channels=1, out_channels=64, kernel_size=4, stride=2, padding=(2, 4) ), ... ).cuda() ## %%%%%%%%%%%%%%% Your code here - End %%%%%%%%%%%%%%%%% alpha = 1e-3 llambda = 0.1 n_iters = 1000 objectives_array_train, objectives_array_val = train_model(model, alpha, n_iters, x_train_gpu[:, None, :, :], y_train_gpu, x_val_gpu[:, None, :, :], y_val_gpu, llambda) ## Plot the objective ## ================== fig, ax = plt.subplots() ax.plot(objectives_array_train, label='Train') ax.plot(objectives_array_val, label='Validation') ax.set_title('Otimization objective') ax.set_xlabel('Step') ax.set_xlabel('Objective') ax.set_ylim(0, 5) ax.legend(); with torch.no_grad(): y_hat_test = model(x_test_gpu[:, None, :, :]).argmax(dim=1)[:, 0, 0] empirical_risk_test = (y_hat_test != y_test_gpu).float().mean() print('The empirical risk (amount of misclassifications) on the test set is: {}'.format(empirical_risk_test)) ###Output _____no_output_____
stimuli/preprocess_neural_speaker_for_eval.ipynb
###Markdown helper funcs ###Code ## this helps to sort in human order import re def tryint(s): try: return int(s) except ValueError: return s def alphanum_key(s): """ Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [ tryint(c) for c in re.split('([0-9]+)', s) ] def sort_nicely(l): """ Sort the given list in the way that humans expect. """ l.sort(key=alphanum_key) def load_text(path): with open(path, 'r') as f: x = f.readlines() utt = x[0] # replace special tokens with question marks if '<DIA>' in utt: utt = utt.replace('<DIA>', '-') if '<UKN>' in utt: utt = utt.replace('<UKN>', '___') return utt ###Output _____no_output_____ ###Markdown setup ###Code # paths alphanum = dict(zip(range(26),string.ascii_lowercase)) conditions = ['literal','pragmatic'] upload_dir = './context_agnostic_False_rs_33' bucket_name = 'shapenet-chairs-speaker-eval' dataset_name = 'shapenet_chairs_speaker_eval' # get list of triplet dirs triplet_dirs = [i for i in os.listdir(upload_dir) if i != '.DS_Store'] triplet_dirs = [i for i in triplet_dirs if i[:7]=='triplet'] triplet_dirs = [os.path.join(upload_dir,i) for i in triplet_dirs] sort_nicely(triplet_dirs) # go through and rename the images from 0,1,2 to distractor1,distractor2,target for this_triplet in triplet_dirs: if os.path.exists(os.path.join(this_triplet,'0.png')): _shapenet_ids = np.load(os.path.join(this_triplet,'shape_net_ids.npy')) shapenet_id_dict = dict(zip(['distractor1','distractor2','target'],_shapenet_ids)) os.rename(os.path.join(this_triplet,'0.png'),os.path.join(this_triplet,'{}_distractor1.png'.format(shapenet_id_dict['distractor1']))) os.rename(os.path.join(this_triplet,'1.png'),os.path.join(this_triplet,'{}_distractor2.png'.format(shapenet_id_dict['distractor2']))) os.rename(os.path.join(this_triplet,'2.png'),os.path.join(this_triplet,'{}_target.png'.format(shapenet_id_dict['target']))) # _shapenet_ids = np.load(os.path.join(this_triplet,'shape_net_ids.npy')) # shapenet_id_dict = dict(zip(['distractor1','distractor2','target'],_shapenet_ids)) # literal_utt = load_text(os.path.join(this_triplet,'literal_utterance.txt')) # pragmatic_utt = load_text(os.path.join(this_triplet,'pragmatic_utterance.txt')) ###Output _____no_output_____ ###Markdown upload stims to s3 ###Code import boto runThis = 0 if runThis: conn = boto.connect_s3() b = conn.create_bucket(bucket_name) ### if bucket already exists, then get_bucket, else create_bucket for ind,this_triplet in enumerate(triplet_dirs): ims = [i for i in os.listdir(this_triplet) if i[-3:]=='png'] for im in ims: print ind, im k = b.new_key(im) k.set_contents_from_filename(os.path.join(this_triplet,im)) k.set_acl('public-read') ###Output _____no_output_____ ###Markdown build stimulus dictionary & upload metadata to mongo ###Code print('Generating list of triplets and their attributes...') # generate pandas dataframe with different attributes condition = [] family = [] utt = [] target = [] distractor1 = [] distractor2 = [] games = [] # this field keeps track of which games this triplet has been shown in shuffler_ind = [] ## generate permuted list of triplet indices in order to be able retrieve from triplets pseudorandomly inds = np.arange(len(conditions)*len(triplet_dirs)) shuffled_inds = np.random.RandomState(0).permutation(inds) counter = 0 for cond_ind,this_condition in enumerate(conditions): for trip_ind,this_triplet in enumerate(triplet_dirs): ims = [i for i in os.listdir(this_triplet) if i[-3:]=='png'] # extract filename target_filename = [i for i in ims if 'target' in i][0] distractor1_filename = [i for i in ims if 'distractor1' in i][0] distractor2_filename = [i for i in ims if 'distractor2' in i][0] # define url target_url = 'https://s3.amazonaws.com/{}/{}'.format(bucket_name,target_filename) distractor1_url = 'https://s3.amazonaws.com/{}/{}'.format(bucket_name,distractor1_filename) distractor2_url = 'https://s3.amazonaws.com/{}/{}'.format(bucket_name,distractor2_filename) # extract shapenetid target_shapenetid = target_filename.split('_')[0] distractor1_shapenetid = distractor1_filename.split('_')[0] distractor2_shapenetid = distractor2_filename.split('_')[0] # roll metadata into targ, d1, d2 dictionaries _target = {'filename': target_filename, 'url': target_url, 'shapenetid': target_shapenetid} _distractor1 = {'filename': distractor1_filename, 'url': distractor1_url, 'shapenetid': distractor1_shapenetid} _distractor2 = {'filename': distractor2_filename, 'url': distractor2_url, 'shapenetid': distractor2_shapenetid} # extract family and utt info this_family = this_triplet.split('/')[-1] this_utt = load_text(os.path.join(this_triplet,'{}_utterance.txt'.format(this_condition))) # append to lists to prep for dataframe condition.append(this_condition) family.append(this_family) utt.append(this_utt) target.append(_target) distractor1.append(_distractor1) distractor2.append(_distractor2) games.append([]) shuffler_ind.append(shuffled_inds[counter]) counter += 1 print('Generating pandas dataframe...') table = [condition,family,utt,target,distractor1,distractor2,games,shuffler_ind] headers = ['condition','family','utt','target','distractor1','distractor2','games','shuffler_ind'] df = pd.DataFrame(table) df = df.transpose() df.columns = headers ## save out to file print('Saving out json dictionary out to file...') stimdict = df.to_dict(orient='records') with open('{}.js'.format(dataset_name), 'w') as fout: json.dump(stimdict, fout) ### next todo is to upload this JSON to initialize the new stimulus collection print('next todo is to upload this JSON to initialize the new stimulus collection...') import json J = json.loads(open('{}.js'.format(dataset_name),mode='ru').read()) ##assert len(J)==len(all_files) print 'dataset_name: {}'.format(dataset_name) print len(J) # set vars auth = pd.read_csv('auth.txt', header = None) # this auth.txt file contains the password for the sketchloop user pswd = auth.values[0][0] user = 'sketchloop' host = 'rxdhawkins.me' ## cocolab ip address # have to fix this to be able to analyze from local conn = pm.MongoClient('mongodb://sketchloop:' + pswd + '@127.0.0.1') db = conn['stimuli'] coll = db[dataset_name] ## actually add data now to the database reallyRun = 1 if reallyRun: for (i,j) in enumerate(J): if i%100==0: print ('%d of %d' % (i,len(J))) coll.insert_one(j) ## check how many records have been retrieved a = coll.find({'shuffler_ind':{'$gte':0}}) numGames = [] for rec in a: numGames.append(len(rec['games'])) b = np.array(numGames) print np.mean(b>0) ###Output _____no_output_____
notebooks/CLEU-2020.ipynb
###Markdown IOS-XE CLEU 2020 Demo Connecting to a Device Let's define some variables: ###Code # Local CSR 1000v (running under vagrant) -- rtr1 HOST = '127.0.0.1' PORT = 2223 USER = 'vagrant' PASS = 'vagrant' ###Output _____no_output_____ ###Markdown Now let's establish a NETCONF session to that box using ncclient: ###Code from ncclient import manager from lxml import etree def pretty_print(retval): print(etree.tostring(retval.data, pretty_print=True).decode()) def my_unknown_host_cb(host, fingerprint): return True m = manager.connect(host=HOST, port=PORT, username=USER, password=PASS, allow_agent=False, look_for_keys=False, hostkey_verify=False, unknown_host_cb=my_unknown_host_cb) m ###Output _____no_output_____ ###Markdown Capabilities Let's look at the capabilities presented by the thing we've just connected to: ###Code for c in m.server_capabilities: print(c) ###Output urn:ietf:params:netconf:base:1.0 urn:ietf:params:netconf:base:1.1 urn:ietf:params:netconf:capability:writable-running:1.0 urn:ietf:params:netconf:capability:xpath:1.0 urn:ietf:params:netconf:capability:validate:1.0 urn:ietf:params:netconf:capability:validate:1.1 urn:ietf:params:netconf:capability:rollback-on-error:1.0 urn:ietf:params:netconf:capability:notification:1.0 urn:ietf:params:netconf:capability:interleave:1.0 urn:ietf:params:netconf:capability:with-defaults:1.0?basic-mode=explicit&also-supported=report-all-tagged urn:ietf:params:netconf:capability:yang-library:1.0?revision=2016-06-21&module-set-id=61de1a2313e60afe62df413a77ed9087 http://tail-f.com/ns/netconf/actions/1.0 http://tail-f.com/ns/netconf/extensions http://cisco.com/ns/cisco-xe-ietf-ip-deviation?module=cisco-xe-ietf-ip-deviation&revision=2016-08-10 http://cisco.com/ns/cisco-xe-ietf-ipv4-unicast-routing-deviation?module=cisco-xe-ietf-ipv4-unicast-routing-deviation&revision=2015-09-11 http://cisco.com/ns/cisco-xe-ietf-ipv6-unicast-routing-deviation?module=cisco-xe-ietf-ipv6-unicast-routing-deviation&revision=2015-09-11 http://cisco.com/ns/cisco-xe-ietf-ospf-deviation?module=cisco-xe-ietf-ospf-deviation&revision=2018-02-09 http://cisco.com/ns/cisco-xe-ietf-routing-deviation?module=cisco-xe-ietf-routing-deviation&revision=2016-07-09 http://cisco.com/ns/cisco-xe-openconfig-acl-deviation?module=cisco-xe-openconfig-acl-deviation&revision=2017-08-25 http://cisco.com/ns/cisco-xe-openconfig-aft-deviation?module=cisco-xe-openconfig-aft-deviation&revision=2018-12-05 http://cisco.com/ns/cisco-xe-openconfig-isis-deviation?module=cisco-xe-openconfig-isis-deviation&revision=2018-12-05 http://cisco.com/ns/cisco-xe-openconfig-lldp-deviation?module=cisco-xe-openconfig-lldp-deviation&revision=2018-07-25 http://cisco.com/ns/cisco-xe-openconfig-mpls-deviation?module=cisco-xe-openconfig-mpls-deviation&revision=2019-06-27 http://cisco.com/ns/cisco-xe-openconfig-segment-routing-deviation?module=cisco-xe-openconfig-segment-routing-deviation&revision=2018-12-05 http://cisco.com/ns/cisco-xe-routing-openconfig-system-management-deviation?module=cisco-xe-routing-openconfig-system-management-deviation&revision=2019-07-01 http://cisco.com/ns/mpls-static/devs?module=common-mpls-static-devs&revision=2015-09-11 http://cisco.com/ns/nvo/devs?module=nvo-devs&revision=2015-09-11 http://cisco.com/ns/yang/Cisco-IOS-XE-aaa?module=Cisco-IOS-XE-aaa&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-aaa-oper?module=Cisco-IOS-XE-aaa-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-acl?module=Cisco-IOS-XE-acl&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-acl-oper?module=Cisco-IOS-XE-acl-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-app-hosting-cfg?module=Cisco-IOS-XE-app-hosting-cfg&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-app-hosting-oper?module=Cisco-IOS-XE-app-hosting-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-arp?module=Cisco-IOS-XE-arp&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-arp-oper?module=Cisco-IOS-XE-arp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-atm?module=Cisco-IOS-XE-atm&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bba-group?module=Cisco-IOS-XE-bba-group&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bfd?module=Cisco-IOS-XE-bfd&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bfd-oper?module=Cisco-IOS-XE-bfd-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bgp?module=Cisco-IOS-XE-bgp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bgp-common-oper?module=Cisco-IOS-XE-bgp-common-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bgp-oper?module=Cisco-IOS-XE-bgp-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bgp-route-oper?module=Cisco-IOS-XE-bgp-route-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-bridge-domain?module=Cisco-IOS-XE-bridge-domain&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-call-home?module=Cisco-IOS-XE-call-home&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-card?module=Cisco-IOS-XE-card&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cdp?module=Cisco-IOS-XE-cdp&revision=2019-11-01&deviations=Cisco-IOS-XE-cdp-deviation http://cisco.com/ns/yang/Cisco-IOS-XE-cdp-deviation?module=Cisco-IOS-XE-cdp-deviation&revision=2019-07-23 http://cisco.com/ns/yang/Cisco-IOS-XE-cdp-oper?module=Cisco-IOS-XE-cdp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cef?module=Cisco-IOS-XE-cef&revision=2019-11-01&features=asr1k-dpi http://cisco.com/ns/yang/Cisco-IOS-XE-cellular?module=Cisco-IOS-XE-cellular&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cellular-rpc?module=Cisco-IOS-XE-cellular-rpc&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cellwan-oper?module=Cisco-IOS-XE-cellwan-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cfm-oper?module=Cisco-IOS-XE-cfm-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-checkpoint-archive-oper?module=Cisco-IOS-XE-checkpoint-archive-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-common-types?module=Cisco-IOS-XE-common-types&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-controller?module=Cisco-IOS-XE-controller&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-crypto?module=Cisco-IOS-XE-crypto&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-crypto-oper?module=Cisco-IOS-XE-crypto-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-crypto-pki-events?module=Cisco-IOS-XE-crypto-pki-events&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-crypto-pki-oper?module=Cisco-IOS-XE-crypto-pki-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cts?module=Cisco-IOS-XE-cts&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-cts-rpc?module=Cisco-IOS-XE-cts-rpc&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-dapr?module=Cisco-IOS-XE-dapr&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-device-hardware-oper?module=Cisco-IOS-XE-device-hardware-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-device-tracking?module=Cisco-IOS-XE-device-tracking&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-dhcp?module=Cisco-IOS-XE-dhcp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-dhcp-oper?module=Cisco-IOS-XE-dhcp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-diagnostics?module=Cisco-IOS-XE-diagnostics&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-dialer?module=Cisco-IOS-XE-dialer&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-dot1x?module=Cisco-IOS-XE-dot1x&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-eem?module=Cisco-IOS-XE-eem&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-efp-oper?module=Cisco-IOS-XE-efp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-eigrp?module=Cisco-IOS-XE-eigrp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-eigrp-oper?module=Cisco-IOS-XE-eigrp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-environment-oper?module=Cisco-IOS-XE-environment-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-eta?module=Cisco-IOS-XE-eta&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet?module=Cisco-IOS-XE-ethernet&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-event-history-types?module=Cisco-IOS-XE-event-history-types&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ezpm?module=Cisco-IOS-XE-ezpm&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-features?module=Cisco-IOS-XE-features&revision=2019-10-01&features=virtual-template,routing-platform,punt-num,parameter-map,multilink,l2vpn,l2,ezpm,eth-evc,esmc,efp,dhcp-border-relay,crypto http://cisco.com/ns/yang/Cisco-IOS-XE-fib-oper?module=Cisco-IOS-XE-fib-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-flow?module=Cisco-IOS-XE-flow&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-flow-monitor-oper?module=Cisco-IOS-XE-flow-monitor-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-flow-rpc?module=Cisco-IOS-XE-flow-rpc&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-fw-oper?module=Cisco-IOS-XE-fw-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-gir-oper?module=Cisco-IOS-XE-gir-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-http?module=Cisco-IOS-XE-http&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-icmp?module=Cisco-IOS-XE-icmp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-igmp?module=Cisco-IOS-XE-igmp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-im-events-oper?module=Cisco-IOS-XE-im-events-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-interface-common?module=Cisco-IOS-XE-interface-common&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper?module=Cisco-IOS-XE-interfaces-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ios-common-oper?module=Cisco-IOS-XE-ios-common-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ios-events-oper?module=Cisco-IOS-XE-ios-events-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ip-sla-oper?module=Cisco-IOS-XE-ip-sla-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ipv6-oper?module=Cisco-IOS-XE-ipv6-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-isis?module=Cisco-IOS-XE-isis&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-iwanfabric?module=Cisco-IOS-XE-iwanfabric&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-l2vpn?module=Cisco-IOS-XE-l2vpn&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-l3vpn?module=Cisco-IOS-XE-l3vpn&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-lisp?module=Cisco-IOS-XE-lisp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-lisp-oper?module=Cisco-IOS-XE-lisp-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-lldp?module=Cisco-IOS-XE-lldp&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-lldp-oper?module=Cisco-IOS-XE-lldp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mdns-gateway?module=Cisco-IOS-XE-mdns-gateway&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mdt-cfg?module=Cisco-IOS-XE-mdt-cfg&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mdt-common-defs?module=Cisco-IOS-XE-mdt-common-defs&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mdt-oper?module=Cisco-IOS-XE-mdt-oper&revision=2019-09-04 http://cisco.com/ns/yang/Cisco-IOS-XE-memory-oper?module=Cisco-IOS-XE-memory-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mld?module=Cisco-IOS-XE-mld&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mlppp-oper?module=Cisco-IOS-XE-mlppp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mpls?module=Cisco-IOS-XE-mpls&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-mpls-forwarding-oper?module=Cisco-IOS-XE-mpls-forwarding-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-multicast?module=Cisco-IOS-XE-multicast&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nam?module=Cisco-IOS-XE-nam&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nat?module=Cisco-IOS-XE-nat&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nat-oper?module=Cisco-IOS-XE-nat-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-native?module=Cisco-IOS-XE-native&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nbar?module=Cisco-IOS-XE-nbar&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nd?module=Cisco-IOS-XE-nd&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-nhrp?module=Cisco-IOS-XE-nhrp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ntp?module=Cisco-IOS-XE-ntp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ntp-oper?module=Cisco-IOS-XE-ntp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-object-group?module=Cisco-IOS-XE-object-group&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ospf?module=Cisco-IOS-XE-ospf&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ospf-oper?module=Cisco-IOS-XE-ospf-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ospfv3?module=Cisco-IOS-XE-ospfv3&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-otv?module=Cisco-IOS-XE-otv&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-pathmgr?module=Cisco-IOS-XE-pathmgr&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-perf-measure?module=Cisco-IOS-XE-perf-measure&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-pfr?module=Cisco-IOS-XE-pfr&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-platform?module=Cisco-IOS-XE-platform&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-platform-oper?module=Cisco-IOS-XE-platform-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-platform-software-oper?module=Cisco-IOS-XE-platform-software-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-pnp?module=Cisco-IOS-XE-pnp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-policy?module=Cisco-IOS-XE-policy&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ppp?module=Cisco-IOS-XE-ppp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-ppp-oper?module=Cisco-IOS-XE-ppp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-pppoe?module=Cisco-IOS-XE-pppoe&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-process-cpu-oper?module=Cisco-IOS-XE-process-cpu-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-process-memory-oper?module=Cisco-IOS-XE-process-memory-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-qfp-stats?module=Cisco-IOS-XE-qfp-stats&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-qos?module=Cisco-IOS-XE-qos&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-rip?module=Cisco-IOS-XE-rip&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-rmi-dad?module=Cisco-IOS-XE-rmi-dad&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-route-map?module=Cisco-IOS-XE-route-map&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-rpc?module=Cisco-IOS-XE-rpc&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-rsvp?module=Cisco-IOS-XE-rsvp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-sanet?module=Cisco-IOS-XE-sanet&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-segment-routing?module=Cisco-IOS-XE-segment-routing&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-service-discovery?module=Cisco-IOS-XE-service-discovery&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-service-insertion?module=Cisco-IOS-XE-service-insertion&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-service-routing?module=Cisco-IOS-XE-service-routing&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-site-manager?module=Cisco-IOS-XE-site-manager&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-sla?module=Cisco-IOS-XE-sla&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-sm-enum-types?module=Cisco-IOS-XE-sm-enum-types&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-sm-events-oper?module=Cisco-IOS-XE-sm-events-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-snmp?module=Cisco-IOS-XE-snmp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-spanning-tree?module=Cisco-IOS-XE-spanning-tree&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-switch?module=Cisco-IOS-XE-switch&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-track?module=Cisco-IOS-XE-track&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-trustsec-oper?module=Cisco-IOS-XE-trustsec-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-tunnel?module=Cisco-IOS-XE-tunnel&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-types?module=Cisco-IOS-XE-types&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-umbrella?module=Cisco-IOS-XE-umbrella&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-umbrella-oper?module=Cisco-IOS-XE-umbrella-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-umbrella-oper-dp?module=Cisco-IOS-XE-umbrella-oper-dp&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-umbrella-rpc?module=Cisco-IOS-XE-umbrella-rpc&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-utd?module=Cisco-IOS-XE-utd&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-utd-common-oper?module=Cisco-IOS-XE-utd-common-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-utd-oper?module=Cisco-IOS-XE-utd-oper&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-utd-rpc?module=Cisco-IOS-XE-utd-rpc&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vlan?module=Cisco-IOS-XE-vlan&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-voice?module=Cisco-IOS-XE-voice&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vpdn?module=Cisco-IOS-XE-vpdn&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vrf-oper?module=Cisco-IOS-XE-vrf-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vrrp?module=Cisco-IOS-XE-vrrp&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vrrp-oper?module=Cisco-IOS-XE-vrrp-oper&revision=2019-05-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vservice?module=Cisco-IOS-XE-vservice&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vtp?module=Cisco-IOS-XE-vtp&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-vxlan?module=Cisco-IOS-XE-vxlan&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-wccp?module=Cisco-IOS-XE-wccp&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-wsma?module=Cisco-IOS-XE-wsma&revision=2019-07-01 http://cisco.com/ns/yang/Cisco-IOS-XE-yang-interfaces-cfg?module=Cisco-IOS-XE-yang-interfaces-cfg&revision=2019-05-21 http://cisco.com/ns/yang/Cisco-IOS-XE-zone?module=Cisco-IOS-XE-zone&revision=2019-11-01 http://cisco.com/ns/yang/Cisco-IOS-XE-zone-rpc?module=Cisco-IOS-XE-zone-rpc&revision=2019-11-01 http://cisco.com/ns/yang/cisco-semver?module=cisco-semver&revision=2019-03-20 http://cisco.com/ns/yang/cisco-smart-license?module=cisco-smart-license&revision=2019-07-01 http://cisco.com/ns/yang/cisco-xe-bgp-policy-deviation?module=cisco-xe-openconfig-bgp-policy-deviation&revision=2017-07-24 http://cisco.com/ns/yang/cisco-xe-ietf-event-notifications-deviation?module=cisco-xe-ietf-event-notifications-deviation&revision=2018-12-03 http://cisco.com/ns/yang/cisco-xe-ietf-yang-push-deviation?module=cisco-xe-ietf-yang-push-deviation&revision=2018-12-03 http://cisco.com/ns/yang/cisco-xe-openconfig-acl-ext?module=cisco-xe-openconfig-acl-ext&revision=2017-03-30 http://cisco.com/ns/yang/cisco-xe-openconfig-bgp-deviation?module=cisco-xe-openconfig-bgp-deviation&revision=2018-05-21 http://cisco.com/ns/yang/cisco-xe-openconfig-if-ethernet-ext?module=cisco-xe-openconfig-if-ethernet-ext&revision=2017-10-30 http://cisco.com/ns/yang/cisco-xe-openconfig-interfaces-ext?module=cisco-xe-openconfig-interfaces-ext&revision=2018-07-14 http://cisco.com/ns/yang/cisco-xe-openconfig-network-instance-deviation?module=cisco-xe-openconfig-network-instance-deviation&revision=2017-02-14 http://cisco.com/ns/yang/cisco-xe-openconfig-rib-bgp-ext?module=cisco-xe-openconfig-rib-bgp-ext&revision=2016-11-30 http://cisco.com/ns/yang/cisco-xe-openconfig-system-ext?module=cisco-xe-openconfig-system-ext&revision=2018-03-21 http://cisco.com/ns/yang/cisco-xe-routing-openconfig-vlan-deviation?module=cisco-xe-routing-openconfig-vlan-deviation&revision=2018-12-12 http://cisco.com/ns/yang/cisco-xe-routing-policy-deviation?module=cisco-xe-openconfig-routing-policy-deviation&revision=2017-03-30 http://cisco.com/ns/yang/ios-xe/template?module=Cisco-IOS-XE-template&revision=2019-11-01 http://cisco.com/yang/cisco-ia?module=cisco-ia&revision=2019-07-01 http://cisco.com/yang/cisco-self-mgmt?module=cisco-self-mgmt&revision=2019-07-01 http://openconfig.net/yang/aaa?module=openconfig-aaa&revision=2017-09-18 http://openconfig.net/yang/aaa/types?module=openconfig-aaa-types&revision=2017-09-18 http://openconfig.net/yang/acl?module=openconfig-acl&revision=2017-05-26&deviations=cisco-xe-openconfig-acl-deviation http://openconfig.net/yang/aft?module=openconfig-aft&revision=2017-01-13 http://openconfig.net/yang/aft/ni?module=openconfig-aft-network-instance&revision=2017-01-13 http://openconfig.net/yang/alarms?module=openconfig-alarms&revision=2017-08-24 http://openconfig.net/yang/alarms/types?module=openconfig-alarm-types&revision=2018-11-21 http://openconfig.net/yang/bgp?module=openconfig-bgp&revision=2016-06-21 http://openconfig.net/yang/bgp-policy?module=openconfig-bgp-policy&revision=2016-06-21&deviations=cisco-xe-openconfig-bgp-policy-deviation http://openconfig.net/yang/bgp-types?module=openconfig-bgp-types&revision=2016-06-21 http://openconfig.net/yang/cisco-xe-openconfig-if-ip-deviation?module=cisco-xe-openconfig-if-ip-deviation&revision=2017-03-04 http://openconfig.net/yang/cisco-xe-openconfig-interfaces-deviation?module=cisco-xe-openconfig-interfaces-deviation&revision=2018-08-21 http://openconfig.net/yang/cisco-xe-routing-csr-openconfig-platform-deviation?module=cisco-xe-routing-csr-openconfig-platform-deviation&revision=2010-10-09 http://openconfig.net/yang/cisco-xe-routing-openconfig-system-deviation?module=cisco-xe-routing-openconfig-system-deviation&revision=2017-11-27 http://openconfig.net/yang/fib-types?module=openconfig-aft-types&revision=2017-01-13 http://openconfig.net/yang/header-fields?module=openconfig-packet-match&revision=2017-05-26 http://openconfig.net/yang/interfaces?module=openconfig-interfaces&revision=2018-01-05&deviations=cisco-xe-openconfig-interfaces-deviation http://openconfig.net/yang/interfaces/aggregate?module=openconfig-if-aggregate&revision=2018-01-05 http://openconfig.net/yang/interfaces/ethernet?module=openconfig-if-ethernet&revision=2018-01-05 http://openconfig.net/yang/interfaces/ip?module=openconfig-if-ip&revision=2018-01-05&deviations=cisco-xe-openconfig-if-ip-deviation,cisco-xe-openconfig-interfaces-deviation http://openconfig.net/yang/interfaces/ip-ext?module=openconfig-if-ip-ext&revision=2018-01-05 http://openconfig.net/yang/isis-lsdb-types?module=openconfig-isis-lsdb-types&revision=2017-01-13 http://openconfig.net/yang/isis-types?module=openconfig-isis-types&revision=2017-01-13 http://openconfig.net/yang/lacp?module=openconfig-lacp&revision=2016-05-26 http://openconfig.net/yang/ldp?module=openconfig-mpls-ldp&revision=2016-12-15 http://openconfig.net/yang/lldp?module=openconfig-lldp&revision=2016-05-16&deviations=cisco-xe-openconfig-lldp-deviation http://openconfig.net/yang/lldp/types?module=openconfig-lldp-types&revision=2016-05-16 http://openconfig.net/yang/local-routing?module=openconfig-local-routing&revision=2016-05-11 http://openconfig.net/yang/mpls?module=openconfig-mpls&revision=2016-12-15&deviations=cisco-xe-openconfig-mpls-deviation http://openconfig.net/yang/mpls-sr?module=openconfig-mpls-sr&revision=2016-12-15 http://openconfig.net/yang/mpls-types?module=openconfig-mpls-types&revision=2016-12-15 http://openconfig.net/yang/network-instance?module=openconfig-network-instance&revision=2017-01-13&deviations=cisco-xe-openconfig-aft-deviation,cisco-xe-openconfig-bgp-deviation,cisco-xe-openconfig-isis-deviation,cisco-xe-openconfig-mpls-deviation,cisco-xe-openconfig-network-instance-deviation,cisco-xe-openconfig-segment-routing-deviation http://openconfig.net/yang/network-instance-l3?module=openconfig-network-instance-l3&revision=2017-01-13 http://openconfig.net/yang/network-instance-types?module=openconfig-network-instance-types&revision=2016-12-15 http://openconfig.net/yang/openconfig-ext?module=openconfig-extensions&revision=2018-10-17 http://openconfig.net/yang/openconfig-isis?module=openconfig-isis&revision=2017-01-13 http://openconfig.net/yang/openconfig-isis-policy?module=openconfig-isis-policy&revision=2017-01-13 http://openconfig.net/yang/openconfig-types?module=openconfig-types&revision=2018-11-21 http://openconfig.net/yang/packet-match-types?module=openconfig-packet-match-types&revision=2017-05-26 http://openconfig.net/yang/platform?module=openconfig-platform&revision=2018-11-21&deviations=cisco-xe-routing-csr-openconfig-platform-deviation http://openconfig.net/yang/platform-types?module=openconfig-platform-types&revision=2018-11-21 http://openconfig.net/yang/policy-types?module=openconfig-policy-types&revision=2016-05-12 http://openconfig.net/yang/rib/bgp?module=openconfig-rib-bgp&revision=2017-03-07 http://openconfig.net/yang/rib/bgp-ext?module=openconfig-rib-bgp-ext&revision=2016-04-11 http://openconfig.net/yang/rib/bgp-types?module=openconfig-rib-bgp-types&revision=2016-04-11 http://openconfig.net/yang/routing-policy?module=openconfig-routing-policy&revision=2016-05-12&deviations=cisco-xe-openconfig-routing-policy-deviation http://openconfig.net/yang/rsvp?module=openconfig-mpls-rsvp&revision=2016-12-15 http://openconfig.net/yang/sr?module=openconfig-segment-routing&revision=2017-01-12 http://openconfig.net/yang/system?module=openconfig-system&revision=2018-07-17&deviations=cisco-xe-routing-openconfig-system-deviation,cisco-xe-routing-openconfig-system-management-deviation http://openconfig.net/yang/system/logging?module=openconfig-system-logging&revision=2017-09-18 http://openconfig.net/yang/system/management?module=openconfig-system-management&revision=2018-11-21 http://openconfig.net/yang/system/procmon?module=openconfig-procmon&revision=2017-09-18 http://openconfig.net/yang/system/terminal?module=openconfig-system-terminal&revision=2017-09-18 http://openconfig.net/yang/types/inet?module=openconfig-inet-types&revision=2017-08-24 http://openconfig.net/yang/types/yang?module=openconfig-yang-types&revision=2018-11-21 http://openconfig.net/yang/vlan?module=openconfig-vlan&revision=2016-05-26&deviations=cisco-xe-routing-openconfig-vlan-deviation http://openconfig.net/yang/vlan-types?module=openconfig-vlan-types&revision=2016-05-26 http://tail-f.com/ns/common/query?module=tailf-common-query&revision=2017-12-15 http://tail-f.com/yang/common?module=tailf-common&revision=2019-03-18 http://tail-f.com/yang/common-monitoring?module=tailf-common-monitoring&revision=2013-06-14 http://tail-f.com/yang/confd-monitoring?module=tailf-confd-monitoring&revision=2013-06-14 http://tail-f.com/yang/netconf-monitoring?module=tailf-netconf-monitoring&revision=2019-03-28 urn:cisco:params:xml:ns:yang:cisco-bridge-common?module=cisco-bridge-common&revision=2019-07-01&features=configurable-bd-mac-limit-notif,configurable-bd-mac-limit-max,configurable-bd-mac-limit-actions,configurable-bd-mac-aging-types,configurable-bd-flooding-control urn:cisco:params:xml:ns:yang:cisco-bridge-domain?module=cisco-bridge-domain&revision=2019-07-01&features=parameterized-bridge-domains,configurable-bd-storm-control,configurable-bd-static-mac,configurable-bd-snooping-profiles,configurable-bd-sh-group-number,configurable-bd-mtu,configurable-bd-member-features,configurable-bd-mac-secure,configurable-bd-mac-features,configurable-bd-mac-event-action,configurable-bd-ipsg,configurable-bd-groups,configurable-bd-flooding-mode,configurable-bd-flooding,configurable-bd-dai,clear-bridge-domain urn:cisco:params:xml:ns:yang:cisco-ethernet?module=cisco-ethernet&revision=2016-05-10 urn:cisco:params:xml:ns:yang:cisco-routing-ext?module=cisco-routing-ext&revision=2019-11-01 urn:cisco:params:xml:ns:yang:cisco-storm-control?module=cisco-storm-control&revision=2019-07-01&features=configurable-storm-control-actions urn:cisco:params:xml:ns:yang:cisco-xe-ietf-yang-push-ext?module=cisco-xe-ietf-yang-push-ext&revision=2019-03-26 urn:cisco:params:xml:ns:yang:pim?module=pim&revision=2019-07-01&features=bsr,auto-rp urn:cisco:params:xml:ns:yang:pw?module=cisco-pw&revision=2019-07-01&features=static-label-direct-config,pw-vccv,pw-tag-impose-vlan-id,pw-status-config,pw-static-oam-config,pw-short-config,pw-sequencing,pw-preferred-path,pw-port-profiles,pw-oam-refresh-config,pw-mac-withdraw-config,pw-load-balancing,pw-ipv6-source,pw-interface,pw-grouping-config,pw-class-tag-rewrite,pw-class-switchover-delay,pw-class-status,pw-class-source-ip,pw-class-flow-setting,preferred-path-peer,predictive-redundancy-config,flow-label-tlv-code17,flow-label-static-config urn:ietf:params:xml:ns:yang:c3pl-types?module=policy-types&revision=2019-07-01&features=protocol-name-support,match-wlan-user-priority-support,match-vpls-support,match-vlan-support,match-vlan-inner-support,match-src-mac-support,match-security-group-support,match-qos-group-support,match-prec-support,match-packet-length-support,match-mpls-exp-top-support,match-mpls-exp-imp-support,match-metadata-support,match-ipv6-acl-support,match-ipv6-acl-name-support,match-ipv4-acl-support,match-ipv4-acl-name-support,match-ip-rtp-support,match-input-interface-support,match-fr-dlci-support,match-fr-de-support,match-flow-record-support,match-flow-ip-support,match-dst-mac-support,match-discard-class-support,match-dei-support,match-dei-inner-support,match-cos-support,match-cos-inner-support,match-class-map-support,match-atm-vci-support,match-atm-clp-support,match-application-support urn:ietf:params:xml:ns:yang:cisco-ospf?module=cisco-ospf&revision=2019-07-01&features=graceful-shutdown,flood-reduction,database-filter urn:ietf:params:xml:ns:yang:cisco-policy?module=cisco-policy&revision=2019-07-01 urn:ietf:params:xml:ns:yang:cisco-policy-filters?module=cisco-policy-filters&revision=2019-07-01 urn:ietf:params:xml:ns:yang:cisco-policy-target?module=cisco-policy-target&revision=2019-07-01 urn:ietf:params:xml:ns:yang:common-mpls-static?module=common-mpls-static&revision=2019-07-01&deviations=common-mpls-static-devs urn:ietf:params:xml:ns:yang:common-mpls-types?module=common-mpls-types&revision=2019-07-01 urn:ietf:params:xml:ns:yang:iana-crypt-hash?module=iana-crypt-hash&revision=2014-08-06&features=crypt-hash-sha-512,crypt-hash-sha-256,crypt-hash-md5 urn:ietf:params:xml:ns:yang:iana-if-type?module=iana-if-type&revision=2014-05-08 urn:ietf:params:xml:ns:yang:ietf-diffserv-action?module=ietf-diffserv-action&revision=2015-04-07&features=priority-rate-burst-support,hierarchial-policy-support,aqm-red-support urn:ietf:params:xml:ns:yang:ietf-diffserv-classifier?module=ietf-diffserv-classifier&revision=2015-04-07&features=policy-inline-classifier-config urn:ietf:params:xml:ns:yang:ietf-diffserv-policy?module=ietf-diffserv-policy&revision=2015-04-07&features=policy-template-support,hierarchial-policy-support urn:ietf:params:xml:ns:yang:ietf-diffserv-target?module=ietf-diffserv-target&revision=2015-04-07&features=target-inline-policy-config urn:ietf:params:xml:ns:yang:ietf-event-notifications?module=ietf-event-notifications&revision=2016-10-27&features=json,configured-subscriptions&deviations=cisco-xe-ietf-event-notifications-deviation,cisco-xe-ietf-yang-push-deviation urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&revision=2013-07-15 urn:ietf:params:xml:ns:yang:ietf-interfaces?module=ietf-interfaces&revision=2014-05-08&features=pre-provisioning,if-mib,arbitrary-names urn:ietf:params:xml:ns:yang:ietf-interfaces-ext?module=ietf-interfaces-ext urn:ietf:params:xml:ns:yang:ietf-ip?module=ietf-ip&revision=2014-06-16&features=ipv6-privacy-autoconf,ipv4-non-contiguous-netmasks&deviations=cisco-xe-ietf-ip-deviation urn:ietf:params:xml:ns:yang:ietf-ipv4-unicast-routing?module=ietf-ipv4-unicast-routing&revision=2015-05-25&deviations=cisco-xe-ietf-ipv4-unicast-routing-deviation urn:ietf:params:xml:ns:yang:ietf-ipv6-unicast-routing?module=ietf-ipv6-unicast-routing&revision=2015-05-25&deviations=cisco-xe-ietf-ipv6-unicast-routing-deviation urn:ietf:params:xml:ns:yang:ietf-key-chain?module=ietf-key-chain&revision=2015-02-24&features=independent-send-accept-lifetime,hex-key-string,accept-tolerance urn:ietf:params:xml:ns:yang:ietf-netconf-acm?module=ietf-netconf-acm&revision=2012-02-22 urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04 urn:ietf:params:xml:ns:yang:ietf-netconf-notifications?module=ietf-netconf-notifications&revision=2012-02-06 urn:ietf:params:xml:ns:yang:ietf-ospf?module=ietf-ospf&revision=2015-03-09&features=ttl-security,te-rid,router-id,remote-lfa,prefix-suppression,ospfv3-authentication-ipsec,nsr,node-flag,multi-topology,multi-area-adj,mtu-ignore,max-lsa,max-ecmp,lls,lfa,ldp-igp-sync,ldp-igp-autoconfig,interface-inheritance,instance-inheritance,graceful-restart,fast-reroute,demand-circuit,bfd,auto-cost,area-inheritance,admin-control&deviations=cisco-xe-ietf-ospf-deviation urn:ietf:params:xml:ns:yang:ietf-restconf-monitoring?module=ietf-restconf-monitoring&revision=2017-01-26 urn:ietf:params:xml:ns:yang:ietf-routing?module=ietf-routing&revision=2015-05-25&features=router-id,multiple-ribs&deviations=cisco-xe-ietf-routing-deviation urn:ietf:params:xml:ns:yang:ietf-yang-library?module=ietf-yang-library&revision=2016-06-21 urn:ietf:params:xml:ns:yang:ietf-yang-push?module=ietf-yang-push&revision=2016-10-28&features=on-change&deviations=cisco-xe-ietf-yang-push-deviation urn:ietf:params:xml:ns:yang:ietf-yang-smiv2?module=ietf-yang-smiv2&revision=2012-06-22 urn:ietf:params:xml:ns:yang:ietf-yang-types?module=ietf-yang-types&revision=2013-07-15 urn:ietf:params:xml:ns:yang:nvo?module=nvo&revision=2019-07-01&deviations=nvo-devs urn:ietf:params:xml:ns:yang:policy-attr?module=policy-attr&revision=2019-07-01 urn:ietf:params:xml:ns:yang:smiv2:ATM-FORUM-TC-MIB?module=ATM-FORUM-TC-MIB urn:ietf:params:xml:ns:yang:smiv2:ATM-MIB?module=ATM-MIB&revision=1998-10-19 urn:ietf:params:xml:ns:yang:smiv2:ATM-TC-MIB?module=ATM-TC-MIB&revision=1998-10-19 urn:ietf:params:xml:ns:yang:smiv2:BGP4-MIB?module=BGP4-MIB&revision=1994-05-05 urn:ietf:params:xml:ns:yang:smiv2:BRIDGE-MIB?module=BRIDGE-MIB&revision=2005-09-19 urn:ietf:params:xml:ns:yang:smiv2:CISCO-AAA-SERVER-MIB?module=CISCO-AAA-SERVER-MIB&revision=2003-11-17 urn:ietf:params:xml:ns:yang:smiv2:CISCO-AAA-SESSION-MIB?module=CISCO-AAA-SESSION-MIB&revision=2006-03-21 urn:ietf:params:xml:ns:yang:smiv2:CISCO-AAL5-MIB?module=CISCO-AAL5-MIB&revision=2003-09-22 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ATM-EXT-MIB?module=CISCO-ATM-EXT-MIB&revision=2003-01-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ATM-PVCTRAP-EXTN-MIB?module=CISCO-ATM-PVCTRAP-EXTN-MIB&revision=2003-01-20 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ATM-QOS-MIB?module=CISCO-ATM-QOS-MIB&revision=2002-06-10 urn:ietf:params:xml:ns:yang:smiv2:CISCO-BGP-POLICY-ACCOUNTING-MIB?module=CISCO-BGP-POLICY-ACCOUNTING-MIB&revision=2002-07-26 urn:ietf:params:xml:ns:yang:smiv2:CISCO-BGP4-MIB?module=CISCO-BGP4-MIB&revision=2010-09-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-BULK-FILE-MIB?module=CISCO-BULK-FILE-MIB&revision=2002-06-10 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CBP-TARGET-MIB?module=CISCO-CBP-TARGET-MIB&revision=2006-05-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CBP-TARGET-TC-MIB?module=CISCO-CBP-TARGET-TC-MIB&revision=2006-03-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CBP-TC-MIB?module=CISCO-CBP-TC-MIB&revision=2008-06-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CDP-MIB?module=CISCO-CDP-MIB&revision=2005-03-21 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CEF-MIB?module=CISCO-CEF-MIB&revision=2006-01-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CEF-TC?module=CISCO-CEF-TC&revision=2005-09-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CONFIG-COPY-MIB?module=CISCO-CONFIG-COPY-MIB&revision=2005-04-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CONFIG-MAN-MIB?module=CISCO-CONFIG-MAN-MIB&revision=2007-04-27 urn:ietf:params:xml:ns:yang:smiv2:CISCO-CONTEXT-MAPPING-MIB?module=CISCO-CONTEXT-MAPPING-MIB&revision=2008-11-22 urn:ietf:params:xml:ns:yang:smiv2:CISCO-DATA-COLLECTION-MIB?module=CISCO-DATA-COLLECTION-MIB&revision=2002-10-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-DIAL-CONTROL-MIB?module=CISCO-DIAL-CONTROL-MIB&revision=2005-05-26 urn:ietf:params:xml:ns:yang:smiv2:CISCO-DOT3-OAM-MIB?module=CISCO-DOT3-OAM-MIB&revision=2006-05-31 urn:ietf:params:xml:ns:yang:smiv2:CISCO-DYNAMIC-TEMPLATE-MIB?module=CISCO-DYNAMIC-TEMPLATE-MIB&revision=2007-09-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-DYNAMIC-TEMPLATE-TC-MIB?module=CISCO-DYNAMIC-TEMPLATE-TC-MIB&revision=2012-01-27 urn:ietf:params:xml:ns:yang:smiv2:CISCO-EIGRP-MIB?module=CISCO-EIGRP-MIB&revision=2004-11-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-EMBEDDED-EVENT-MGR-MIB?module=CISCO-EMBEDDED-EVENT-MGR-MIB&revision=2006-11-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENHANCED-MEMPOOL-MIB?module=CISCO-ENHANCED-MEMPOOL-MIB&revision=2008-12-05 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-ALARM-MIB?module=CISCO-ENTITY-ALARM-MIB&revision=1999-07-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-EXT-MIB?module=CISCO-ENTITY-EXT-MIB&revision=2008-11-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-FRU-CONTROL-MIB?module=CISCO-ENTITY-FRU-CONTROL-MIB&revision=2013-08-19 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-QFP-MIB?module=CISCO-ENTITY-QFP-MIB&revision=2014-06-18 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-SENSOR-MIB?module=CISCO-ENTITY-SENSOR-MIB&revision=2015-01-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ENTITY-VENDORTYPE-OID-MIB?module=CISCO-ENTITY-VENDORTYPE-OID-MIB&revision=2014-12-09 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ETHER-CFM-MIB?module=CISCO-ETHER-CFM-MIB&revision=2004-12-28 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ETHERLIKE-EXT-MIB?module=CISCO-ETHERLIKE-EXT-MIB&revision=2010-06-04 urn:ietf:params:xml:ns:yang:smiv2:CISCO-FIREWALL-TC?module=CISCO-FIREWALL-TC&revision=2006-03-03 urn:ietf:params:xml:ns:yang:smiv2:CISCO-FLASH-MIB?module=CISCO-FLASH-MIB&revision=2013-08-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-FTP-CLIENT-MIB?module=CISCO-FTP-CLIENT-MIB&revision=2006-03-31 urn:ietf:params:xml:ns:yang:smiv2:CISCO-HSRP-EXT-MIB?module=CISCO-HSRP-EXT-MIB&revision=2010-09-02 urn:ietf:params:xml:ns:yang:smiv2:CISCO-HSRP-MIB?module=CISCO-HSRP-MIB&revision=2010-09-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-ATM2-PVCTRAP-MIB?module=CISCO-IETF-ATM2-PVCTRAP-MIB&revision=1998-02-03 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-ATM2-PVCTRAP-MIB-EXTN?module=CISCO-IETF-ATM2-PVCTRAP-MIB-EXTN&revision=2000-07-11 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-BFD-MIB?module=CISCO-IETF-BFD-MIB&revision=2011-04-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-FRR-MIB?module=CISCO-IETF-FRR-MIB&revision=2008-04-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-ISIS-MIB?module=CISCO-IETF-ISIS-MIB&revision=2005-08-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-MPLS-ID-STD-03-MIB?module=CISCO-IETF-MPLS-ID-STD-03-MIB&revision=2012-06-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-MPLS-TE-EXT-STD-03-MIB?module=CISCO-IETF-MPLS-TE-EXT-STD-03-MIB&revision=2012-06-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-ATM-MIB?module=CISCO-IETF-PW-ATM-MIB&revision=2005-04-19 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-ENET-MIB?module=CISCO-IETF-PW-ENET-MIB&revision=2002-09-22 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-MIB?module=CISCO-IETF-PW-MIB&revision=2004-03-17 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-MPLS-MIB?module=CISCO-IETF-PW-MPLS-MIB&revision=2003-02-26 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-TC-MIB?module=CISCO-IETF-PW-TC-MIB&revision=2006-07-21 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IETF-PW-TDM-MIB?module=CISCO-IETF-PW-TDM-MIB&revision=2006-07-21 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IF-EXTENSION-MIB?module=CISCO-IF-EXTENSION-MIB&revision=2013-03-13 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IGMP-FILTER-MIB?module=CISCO-IGMP-FILTER-MIB&revision=2005-11-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IMAGE-LICENSE-MGMT-MIB?module=CISCO-IMAGE-LICENSE-MGMT-MIB&revision=2007-10-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IMAGE-MIB?module=CISCO-IMAGE-MIB&revision=1995-08-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IP-LOCAL-POOL-MIB?module=CISCO-IP-LOCAL-POOL-MIB&revision=2007-11-12 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IP-TAP-MIB?module=CISCO-IP-TAP-MIB&revision=2004-03-11 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IP-URPF-MIB?module=CISCO-IP-URPF-MIB&revision=2011-12-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPMROUTE-MIB?module=CISCO-IPMROUTE-MIB&revision=2005-03-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSEC-FLOW-MONITOR-MIB?module=CISCO-IPSEC-FLOW-MONITOR-MIB&revision=2007-10-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSEC-MIB?module=CISCO-IPSEC-MIB&revision=2000-08-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSEC-POLICY-MAP-MIB?module=CISCO-IPSEC-POLICY-MAP-MIB&revision=2000-08-17 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSLA-AUTOMEASURE-MIB?module=CISCO-IPSLA-AUTOMEASURE-MIB&revision=2007-06-13 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSLA-ECHO-MIB?module=CISCO-IPSLA-ECHO-MIB&revision=2007-08-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSLA-JITTER-MIB?module=CISCO-IPSLA-JITTER-MIB&revision=2007-07-24 urn:ietf:params:xml:ns:yang:smiv2:CISCO-IPSLA-TC-MIB?module=CISCO-IPSLA-TC-MIB&revision=2007-03-23 urn:ietf:params:xml:ns:yang:smiv2:CISCO-LICENSE-MGMT-MIB?module=CISCO-LICENSE-MGMT-MIB&revision=2012-04-19 urn:ietf:params:xml:ns:yang:smiv2:CISCO-MEDIA-GATEWAY-MIB?module=CISCO-MEDIA-GATEWAY-MIB&revision=2009-02-25 urn:ietf:params:xml:ns:yang:smiv2:CISCO-MPLS-LSR-EXT-STD-MIB?module=CISCO-MPLS-LSR-EXT-STD-MIB&revision=2012-04-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-MPLS-TC-EXT-STD-MIB?module=CISCO-MPLS-TC-EXT-STD-MIB&revision=2012-02-22 urn:ietf:params:xml:ns:yang:smiv2:CISCO-NBAR-PROTOCOL-DISCOVERY-MIB?module=CISCO-NBAR-PROTOCOL-DISCOVERY-MIB&revision=2002-08-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-NETSYNC-MIB?module=CISCO-NETSYNC-MIB&revision=2010-10-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-NTP-MIB?module=CISCO-NTP-MIB&revision=2006-07-31 urn:ietf:params:xml:ns:yang:smiv2:CISCO-OSPF-MIB?module=CISCO-OSPF-MIB&revision=2003-07-18 urn:ietf:params:xml:ns:yang:smiv2:CISCO-OSPF-TRAP-MIB?module=CISCO-OSPF-TRAP-MIB&revision=2003-07-18 urn:ietf:params:xml:ns:yang:smiv2:CISCO-PIM-MIB?module=CISCO-PIM-MIB&revision=2000-11-02 urn:ietf:params:xml:ns:yang:smiv2:CISCO-PING-MIB?module=CISCO-PING-MIB&revision=2001-08-28 urn:ietf:params:xml:ns:yang:smiv2:CISCO-PROCESS-MIB?module=CISCO-PROCESS-MIB&revision=2011-06-23 urn:ietf:params:xml:ns:yang:smiv2:CISCO-PRODUCTS-MIB?module=CISCO-PRODUCTS-MIB&revision=2014-11-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-PTP-MIB?module=CISCO-PTP-MIB&revision=2011-01-28 urn:ietf:params:xml:ns:yang:smiv2:CISCO-QOS-PIB-MIB?module=CISCO-QOS-PIB-MIB&revision=2007-08-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-RADIUS-EXT-MIB?module=CISCO-RADIUS-EXT-MIB&revision=2010-05-25 urn:ietf:params:xml:ns:yang:smiv2:CISCO-RF-MIB?module=CISCO-RF-MIB&revision=2005-09-01 urn:ietf:params:xml:ns:yang:smiv2:CISCO-RTTMON-MIB?module=CISCO-RTTMON-MIB&revision=2012-08-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-RTTMON-TC-MIB?module=CISCO-RTTMON-TC-MIB&revision=2012-05-25 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SESS-BORDER-CTRLR-CALL-STATS-MIB?module=CISCO-SESS-BORDER-CTRLR-CALL-STATS-MIB&revision=2010-09-03 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SESS-BORDER-CTRLR-STATS-MIB?module=CISCO-SESS-BORDER-CTRLR-STATS-MIB&revision=2010-09-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SIP-UA-MIB?module=CISCO-SIP-UA-MIB&revision=2004-02-19 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SMI?module=CISCO-SMI&revision=2012-08-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SONET-MIB?module=CISCO-SONET-MIB&revision=2003-03-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-ST-TC?module=CISCO-ST-TC&revision=2012-08-08 urn:ietf:params:xml:ns:yang:smiv2:CISCO-STP-EXTENSIONS-MIB?module=CISCO-STP-EXTENSIONS-MIB&revision=2013-03-07 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SUBSCRIBER-IDENTITY-TC-MIB?module=CISCO-SUBSCRIBER-IDENTITY-TC-MIB&revision=2011-12-23 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SUBSCRIBER-SESSION-MIB?module=CISCO-SUBSCRIBER-SESSION-MIB&revision=2012-08-08 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SUBSCRIBER-SESSION-TC-MIB?module=CISCO-SUBSCRIBER-SESSION-TC-MIB&revision=2012-01-27 urn:ietf:params:xml:ns:yang:smiv2:CISCO-SYSLOG-MIB?module=CISCO-SYSLOG-MIB&revision=2005-12-03 urn:ietf:params:xml:ns:yang:smiv2:CISCO-TAP2-MIB?module=CISCO-TAP2-MIB&revision=2009-11-06 urn:ietf:params:xml:ns:yang:smiv2:CISCO-TC?module=CISCO-TC&revision=2011-11-11 urn:ietf:params:xml:ns:yang:smiv2:CISCO-UBE-MIB?module=CISCO-UBE-MIB&revision=2010-11-29 urn:ietf:params:xml:ns:yang:smiv2:CISCO-UNIFIED-FIREWALL-MIB?module=CISCO-UNIFIED-FIREWALL-MIB&revision=2005-09-22 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB?module=CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB&revision=2013-07-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VLAN-MEMBERSHIP-MIB?module=CISCO-VLAN-MEMBERSHIP-MIB&revision=2007-12-14 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VOICE-COMMON-DIAL-CONTROL-MIB?module=CISCO-VOICE-COMMON-DIAL-CONTROL-MIB&revision=2010-06-30 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VOICE-DIAL-CONTROL-MIB?module=CISCO-VOICE-DIAL-CONTROL-MIB&revision=2012-05-15 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VOICE-DNIS-MIB?module=CISCO-VOICE-DNIS-MIB&revision=2002-05-01 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VPDN-MGMT-MIB?module=CISCO-VPDN-MGMT-MIB&revision=2009-06-16 urn:ietf:params:xml:ns:yang:smiv2:CISCO-VTP-MIB?module=CISCO-VTP-MIB&revision=2013-10-14 urn:ietf:params:xml:ns:yang:smiv2:DIAL-CONTROL-MIB?module=DIAL-CONTROL-MIB&revision=1996-09-23 urn:ietf:params:xml:ns:yang:smiv2:DIFFSERV-DSCP-TC?module=DIFFSERV-DSCP-TC&revision=2002-05-09 urn:ietf:params:xml:ns:yang:smiv2:DIFFSERV-MIB?module=DIFFSERV-MIB&revision=2002-02-07 urn:ietf:params:xml:ns:yang:smiv2:DISMAN-EVENT-MIB?module=DISMAN-EVENT-MIB&revision=2000-10-16 urn:ietf:params:xml:ns:yang:smiv2:DISMAN-EXPRESSION-MIB?module=DISMAN-EXPRESSION-MIB&revision=2000-10-16 urn:ietf:params:xml:ns:yang:smiv2:DRAFT-MSDP-MIB?module=DRAFT-MSDP-MIB&revision=1999-12-16 urn:ietf:params:xml:ns:yang:smiv2:DS1-MIB?module=DS1-MIB&revision=1998-08-01 urn:ietf:params:xml:ns:yang:smiv2:DS3-MIB?module=DS3-MIB&revision=1998-08-01 urn:ietf:params:xml:ns:yang:smiv2:ENTITY-MIB?module=ENTITY-MIB&revision=2005-08-10 urn:ietf:params:xml:ns:yang:smiv2:ENTITY-SENSOR-MIB?module=ENTITY-SENSOR-MIB&revision=2002-12-16 urn:ietf:params:xml:ns:yang:smiv2:ENTITY-STATE-MIB?module=ENTITY-STATE-MIB&revision=2005-11-22 urn:ietf:params:xml:ns:yang:smiv2:ENTITY-STATE-TC-MIB?module=ENTITY-STATE-TC-MIB&revision=2005-11-22 urn:ietf:params:xml:ns:yang:smiv2:ETHER-WIS?module=ETHER-WIS&revision=2003-09-19 urn:ietf:params:xml:ns:yang:smiv2:EXPRESSION-MIB?module=EXPRESSION-MIB&revision=2005-11-24 urn:ietf:params:xml:ns:yang:smiv2:EtherLike-MIB?module=EtherLike-MIB&revision=2003-09-19 urn:ietf:params:xml:ns:yang:smiv2:FRAME-RELAY-DTE-MIB?module=FRAME-RELAY-DTE-MIB&revision=1997-05-01 urn:ietf:params:xml:ns:yang:smiv2:HCNUM-TC?module=HCNUM-TC&revision=2000-06-08 urn:ietf:params:xml:ns:yang:smiv2:IANA-ADDRESS-FAMILY-NUMBERS-MIB?module=IANA-ADDRESS-FAMILY-NUMBERS-MIB&revision=2000-09-08 urn:ietf:params:xml:ns:yang:smiv2:IANA-RTPROTO-MIB?module=IANA-RTPROTO-MIB&revision=2000-09-26 urn:ietf:params:xml:ns:yang:smiv2:IANAifType-MIB?module=IANAifType-MIB&revision=2006-03-31 urn:ietf:params:xml:ns:yang:smiv2:IEEE8021-TC-MIB?module=IEEE8021-TC-MIB&revision=2008-10-15 urn:ietf:params:xml:ns:yang:smiv2:IF-MIB?module=IF-MIB&revision=2000-06-14 urn:ietf:params:xml:ns:yang:smiv2:IGMP-STD-MIB?module=IGMP-STD-MIB&revision=2000-09-28 urn:ietf:params:xml:ns:yang:smiv2:INET-ADDRESS-MIB?module=INET-ADDRESS-MIB&revision=2005-02-04 urn:ietf:params:xml:ns:yang:smiv2:INT-SERV-MIB?module=INT-SERV-MIB&revision=1997-10-03 urn:ietf:params:xml:ns:yang:smiv2:INTEGRATED-SERVICES-MIB?module=INTEGRATED-SERVICES-MIB&revision=1995-11-03 urn:ietf:params:xml:ns:yang:smiv2:IP-FORWARD-MIB?module=IP-FORWARD-MIB&revision=1996-09-19 urn:ietf:params:xml:ns:yang:smiv2:IP-MIB?module=IP-MIB&revision=2006-02-02 urn:ietf:params:xml:ns:yang:smiv2:IPMROUTE-STD-MIB?module=IPMROUTE-STD-MIB&revision=2000-09-22 urn:ietf:params:xml:ns:yang:smiv2:IPV6-FLOW-LABEL-MIB?module=IPV6-FLOW-LABEL-MIB&revision=2003-08-28 urn:ietf:params:xml:ns:yang:smiv2:LLDP-MIB?module=LLDP-MIB&revision=2005-05-06 urn:ietf:params:xml:ns:yang:smiv2:MPLS-L3VPN-STD-MIB?module=MPLS-L3VPN-STD-MIB&revision=2006-01-23 urn:ietf:params:xml:ns:yang:smiv2:MPLS-LDP-GENERIC-STD-MIB?module=MPLS-LDP-GENERIC-STD-MIB&revision=2004-06-03 urn:ietf:params:xml:ns:yang:smiv2:MPLS-LDP-STD-MIB?module=MPLS-LDP-STD-MIB&revision=2004-06-03 urn:ietf:params:xml:ns:yang:smiv2:MPLS-LSR-STD-MIB?module=MPLS-LSR-STD-MIB&revision=2004-06-03 urn:ietf:params:xml:ns:yang:smiv2:MPLS-TC-MIB?module=MPLS-TC-MIB&revision=2001-01-04 urn:ietf:params:xml:ns:yang:smiv2:MPLS-TC-STD-MIB?module=MPLS-TC-STD-MIB&revision=2004-06-03 urn:ietf:params:xml:ns:yang:smiv2:MPLS-TE-STD-MIB?module=MPLS-TE-STD-MIB&revision=2004-06-03 urn:ietf:params:xml:ns:yang:smiv2:MPLS-VPN-MIB?module=MPLS-VPN-MIB&revision=2001-10-15 urn:ietf:params:xml:ns:yang:smiv2:NHRP-MIB?module=NHRP-MIB&revision=1999-08-26 urn:ietf:params:xml:ns:yang:smiv2:NOTIFICATION-LOG-MIB?module=NOTIFICATION-LOG-MIB&revision=2000-11-27 urn:ietf:params:xml:ns:yang:smiv2:OSPF-MIB?module=OSPF-MIB&revision=2006-11-10 urn:ietf:params:xml:ns:yang:smiv2:OSPF-TRAP-MIB?module=OSPF-TRAP-MIB&revision=2006-11-10 urn:ietf:params:xml:ns:yang:smiv2:P-BRIDGE-MIB?module=P-BRIDGE-MIB&revision=2006-01-09 urn:ietf:params:xml:ns:yang:smiv2:PIM-MIB?module=PIM-MIB&revision=2000-09-28 urn:ietf:params:xml:ns:yang:smiv2:PerfHist-TC-MIB?module=PerfHist-TC-MIB&revision=1998-11-07 urn:ietf:params:xml:ns:yang:smiv2:Q-BRIDGE-MIB?module=Q-BRIDGE-MIB&revision=2006-01-09 urn:ietf:params:xml:ns:yang:smiv2:RFC-1212?module=RFC-1212 urn:ietf:params:xml:ns:yang:smiv2:RFC-1215?module=RFC-1215 urn:ietf:params:xml:ns:yang:smiv2:RFC1155-SMI?module=RFC1155-SMI urn:ietf:params:xml:ns:yang:smiv2:RFC1213-MIB?module=RFC1213-MIB urn:ietf:params:xml:ns:yang:smiv2:RFC1315-MIB?module=RFC1315-MIB urn:ietf:params:xml:ns:yang:smiv2:RMON-MIB?module=RMON-MIB&revision=2000-05-11 urn:ietf:params:xml:ns:yang:smiv2:RMON2-MIB?module=RMON2-MIB&revision=1996-05-27 urn:ietf:params:xml:ns:yang:smiv2:RSVP-MIB?module=RSVP-MIB&revision=1998-08-25 urn:ietf:params:xml:ns:yang:smiv2:SNMP-FRAMEWORK-MIB?module=SNMP-FRAMEWORK-MIB&revision=2002-10-14 urn:ietf:params:xml:ns:yang:smiv2:SNMP-PROXY-MIB?module=SNMP-PROXY-MIB&revision=2002-10-14 urn:ietf:params:xml:ns:yang:smiv2:SNMP-TARGET-MIB?module=SNMP-TARGET-MIB&revision=1998-08-04 urn:ietf:params:xml:ns:yang:smiv2:SNMPv2-MIB?module=SNMPv2-MIB&revision=2002-10-16 urn:ietf:params:xml:ns:yang:smiv2:SNMPv2-TC?module=SNMPv2-TC urn:ietf:params:xml:ns:yang:smiv2:SONET-MIB?module=SONET-MIB&revision=2003-08-11 urn:ietf:params:xml:ns:yang:smiv2:TCP-MIB?module=TCP-MIB&revision=2005-02-18 urn:ietf:params:xml:ns:yang:smiv2:TOKEN-RING-RMON-MIB?module=TOKEN-RING-RMON-MIB urn:ietf:params:xml:ns:yang:smiv2:TOKENRING-MIB?module=TOKENRING-MIB&revision=1994-10-23 urn:ietf:params:xml:ns:yang:smiv2:TUNNEL-MIB?module=TUNNEL-MIB&revision=2005-05-16 urn:ietf:params:xml:ns:yang:smiv2:UDP-MIB?module=UDP-MIB&revision=2005-05-20 urn:ietf:params:xml:ns:yang:smiv2:VPN-TC-STD-MIB?module=VPN-TC-STD-MIB&revision=2005-11-15 urn:ietf:params:xml:ns:netconf:base:1.0?module=ietf-netconf&revision=2011-06-01 urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults?module=ietf-netconf-with-defaults&revision=2011-06-01 urn:ietf:params:netconf:capability:notification:1.1 ###Markdown Ok, that's a bit messy, so let's tidy it up a bit and look, initially, at all the base netconf capabilities: ###Code nc_caps = [c for c in m.server_capabilities if c.startswith('urn:ietf:params:netconf') and "smiv2" not in c] for c in nc_caps: print(c) ###Output urn:ietf:params:netconf:base:1.0 urn:ietf:params:netconf:base:1.1 urn:ietf:params:netconf:capability:writable-running:1.0 urn:ietf:params:netconf:capability:xpath:1.0 urn:ietf:params:netconf:capability:validate:1.0 urn:ietf:params:netconf:capability:validate:1.1 urn:ietf:params:netconf:capability:rollback-on-error:1.0 urn:ietf:params:netconf:capability:notification:1.0 urn:ietf:params:netconf:capability:interleave:1.0 urn:ietf:params:netconf:capability:with-defaults:1.0?basic-mode=explicit&also-supported=report-all-tagged urn:ietf:params:netconf:capability:yang-library:1.0?revision=2016-06-21&module-set-id=61de1a2313e60afe62df413a77ed9087 ###Markdown And now let's look at the capabilities that are related to model support: ###Code import re for c in m.server_capabilities: model = re.search('module=([^&]*)&', c) if model is not None: print("{}".format(model.group(1))) revision = re.search('revision=([0-9]{4}-[0-9]{2}-[0-9]{2})', c) if revision is not None: print(" revision = {}".format(revision.group(1))) deviations = re.search('deviations=([a-zA-Z0-9\-,]+)($|&)',c) if deviations is not None: print(" deviations = {}".format(deviations.group(1))) features = re.search('features=([a-zA-Z0-9\-,]+)($|&)',c) if features is not None: print(" features = {}".format(features.group(1))) ###Output _____no_output_____ ###Markdown SchemaLet's take a look at playing with schema. First, we can try downloading them, picking one of the modules we got capabilities for. ###Code # SCHEMA_TO_GET = 'openconfig-interfaces' # SCHEMA_TO_GET = 'Cisco-IOS-XE-native' # SCHEMA_TO_GET = 'Cisco-IOS-XE-features' SCHEMA_TO_GET = 'Cisco-IOS-XE-interfaces-oper' c = m.get_schema(SCHEMA_TO_GET) print(c.data) ###Output module Cisco-IOS-XE-interfaces-oper { yang-version 1; namespace "http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"; prefix interfaces-ios-xe-oper; import ietf-inet-types { prefix inet; } import ietf-yang-types { prefix yang; } import cisco-semver { prefix cisco-semver; } organization "Cisco Systems, Inc."; contact "Cisco Systems, Inc. Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 Tel: +1 1800 553-NETS E-mail: [email protected]"; description "This module contains a collection of YANG definitions for monitoring the interfaces in a Network Element. Copyright (c) 2016-2019 by Cisco Systems, Inc. All rights reserved."; revision 2019-11-01 { description "- Added media type to interface - Added more interface speed values"; reference "3.3.0"; cisco-semver:module-version "3.3.0"; } revision 2019-05-01 { description "- Added ethernet error counters. - Added semantic version"; reference "3.2.0"; cisco-semver:module-version "3.2.0"; } revision 2018-10-29 { description "Cleaned up spelling errors in descriptions."; reference "3.1.0"; cisco-semver:module-version "3.1.0"; } revision 2018-06-29 { description "- Add switching interface speed values - Add synchronous serial interface model"; reference "3.0.0"; cisco-semver:module-version "3.0.0"; } revision 2018-02-01 { description "IPv6 addresses"; reference "2.0.0"; cisco-semver:module-version "2.0.0"; } revision 2017-10-10 { description "Initial revision"; reference "1.0.0"; cisco-semver:module-version "1.0.0"; } typedef qos-match-type { type enumeration { enum "qos-match-dscp" { value 0; } enum "qos-match-src-ip" { value 1; } enum "qos-match-dst-ip" { value 2; } enum "qos-match-src-port" { value 3; } enum "qos-match-dst-port" { value 4; } enum "qos-match-proto" { value 5; } } description "QOS match type"; } typedef thresh-unit { type enumeration { enum "thresh-units-default" { value 0; } enum "thresh-units-bytes" { value 1; } enum "thresh-units-sec" { value 2; } enum "thresh-units-packets" { value 3; } enum "thresh-units-cells" { value 4; } enum "thresh-units-percent" { value 5; } } description "Units of threshold"; } typedef qos-direction { type enumeration { enum "qos-inbound" { value 0; description "Direction of traffic coming into the network entry"; } enum "qos-outbound" { value 1; description "Direction of traffic going out of the network entry"; } } description "QoS direction indication"; } typedef aggregation-type { type enumeration { enum "lag-off" { value 0; description "LAG mode is off"; } enum "lag-auto" { value 1; description "LAG mode is auto"; } enum "lag-active" { value 2; description "LAG mode is active"; } enum "lag-passive" { value 3; description "LAG mode is passive"; } } description "Type to define the lag-type, i.e., how the LAG is defined and managed"; } typedef intf-state { type enumeration { enum "if-state-unknown" { value 0; } enum "if-state-up" { value 1; } enum "if-state-down" { value 2; } enum "if-state-test" { value 3; } } description "The desired state of the interface. This leaf has the same read semantics as ifAdminStatus. Reference: RFC 2863: The Interfaces Group MIB - ifAdminStatus"; } typedef ether-duplex { type enumeration { enum "full-duplex" { value 0; } enum "half-duplex" { value 1; } enum "auto-duplex" { value 2; } enum "unknown-duplex" { value 3; } } description "The duplex setting of the interface"; } typedef ether-speed { type enumeration { enum "speed-10mb" { value 0; } enum "speed-100mb" { value 1; } enum "speed-1gb" { value 2; } enum "speed-10gb" { value 3; } enum "speed-25gb" { value 4; } enum "speed-40gb" { value 5; } enum "speed-50gb" { value 6; } enum "speed-100gb" { value 7; } enum "speed-unknown" { value 8; } enum "speed-auto" { value 9; } enum "speed-2500mb" { value 10; description "Ethernet Speed 2500 MBPS"; } enum "speed-5gb" { value 11; description "Ethernet Speed 5 GBPS"; } enum "speed-400gb" { value 12; description "Ethernet Speed 400 GBPS"; } } description "The speed setting of the interface"; } typedef oper-state { type enumeration { enum "if-oper-state-invalid" { value 0; } enum "if-oper-state-ready" { value 1; } enum "if-oper-state-no-pass" { value 2; } enum "if-oper-state-test" { value 3; } enum "if-oper-state-unknown" { value 4; } enum "if-oper-state-dormant" { value 5; } enum "if-oper-state-not-present" { value 6; } enum "if-oper-state-lower-layer-down" { value 7; } } description "The current operational state of the interface. This leaf has the same semantics as ifOperStatus. Reference: RFC 2863: The Interfaces Group MIB - ifOperStatus"; } typedef ietf-intf-type { type enumeration { enum "iana-iftype-other" { value 1; } enum "iana-iftype-regular1822" { value 2; } enum "iana-iftype-hdh1822" { value 3; } enum "iana-iftype-ddnx25" { value 4; } enum "iana-iftype-rfc877x25" { value 5; } enum "iana-iftype-ethernet-csmacd" { value 6; } enum "iana-iftype-iso88023-csmacd" { value 7; } enum "iana-iftype-iso88024-tokenbus" { value 8; } enum "iana-iftype-iso88025-tokenring" { value 9; } enum "iana-iftype-iso88026-man" { value 10; } enum "iana-iftype-starlan" { value 11; } enum "iana-iftype-proteon10mbit" { value 12; } enum "iana-iftype-proteon80mbit" { value 13; } enum "iana-iftype-hyperchannel" { value 14; } enum "iana-iftype-fddi" { value 15; } enum "iana-iftype-lapb" { value 16; } enum "iana-iftype-sdlc" { value 17; } enum "iana-iftype-ds1" { value 18; } enum "iana-iftype-e1" { value 19; } enum "iana-iftype-basicisdn" { value 20; } enum "iana-iftype-primaryisdn" { value 21; } enum "iana-iftype-prop-p2p-serial" { value 22; } enum "iana-iftype-ppp" { value 23; } enum "iana-iftype-sw-loopback" { value 24; } enum "iana-iftype-eon" { value 25; } enum "iana-iftype-ethernet3mbit" { value 26; } enum "iana-iftype-nsip" { value 27; } enum "iana-iftype-slip" { value 28; } enum "iana-iftype-ultra" { value 29; } enum "iana-iftype-ds3" { value 30; } enum "iana-iftype-sip" { value 31; } enum "iana-iftype-framerelay" { value 32; } enum "iana-iftype-rs232" { value 33; } enum "iana-iftype-para" { value 34; } enum "iana-iftype-arcnet" { value 35; } enum "iana-iftype-arcnetplus" { value 36; } enum "iana-iftype-atm" { value 37; } enum "iana-iftype-miox25" { value 38; } enum "iana-iftype-sonet" { value 39; } enum "iana-iftype-x25ple" { value 40; } enum "iana-iftype-iso88022-llc" { value 41; } enum "iana-iftype-localtalk" { value 42; } enum "iana-iftype-smdsdxi" { value 43; } enum "iana-iftype-framerelay-service" { value 44; } enum "iana-iftype-v35" { value 45; } enum "iana-iftype-hssi" { value 46; } enum "iana-iftype-hippi" { value 47; } enum "iana-iftype-modem" { value 48; } enum "iana-iftype-aal5" { value 49; } enum "iana-iftype-sonetpath" { value 50; } enum "iana-iftype-sonetvt" { value 51; } enum "iana-iftype-smdsicip" { value 52; } enum "iana-iftype-propvirtual" { value 53; } enum "iana-iftype-propmultiplexor" { value 54; } enum "iana-iftype-ieee80212" { value 55; } enum "iana-iftype-fiberchannel" { value 56; } enum "iana-iftype-hippi-interface" { value 57; } enum "iana-iftype-framerelay-interconnect" { value 58; } enum "iana-iftype-aflane8023" { value 59; } enum "iana-iftype-aflane8025" { value 60; } enum "iana-iftype-cctemul" { value 61; } enum "iana-iftype-fastether" { value 62; } enum "iana-iftype-isdn" { value 63; } enum "iana-iftype-v11" { value 64; } enum "iana-iftype-v36" { value 65; } enum "iana-iftype-g703at64k" { value 66; } enum "iana-iftype-g703at2mb" { value 67; } enum "iana-iftype-qllc" { value 68; } enum "iana-iftype-fastetherfx" { value 69; } enum "iana-iftype-channel" { value 70; } enum "iana-iftype-ieee80211" { value 71; } enum "iana-iftype-ibm370parchan" { value 72; } enum "iana-iftype-escon" { value 73; } enum "iana-iftype-dlsw" { value 74; } enum "iana-iftype-isdns" { value 75; } enum "iana-iftype-isdnu" { value 76; } enum "iana-iftype-lapd" { value 77; } enum "iana-iftype-ipswitch" { value 78; } enum "iana-iftype-rsrb" { value 79; } enum "iana-iftype-atmlogical" { value 80; } enum "iana-iftype-ds0" { value 81; } enum "iana-iftype-ds0bundle" { value 82; } enum "iana-iftype-bsc" { value 83; } enum "iana-iftype-async" { value 84; } enum "iana-iftype-cnr" { value 85; } enum "iana-iftype-iso88025-dtr" { value 86; } enum "iana-iftype-eplrs" { value 87; } enum "iana-iftype-arap" { value 88; } enum "iana-iftype-propcnls" { value 89; } enum "iana-iftype-hostpad" { value 90; } enum "iana-iftype-termpad" { value 91; } enum "iana-iftype-framerelay-mpi" { value 92; } enum "iana-iftype-x213" { value 93; } enum "iana-iftype-adsl" { value 94; } enum "iana-iftype-radsl" { value 95; } enum "iana-iftype-sdsl" { value 96; } enum "iana-iftype-vdsl" { value 97; } enum "iana-iftype-iso88025-crfpint" { value 98; } enum "iana-iftype-myrinet" { value 99; } enum "iana-iftype-voiceem" { value 100; } enum "iana-iftype-voicefxo" { value 101; } enum "iana-iftype-voicefxs" { value 102; } enum "iana-iftype-voiceencap" { value 103; } enum "iana-iftype-voip" { value 104; } enum "iana-iftype-atmdxi" { value 105; } enum "iana-iftype-atmfuni" { value 106; } enum "iana-iftype-atmima" { value 107; } enum "iana-iftype-ppp-multilinkbundle" { value 108; } enum "iana-iftype-ipovercdlc" { value 109; } enum "iana-iftype-ipoverclaw" { value 110; } enum "iana-iftype-stack2stack" { value 111; } enum "iana-iftype-virtualipaddress" { value 112; } enum "iana-iftype-mpc" { value 113; } enum "iana-iftype-ipoveratm" { value 114; } enum "iana-iftype-iso88025-fiber" { value 115; } enum "iana-iftype-tdlc" { value 116; } enum "iana-iftype-gige" { value 117; } enum "iana-iftype-hdlc" { value 118; } enum "iana-iftype-lapf" { value 119; } enum "iana-iftype-v37" { value 120; } enum "iana-iftype-x25mlp" { value 121; } enum "iana-iftype-x25huntgroup" { value 122; } enum "iana-iftype-transphdlc" { value 123; } enum "iana-iftype-interleave" { value 124; } enum "iana-iftype-fast" { value 125; } enum "iana-iftype-ip" { value 126; } enum "iana-iftype-docs-cable-maclayer" { value 127; } enum "iana-iftype-docs-cable-downstream" { value 128; } enum "iana-iftype-docs-cable-upstream" { value 129; } enum "iana-iftype-a12mppswitch" { value 130; } enum "iana-iftype-tunnel" { value 131; } enum "iana-iftype-coffee" { value 132; } enum "iana-iftype-ces" { value 133; } enum "iana-iftype-atmsubinterface" { value 134; } enum "iana-iftype-l2vlan" { value 135; } enum "iana-iftype-l3ipvlan" { value 136; } enum "iana-iftype-l3ipxvlan" { value 137; } enum "iana-iftype-digital-powerline" { value 138; } enum "iana-iftype-media-mailoverip" { value 139; } enum "iana-iftype-dtm" { value 140; } enum "iana-iftype-dcn" { value 141; } enum "iana-iftype-ipforward" { value 142; } enum "iana-iftype-msdsl" { value 143; } enum "iana-iftype-ieee1394" { value 144; } enum "iana-iftype-gsn" { value 145; } enum "iana-iftype-dvbrcc-maclayer" { value 146; } enum "iana-iftype-dvbrcc-downstream" { value 147; } enum "iana-iftype-dvbrcc-upstream" { value 148; } enum "iana-iftype-atmvirtual" { value 149; } enum "iana-iftype-mplstunnel" { value 150; } enum "iana-iftype-srp" { value 151; } enum "iana-iftype-voiceoveratm" { value 152; } enum "iana-iftype-voiceoverframerelay" { value 153; } enum "iana-iftype-idsl" { value 154; } enum "iana-iftype-compositelink" { value 155; } enum "iana-iftype-ss7siglink" { value 156; } enum "iana-iftype-propwireless-p2p" { value 157; } enum "iana-iftype-frforward" { value 158; } enum "iana-iftype-rfc1483" { value 159; } enum "iana-iftype-usb" { value 160; } enum "iana-iftype-ieee8023-adlag" { value 161; } enum "iana-iftype-bgppolicy-accounting" { value 162; } enum "iana-iftype-frf16mfrbundle" { value 163; } enum "iana-iftype-h323gatekeeper" { value 164; } enum "iana-iftype-h323proxy" { value 165; } enum "iana-iftype-mpls" { value 166; } enum "iana-iftype-mfsiglink" { value 167; } enum "iana-iftype-hdsl2" { value 168; } enum "iana-iftype-shdsl" { value 169; } enum "iana-iftype-ds1fdl" { value 170; } enum "iana-iftype-pos" { value 171; } enum "iana-iftype-dvbasiin" { value 172; } enum "iana-iftype-dvbasiout" { value 173; } enum "iana-iftype-plc" { value 174; } enum "iana-iftype-nfas" { value 175; } enum "iana-iftype-tr008" { value 176; } enum "iana-iftype-gr303rdt" { value 177; } enum "iana-iftype-gr303idt" { value 178; } enum "iana-iftype-isup" { value 179; } enum "iana-iftype-prop-docs-wireless-maclayer" { value 180; } enum "iana-iftype-prop-docs-wireless-downstream" { value 181; } enum "iana-iftype-prop-docs-wireless-upstream" { value 182; } enum "iana-iftype-hiperlan2" { value 183; } enum "iana-iftype-prop-bwap2mp" { value 184; } enum "iana-iftype-sonetoverheadchannel" { value 185; } enum "iana-iftype-digital-wrapperoverheadchannel" { value 186; } enum "iana-iftype-aal2" { value 187; } enum "iana-iftype-radiomac" { value 188; } enum "iana-iftype-atmradio" { value 189; } enum "iana-iftype-imt" { value 190; } enum "iana-iftype-mvl" { value 191; } enum "iana-iftype-reachhdsl" { value 192; } enum "iana-iftype-frdlciendpt" { value 193; } enum "iana-iftype-atmvciendpt" { value 194; } enum "iana-iftype-opticalchannel" { value 195; } enum "iana-iftype-opticaltransport" { value 196; } enum "iana-iftype-propatm" { value 197; } enum "iana-iftype-voiceovercable" { value 198; } enum "iana-iftype-infiniband" { value 199; } enum "iana-iftype-telink" { value 200; } enum "iana-iftype-q2931" { value 201; } enum "iana-iftype-virtualatg" { value 202; } enum "iana-iftype-siptg" { value 203; } enum "iana-iftype-sipsig" { value 204; } enum "iana-iftype-docs-cable-upstreamchannel" { value 205; } enum "iana-iftype-econet" { value 206; } enum "iana-iftype-pon155" { value 207; } enum "iana-iftype-pon622" { value 208; } enum "iana-iftype-bridge-if" { value 209; } enum "iana-iftype-linegroup" { value 210; } enum "iana-iftype-voiceemfgd" { value 211; } enum "iana-iftype-voiceefgdeana" { value 212; } enum "iana-iftype-voicedid" { value 213; } enum "iana-iftype-mpegtransport" { value 214; } enum "iana-iftype-sixtofour" { value 215; } enum "iana-iftype-gtp" { value 216; } enum "iana-iftype-pdnetherloop1" { value 217; } enum "iana-iftype-pdnetherloop2" { value 218; } enum "iana-iftype-opticalchannel-group" { value 219; } enum "iana-iftype-homepna" { value 220; } enum "iana-iftype-gfp" { value 221; } enum "iana-iftype-ciscoislvlan" { value 222; } enum "iana-iftype-actelismetaloop" { value 223; } enum "iana-iftype-fciplink" { value 224; } enum "iana-iftype-rpr" { value 225; } enum "iana-iftype-qam" { value 226; } enum "iana-iftype-lmp" { value 227; } enum "iana-iftype-cblvectastar" { value 228; } enum "iana-iftype-docs-cable-mcmts-downtream" { value 229; } enum "iana-iftype-adsl2" { value 230; } enum "iana-iftype-macseccontrolledif" { value 231; } enum "iana-iftype-macsecuncontrolledif" { value 232; } enum "iana-iftype-aviciopticalether" { value 233; } enum "iana-iftype-atmbond" { value 234; } enum "iana-iftype-voicefgdos" { value 235; } enum "iana-iftype-mocaversion1" { value 236; } enum "iana-iftype-ieee80216-wman" { value 237; } enum "iana-iftype-adsl2plus" { value 238; } enum "iana-iftype-dvbrcsmaclayer" { value 239; } enum "iana-iftype-dvbtdm" { value 240; } enum "iana-iftype-dvbrcstdma" { value 241; } enum "iana-iftype-x86laps" { value 242; } enum "iana-iftype-wwanpp" { value 243; } enum "iana-iftype-wwanpp2" { value 244; } enum "iana-iftype-voiceebs" { value 245; } enum "iana-iftype-ifpwtype" { value 246; } enum "iana-iftype-ilan" { value 247; } enum "iana-iftype-pip" { value 248; } enum "iana-iftype-aluelp" { value 249; } enum "iana-iftype-gpon" { value 250; } enum "iana-iftype-vdsl2" { value 251; } enum "iana-iftype-capwapdot11-profile" { value 252; } enum "iana-iftype-capwapdot11-bss" { value 253; } enum "iana-iftype-capwapwtp-virtualradio" { value 254; } enum "iana-iftype-bits" { value 255; } enum "iana-iftype-docs-cable-upstreamrfport" { value 256; } enum "iana-iftype-cable-downstreamrfport" { value 257; } enum "iana-iftype-vmware-virtualnic" { value 258; } enum "iana-iftype-ieee802154" { value 259; } enum "iana-iftype-otnodu" { value 260; } enum "iana-iftype-otnotu" { value 261; } enum "iana-iftype-ifvfitype" { value 262; } enum "iana-iftype-g9981" { value 263; } enum "iana-iftype-g9982" { value 264; } enum "iana-iftype-g9983" { value 265; } enum "iana-iftype-aluepon" { value 266; } enum "iana-iftype-aluepon-onu" { value 267; } enum "iana-iftype-aluepon-physicaluni" { value 268; } enum "iana-iftype-aluepon-logicalink" { value 269; } enum "iana-iftype-alugpon-onu" { value 270; } enum "iana-iftype-alugpon-physicaluni" { value 271; } enum "iana-iftype-vmwarenicteam" { value 272; } enum "iana-iftype-docs-ofdm-downstream" { value 277; } enum "iana-iftype-docs-ofdma-upstream" { value 278; } enum "iana-iftype-gfast" { value 279; } enum "iana-iftype-sdci" { value 280; } enum "iana-iftype-xbox-wireless" { value 281; } enum "iana-iftype-fastdsl" { value 282; } } description "IANAifType This data type is used as the syntax of the ifType object in the (updated) definition of MIB-II's ifTable"; } typedef media-type-class { type enumeration { enum "ether-media-type-none" { value 0; } enum "ether-media-type-aui" { value 1; } enum "ether-media-type-10baset" { value 2; } enum "ether-media-type-nothing-here" { value 3; } enum "ether-media-type-rj45" { value 4; } enum "ether-media-type-mii" { value 5; } enum "ether-media-type-auto-select" { value 6; } enum "ether-media-type-epif-utp" { value 7; } enum "ether-media-type-epif-fx" { value 8; } enum "ether-media-type-gpif-lx" { value 9; } enum "ether-media-type-gpif-sx" { value 10; } enum "ether-media-type-parallel" { value 11; } enum "ether-media-type-serial10km" { value 12; } enum "ether-media-type-vsr300m" { value 13; } enum "ether-media-type-metrowdm50km" { value 14; } enum "ether-media-type-not-connected" { value 15; } enum "ether-media-type-port-missing" { value 16; } enum "ether-media-type-gbic-missing" { value 17; } enum "ether-media-type-feip-mmf-st" { value 18; } enum "ether-media-type-feip-mmf-sc" { value 19; } enum "ether-media-type-1000basecx-gigstack" { value 20; } enum "ether-media-type-serial40km" { value 21; } enum "ether-media-type-serial50km" { value 22; } enum "ether-media-type-unapproved" { value 23; } enum "ether-media-type-unsupported" { value 24; } enum "ether-media-type-bad-eeprom" { value 25; } enum "ether-media-type-gbic" { value 26; } enum "ether-media-type-sfp" { value 27; } enum "ether-media-type-xenpak" { value 28; } enum "ether-media-type-100base-fx" { value 29; } enum "ether-media-type-100base-tx" { value 30; } enum "ether-media-type-rj21" { value 31; } enum "ether-media-type-100mtrj-fx" { value 32; } enum "ether-media-type-100mtrj-lx" { value 33; } enum "ether-media-type-internal" { value 34; } enum "ether-media-type-1000baset" { value 35; } enum "ether-media-type-gpif-zx" { value 36; } enum "ether-media-type-1000base-cwdm-1470" { value 37; } enum "ether-media-type-1000base-cwdm-1490" { value 38; } enum "ether-media-type-1000base-cwdm-1510" { value 39; } enum "ether-media-type-1000base-cwdm-1530" { value 40; } enum "ether-media-type-1000base-cwdm-1550" { value 41; } enum "ether-media-type-1000base-cwdm-1570" { value 42; } enum "ether-media-type-1000base-cwdm-1590" { value 43; } enum "ether-media-type-1000base-cwdm-1610" { value 44; } enum "ether-media-type-1000base-dwdm-6061" { value 45; } enum "ether-media-type-1000base-dwdm-5979" { value 46; } enum "ether-media-type-1000base-dwdm-5898" { value 47; } enum "ether-media-type-1000base-dwdm-5817" { value 48; } enum "ether-media-type-1000base-dwdm-5655" { value 49; } enum "ether-media-type-1000base-dwdm-5575" { value 50; } enum "ether-media-type-1000base-dwdm-5494" { value 51; } enum "ether-media-type-1000base-dwdm-5413" { value 52; } enum "ether-media-type-1000base-dwdm-5252" { value 53; } enum "ether-media-type-1000base-dwdm-5172" { value 54; } enum "ether-media-type-1000base-dwdm-5092" { value 55; } enum "ether-media-type-1000base-dwdm-5012" { value 56; } enum "ether-media-type-1000base-dwdm-4851" { value 57; } enum "ether-media-type-1000base-dwdm-4772" { value 58; } enum "ether-media-type-1000base-dwdm-4692" { value 59; } enum "ether-media-type-1000base-dwdm-4612" { value 60; } enum "ether-media-type-1000base-dwdm-4453" { value 61; } enum "ether-media-type-1000base-dwdm-4373" { value 62; } enum "ether-media-type-1000base-dwdm-4294" { value 63; } enum "ether-media-type-1000base-dwdm-4214" { value 64; } enum "ether-media-type-1000base-dwdm-4056" { value 65; } enum "ether-media-type-1000base-dwdm-3977" { value 66; } enum "ether-media-type-1000base-dwdm-3898" { value 67; } enum "ether-media-type-1000base-dwdm-3819" { value 68; } enum "ether-media-type-1000base-dwdm-3661" { value 69; } enum "ether-media-type-1000base-dwdm-3582" { value 70; } enum "ether-media-type-1000base-dwdm-3504" { value 71; } enum "ether-media-type-1000base-dwdm-3425" { value 72; } enum "ether-media-type-1000base-dwdm-3268" { value 73; } enum "ether-media-type-1000base-dwdm-3190" { value 74; } enum "ether-media-type-1000base-dwdm-3112" { value 75; } enum "ether-media-type-1000base-dwdm-3033" { value 76; } enum "ether-media-type-1000base-dwdm-6141" { value 77; } enum "ether-media-type-1000base-dwdm-5736" { value 78; } enum "ether-media-type-1000base-dwdm-5332" { value 79; } enum "ether-media-type-1000base-dwdm-4931" { value 80; } enum "ether-media-type-1000base-dwdm-4532" { value 81; } enum "ether-media-type-1000base-dwdm-4134" { value 82; } enum "ether-media-type-1000base-dwdm-3739" { value 83; } enum "ether-media-type-1000base-dwdm-3346" { value 84; } enum "ether-media-type-unknown" { value 85; } enum "ether-media-type-1000base-bx10u" { value 86; } enum "ether-media-type-1000base-bx10d" { value 87; } enum "ether-media-type-1000base-tdwdm" { value 88; } enum "ether-media-type-10gbase-sr" { value 89; } enum "ether-media-type-10gbase-sr-sw" { value 90; } enum "ether-media-type-sfp-plus" { value 91; } enum "ether-media-type-gpif-ex" { value 92; } enum "ether-media-type-100base-bx10u" { value 93; } enum "ether-media-type-100base-bx10d" { value 94; } enum "ether-media-type-10gbase-dwdm-3033" { value 95; } enum "ether-media-type-10gbase-dwdm-3112" { value 96; } enum "ether-media-type-10gbase-dwdm-3190" { value 97; } enum "ether-media-type-10gbase-dwdm-3268" { value 98; } enum "ether-media-type-10gbase-dwdm-3425" { value 99; } enum "ether-media-type-10gbase-dwdm-3504" { value 100; } enum "ether-media-type-10gbase-dwdm-3582" { value 101; } enum "ether-media-type-10gbase-dwdm-3661" { value 102; } enum "ether-media-type-10gbase-dwdm-3819" { value 103; } enum "ether-media-type-10gbase-dwdm-3898" { value 104; } enum "ether-media-type-10gbase-dwdm-3977" { value 105; } enum "ether-media-type-10gbase-dwdm-4056" { value 106; } enum "ether-media-type-10gbase-dwdm-4214" { value 107; } enum "ether-media-type-10gbase-dwdm-4294" { value 108; } enum "ether-media-type-10gbase-dwdm-4373" { value 109; } enum "ether-media-type-10gbase-dwdm-4453" { value 110; } enum "ether-media-type-10gbase-dwdm-4612" { value 111; } enum "ether-media-type-10gbase-dwdm-4692" { value 112; } enum "ether-media-type-10gbase-dwdm-4772" { value 113; } enum "ether-media-type-10gbase-dwdm-4851" { value 114; } enum "ether-media-type-10gbase-dwdm-5012" { value 115; } enum "ether-media-type-10gbase-dwdm-5092" { value 116; } enum "ether-media-type-10gbase-dwdm-5172" { value 117; } enum "ether-media-type-10gbase-dwdm-5252" { value 118; } enum "ether-media-type-10gbase-dwdm-5413" { value 119; } enum "ether-media-type-10gbase-dwdm-5494" { value 120; } enum "ether-media-type-10gbase-dwdm-5575" { value 121; } enum "ether-media-type-10gbase-dwdm-5655" { value 122; } enum "ether-media-type-10gbase-dwdm-5817" { value 123; } enum "ether-media-type-10gbase-dwdm-5898" { value 124; } enum "ether-media-type-10gbase-dwdm-5979" { value 125; } enum "ether-media-type-10gbase-dwdm-6061" { value 126; } enum "ether-media-type-10gbase-tdwdm" { value 127; } enum "ether-media-type-100base-zx" { value 128; } enum "ether-media-type-100base-ex" { value 129; } enum "ether-media-type-sfp-plus-10ge-sr" { value 130; } enum "ether-media-type-sfp-plus-10ge-lr" { value 131; } enum "ether-media-type-sfp-plus-10ge-lrm" { value 132; } enum "ether-media-type-sfp-plus-10ge-er" { value 133; } enum "ether-media-type-10gbase-cu1m" { value 134; } enum "ether-media-type-10gbase-cu3m" { value 135; } enum "ether-media-type-10gbase-cu5m" { value 136; } enum "ether-media-type-10gbase-cu7m" { value 137; } enum "ether-media-type-10gbase-cwdm-1470" { value 138; } enum "ether-media-type-10gbase-cwdm-1490" { value 139; } enum "ether-media-type-10gbase-cwdm-1510" { value 140; } enum "ether-media-type-10gbase-cwdm-1530" { value 141; } enum "ether-media-type-10gbase-cwdm-1550" { value 142; } enum "ether-media-type-10gbase-cwdm-1570" { value 143; } enum "ether-media-type-10gbase-cwdm-1590" { value 144; } enum "ether-media-type-10gbase-cwdm-1610" { value 145; } enum "ether-media-type-100base-lx" { value 146; } enum "ether-media-type-100lc-bx10-d" { value 147; } enum "ether-media-type-100lc-bx10-u" { value 148; } enum "ether-media-type-100base-bx10-d" { value 149; } enum "ether-media-type-100base-bx10-u" { value 150; } enum "ether-media-type-x2" { value 151; } enum "ether-media-type-x2-missing" { value 152; } enum "ether-media-type-xg-draught" { value 153; } enum "ether-media-type-1g-10gbaset" { value 154; } enum "ether-media-type-xg-arcadia" { value 155; } enum "ether-media-type-sfp-plus-10ge-zr" { value 156; } enum "ether-media-type-sfpp-10g-dwdm-61-41" { value 157; } enum "ether-media-type-sfpp-10g-dwdm-60-61" { value 158; } enum "ether-media-type-sfpp-10g-dwdm-59-79" { value 159; } enum "ether-media-type-sfpp-10g-dwdm-58-98" { value 160; } enum "ether-media-type-sfpp-10g-dwdm-58-17" { value 161; } enum "ether-media-type-sfpp-10g-dwdm-57-36" { value 162; } enum "ether-media-type-sfpp-10g-dwdm-56-55" { value 163; } enum "ether-media-type-sfpp-10g-dwdm-55-75" { value 164; } enum "ether-media-type-sfpp-10g-dwdm-54-94" { value 165; } enum "ether-media-type-sfpp-10g-dwdm-54-13" { value 166; } enum "ether-media-type-sfpp-10g-dwdm-53-33" { value 167; } enum "ether-media-type-sfpp-10g-dwdm-52-52" { value 168; } enum "ether-media-type-sfpp-10g-dwdm-51-72" { value 169; } enum "ether-media-type-sfpp-10g-dwdm-50-92" { value 170; } enum "ether-media-type-sfpp-10g-dwdm-50-12" { value 171; } enum "ether-media-type-sfpp-10g-dwdm-49-32" { value 172; } enum "ether-media-type-sfpp-10g-dwdm-48-51" { value 173; } enum "ether-media-type-sfpp-10g-dwdm-47-72" { value 174; } enum "ether-media-type-sfpp-10g-dwdm-46-92" { value 175; } enum "ether-media-type-sfpp-10g-dwdm-46-12" { value 176; } enum "ether-media-type-sfpp-10g-dwdm-45-32" { value 177; } enum "ether-media-type-sfpp-10g-dwdm-44-53" { value 178; } enum "ether-media-type-sfpp-10g-dwdm-43-73" { value 179; } enum "ether-media-type-sfpp-10g-dwdm-42-94" { value 180; } enum "ether-media-type-sfpp-10g-dwdm-42-14" { value 181; } enum "ether-media-type-sfpp-10g-dwdm-41-35" { value 182; } enum "ether-media-type-sfpp-10g-dwdm-40-56" { value 183; } enum "ether-media-type-sfpp-10g-dwdm-39-77" { value 184; } enum "ether-media-type-sfpp-10g-dwdm-38-98" { value 185; } enum "ether-media-type-sfpp-10g-dwdm-38-19" { value 186; } enum "ether-media-type-sfpp-10g-dwdm-37-40" { value 187; } enum "ether-media-type-sfpp-10g-dwdm-36-61" { value 188; } enum "ether-media-type-sfpp-10g-dwdm-35-82" { value 189; } enum "ether-media-type-sfpp-10g-dwdm-35-04" { value 190; } enum "ether-media-type-sfpp-10g-dwdm-34-25" { value 191; } enum "ether-media-type-sfpp-10g-dwdm-33-47" { value 192; } enum "ether-media-type-sfpp-10g-dwdm-32-68" { value 193; } enum "ether-media-type-sfpp-10g-dwdm-31-90" { value 194; } enum "ether-media-type-sfpp-10g-dwdm-31-12" { value 195; } enum "ether-media-type-sfpp-10g-dwdm-30-33" { value 196; } enum "ether-media-type-1000base-bx40da" { value 197; } enum "ether-media-type-1000base-bx80u" { value 198; } enum "ether-media-type-1000base-bx80d" { value 199; } enum "ether-media-type-1000base-bx40u" { value 200; } enum "ether-media-type-1000base-bx40d" { value 201; } enum "ether-media-type-sfp-plus-10ge-bxd" { value 202; } enum "ether-media-type-sfp-plus-10ge-bxu" { value 203; } enum "ether-media-type-sfp-plus-10ge-bx40d" { value 204; } enum "ether-media-type-sfp-plus-10ge-bx40u" { value 205; } enum "ether-media-type-sfpp-10g-cwdm-14-70" { value 206; } enum "ether-media-type-sfpp-10g-cwdm-14-90" { value 207; } enum "ether-media-type-sfpp-10g-cwdm-15-10" { value 208; } enum "ether-media-type-sfpp-10g-cwdm-15-30" { value 209; } enum "ether-media-type-sfpp-10g-cwdm-15-50" { value 210; } enum "ether-media-type-sfpp-10g-cwdm-15-70" { value 211; } enum "ether-media-type-sfpp-10g-cwdm-15-90" { value 212; } enum "ether-media-type-sfpp-10g-cwdm-16-10" { value 213; } enum "ether-media-type-sfpp-10g-acu7m" { value 214; } enum "ether-media-type-sfpp-10g-acu10m" { value 215; } enum "ether-media-type-cpak-100ge-sr10" { value 216; } enum "ether-media-type-cpak-100ge-lr4" { value 217; } enum "ether-media-type-cpak-100ge-sr4" { value 218; } enum "ether-media-type-cfp-40g" { value 219; } enum "ether-media-type-qsfp-40ge-lr" { value 220; } enum "ether-media-type-qsfp-40ge-sr" { value 221; } enum "ether-media-type-1000base-dr-lx" { value 222; } enum "ether-media-type-sfpp-10g-tdwdm" { value 223; } enum "ether-media-type-qsfp-40ge-er4" { value 224; } enum "ether-media-type-sfpp-dwdm-10gep-61-83" { value 225; } enum "ether-media-type-sfpp-dwdm-10gep-61-41" { value 226; } enum "ether-media-type-sfpp-dwdm-10gep-61-01" { value 227; } enum "ether-media-type-sfpp-dwdm-10gep-60-61" { value 228; } enum "ether-media-type-sfpp-dwdm-10gep-60-20" { value 229; } enum "ether-media-type-sfpp-dwdm-10gep-59-79" { value 230; } enum "ether-media-type-sfpp-dwdm-10gep-59-39" { value 231; } enum "ether-media-type-sfpp-dwdm-10gep-58-98" { value 232; } enum "ether-media-type-sfpp-dwdm-10gep-58-58" { value 233; } enum "ether-media-type-sfpp-dwdm-10gep-58-17" { value 234; } enum "ether-media-type-sfpp-dwdm-10gep-57-77" { value 235; } enum "ether-media-type-sfpp-dwdm-10gep-57-36" { value 236; } enum "ether-media-type-sfpp-dwdm-10gep-56-96" { value 237; } enum "ether-media-type-sfpp-dwdm-10gep-56-55" { value 238; } enum "ether-media-type-sfpp-dwdm-10gep-56-15" { value 239; } enum "ether-media-type-sfpp-dwdm-10gep-55-75" { value 240; } enum "ether-media-type-sfpp-dwdm-10gep-55-34" { value 241; } enum "ether-media-type-sfpp-dwdm-10gep-54-94" { value 242; } enum "ether-media-type-sfpp-dwdm-10gep-54-54" { value 243; } enum "ether-media-type-sfpp-dwdm-10gep-54-13" { value 244; } enum "ether-media-type-sfpp-dwdm-10gep-53-73" { value 245; } enum "ether-media-type-sfpp-dwdm-10gep-53-33" { value 246; } enum "ether-media-type-sfpp-dwdm-10gep-52-93" { value 247; } enum "ether-media-type-sfpp-dwdm-10gep-52-52" { value 248; } enum "ether-media-type-sfpp-dwdm-10gep-52-12" { value 249; } enum "ether-media-type-sfpp-dwdm-10gep-51-72" { value 250; } enum "ether-media-type-sfpp-dwdm-10gep-51-32" { value 251; } enum "ether-media-type-sfpp-dwdm-10gep-50-92" { value 252; } enum "ether-media-type-sfpp-dwdm-10gep-50-52" { value 253; } enum "ether-media-type-sfpp-dwdm-10gep-50-12" { value 254; } enum "ether-media-type-sfpp-dwdm-10gep-49-72" { value 255; } enum "ether-media-type-sfpp-dwdm-10gep-49-32" { value 256; } enum "ether-media-type-sfpp-dwdm-10gep-48-91" { value 257; } enum "ether-media-type-sfpp-dwdm-10gep-48-51" { value 258; } enum "ether-media-type-sfpp-dwdm-10gep-48-11" { value 259; } enum "ether-media-type-sfpp-dwdm-10gep-47-72" { value 260; } enum "ether-media-type-sfpp-dwdm-10gep-47-32" { value 261; } enum "ether-media-type-sfpp-dwdm-10gep-46-92" { value 262; } enum "ether-media-type-sfpp-dwdm-10gep-46-52" { value 263; } enum "ether-media-type-sfpp-dwdm-10gep-46-12" { value 264; } enum "ether-media-type-sfpp-dwdm-10gep-45-72" { value 265; } enum "ether-media-type-sfpp-dwdm-10gep-45-32" { value 266; } enum "ether-media-type-sfpp-dwdm-10gep-44-92" { value 267; } enum "ether-media-type-sfpp-dwdm-10gep-44-53" { value 268; } enum "ether-media-type-sfpp-dwdm-10gep-44-13" { value 269; } enum "ether-media-type-sfpp-dwdm-10gep-43-73" { value 270; } enum "ether-media-type-sfpp-dwdm-10gep-43-33" { value 271; } enum "ether-media-type-sfpp-dwdm-10gep-42-94" { value 272; } enum "ether-media-type-sfpp-dwdm-10gep-42-54" { value 273; } enum "ether-media-type-sfpp-dwdm-10gep-42-14" { value 274; } enum "ether-media-type-sfpp-dwdm-10gep-41-75" { value 275; } enum "ether-media-type-sfpp-dwdm-10gep-41-35" { value 276; } enum "ether-media-type-sfpp-dwdm-10gep-40-95" { value 277; } enum "ether-media-type-sfpp-dwdm-10gep-40-56" { value 278; } enum "ether-media-type-sfpp-dwdm-10gep-40-16" { value 279; } enum "ether-media-type-sfpp-dwdm-10gep-39-77" { value 280; } enum "ether-media-type-sfpp-dwdm-10gep-39-37" { value 281; } enum "ether-media-type-sfpp-dwdm-10gep-38-98" { value 282; } enum "ether-media-type-sfpp-dwdm-10gep-38-58" { value 283; } enum "ether-media-type-sfpp-dwdm-10gep-38-19" { value 284; } enum "ether-media-type-sfpp-dwdm-10gep-37-79" { value 285; } enum "ether-media-type-sfpp-dwdm-10gep-37-40" { value 286; } enum "ether-media-type-sfpp-dwdm-10gep-37-00" { value 287; } enum "ether-media-type-sfpp-dwdm-10gep-36-61" { value 288; } enum "ether-media-type-sfpp-dwdm-10gep-36-22" { value 289; } enum "ether-media-type-sfpp-dwdm-10gep-35-82" { value 290; } enum "ether-media-type-sfpp-dwdm-10gep-35-43" { value 291; } enum "ether-media-type-sfpp-dwdm-10gep-35-04" { value 292; } enum "ether-media-type-sfpp-dwdm-10gep-34-64" { value 293; } enum "ether-media-type-sfpp-dwdm-10gep-34-25" { value 294; } enum "ether-media-type-sfpp-dwdm-10gep-33-86" { value 295; } enum "ether-media-type-sfpp-dwdm-10gep-33-47" { value 296; } enum "ether-media-type-sfpp-dwdm-10gep-33-07" { value 297; } enum "ether-media-type-sfpp-dwdm-10gep-32-68" { value 298; } enum "ether-media-type-sfpp-dwdm-10gep-32-29" { value 299; } enum "ether-media-type-sfpp-dwdm-10gep-31-90" { value 300; } enum "ether-media-type-sfpp-dwdm-10gep-31-51" { value 301; } enum "ether-media-type-sfpp-dwdm-10gep-31-12" { value 302; } enum "ether-media-type-sfpp-dwdm-10gep-30-72" { value 303; } enum "ether-media-type-sfpp-dwdm-10gep-30-33" { value 304; } enum "ether-media-type-ons-se-z1" { value 305; } enum "ether-media-type-qsfp-100ge-lr" { value 306; } enum "ether-media-type-qsfp-100ge-sr" { value 307; } enum "ether-media-type-sfpp-10g-aoc1m" { value 308; } enum "ether-media-type-sfpp-10g-aoc2m" { value 309; } enum "ether-media-type-sfpp-10g-aoc3m" { value 310; } enum "ether-media-type-sfpp-10g-aoc5m" { value 311; } enum "ether-media-type-sfpp-10g-aoc7m" { value 312; } enum "ether-media-type-sfpp-10g-aoc10m" { value 313; } enum "ether-media-type-cpak-100ge-er4l" { value 314; } enum "ether-media-type-qsfp-40ge-sr-bd" { value 315; } enum "ether-media-type-qsfp-40ge-bd-rx" { value 316; } enum "ether-media-type-tunable-dwdm-sfpp" { value 317; } enum "ether-media-type-qsfp-40ge-sr-s" { value 318; } enum "ether-media-type-qsfp-40ge-lr-s" { value 319; } enum "ether-media-type-qsfp-h40ge-aoc1m" { value 320; } enum "ether-media-type-qsfp-h40ge-aoc2m" { value 321; } enum "ether-media-type-qsfp-h40ge-aoc3m" { value 322; } enum "ether-media-type-qsfp-h40ge-aoc5m" { value 323; } enum "ether-media-type-qsfp-h40ge-aoc7m" { value 324; } enum "ether-media-type-qsfp-h40ge-aoc10m" { value 325; } enum "ether-media-type-qsfp-h40ge-aoc15m" { value 326; } enum "ether-media-type-qsfp-h40ge-aoc20m" { value 327; } enum "ether-media-type-qsfp-40ge-csr4" { value 328; } enum "ether-media-type-qsfp-40ge-sr4" { value 329; } enum "ether-media-type-qsfp-40ge-lr4" { value 330; } enum "ether-media-type-wsp-40ge-lr4l" { value 331; } enum "ether-media-type-qsfp-h40ge-cu1m" { value 332; } enum "ether-media-type-qsfp-h40ge-cu3m" { value 333; } enum "ether-media-type-qsfp-h40ge-cu5m" { value 334; } enum "ether-media-type-qsfp-h40ge-acu7m" { value 335; } enum "ether-media-type-qsfp-h40ge-acu10m" { value 336; } enum "ether-media-type-qsfp-100ge-psm4" { value 337; } enum "ether-media-type-qsfp-100ge-cwdm4" { value 338; } enum "ether-media-type-qsfp-100ge-cu1m" { value 339; } enum "ether-media-type-qsfp-100ge-cu2m" { value 340; } enum "ether-media-type-qsfp-100ge-cu3m" { value 341; } enum "ether-media-type-qsfp-100ge-cu5m" { value 342; } enum "ether-media-type-qsfp-100ge-aoc1m" { value 343; } enum "ether-media-type-qsfp-100ge-aoc2m" { value 344; } enum "ether-media-type-qsfp-100ge-aoc3m" { value 345; } enum "ether-media-type-qsfp-100ge-aoc5m" { value 346; } enum "ether-media-type-qsfp-100ge-aoc7m" { value 347; } enum "ether-media-type-qsfp-100ge-aoc10m" { value 348; } enum "ether-media-type-qsfp-100ge-aoc15m" { value 349; } enum "ether-media-type-qsfp-100ge-aoc20m" { value 350; } enum "ether-media-type-qsfp-100ge-aoc25m" { value 351; } enum "ether-media-type-qsfp-100ge-aoc30m" { value 352; } enum "ether-media-type-qsfp-100ge-sm-sr" { value 353; } enum "ether-media-type-qsfp-100ge-csr4" { value 354; } enum "ether-media-type-1000base-2bxd" { value 355; } enum "ether-media-type-qsfp-h40ge-cudot5m" { value 356; } enum "ether-media-type-qsfp-h40ge-cu2m" { value 357; } enum "ether-media-type-qsfp-h40ge-cu4m" { value 358; } enum "ether-media-type-virtual" { value 359; } enum "ether-media-type-sfp-25ge-sr-s" { value 360; } enum "ether-media-type-sfp-25ge-lr-s" { value 361; } enum "ether-media-type-sfp-25ge-cu1m" { value 362; } enum "ether-media-type-sfp-25ge-cu2m" { value 363; } enum "ether-media-type-sfp-25ge-cu3m" { value 364; } enum "ether-media-type-sfp-25ge-cu5m" { value 365; } enum "ether-media-type-sfp-25ge-aoc1m" { value 366; } enum "ether-media-type-sfp-25ge-aoc2m" { value 367; } enum "ether-media-type-sfp-25ge-aoc3m" { value 368; } enum "ether-media-type-sfp-25ge-aoc5m" { value 369; } enum "ether-media-type-sfp-25ge-aoc7m" { value 370; } enum "ether-media-type-sfp-25ge-aoc10m" { value 371; } enum "ether-media-type-cvr-qsfp-sfp10g" { value 372; } enum "ether-media-type-qsfp-h40ge-aoc25m" { value 373; } enum "ether-media-type-qsfp-h40ge-aoc30m" { value 374; } enum "ether-media-type-sfp-gpon" { value 375; } enum "ether-media-type-sfp-25ge-csr" { value 376; } enum "ether-media-type-10gbase-cu2m" { value 377; } enum "ether-media-type-qsfp-100ge-er4l" { value 378; } enum "ether-media-type-sfp-10ge-csr-s" { value 379; } enum "ether-media-type-qsfp-40ge-csr-s" { value 380; } enum "ether-media-type-qsfp28-4sfp25g-cu1m" { value 381; } enum "ether-media-type-qsfp28-4sfp25g-cu2m" { value 382; } enum "ether-media-type-qsfp28-4sfp25g-cu3m" { value 383; } enum "ether-media-type-qsfp28-4sfp25g-cu5m" { value 384; } enum "ether-media-type-10gbase-cu1-5m" { value 385; } enum "ether-media-type-10gbase-cu2-5m" { value 386; } enum "ether-media-type-qsfp-4x10g-lr-s" { value 387; } enum "ether-media-type-qsfp-4x10g-aoc1m" { value 388; } enum "ether-media-type-qsfp-4x10g-aoc2m" { value 389; } enum "ether-media-type-qsfp-4x10g-aoc3m" { value 390; } enum "ether-media-type-qsfp-4x10g-aoc5m" { value 391; } enum "ether-media-type-qsfp-4x10g-aoc7m" { value 392; } enum "ether-media-type-qsfp-4x10g-aoc10m" { value 393; } enum "ether-media-type-qsfp-4x10g-aoc15m" { value 394; } enum "ether-media-type-qsfp-4sfp10g-cu0-5m" { value 395; } enum "ether-media-type-qsfp-4sfp10g-cu1m" { value 396; } enum "ether-media-type-qsfp-4sfp10g-cu2m" { value 397; } enum "ether-media-type-qsfp-4sfp10g-cu3m" { value 398; } enum "ether-media-type-qsfp-4sfp10g-cu4m" { value 399; } enum "ether-media-type-qsfp-4sfp10g-cu5m" { value 400; } enum "ether-media-type-qsfp-4x10g-ac1m" { value 401; } enum "ether-media-type-qsfp-4x10g-ac3m" { value 402; } enum "ether-media-type-qsfp-4x10g-ac5m" { value 403; } enum "ether-media-type-qsfp-4x10g-ac7m" { value 404; } enum "ether-media-type-qsfp-4x10g-ac10m" { value 405; } enum "ether-media-type-qsfp-100ge-sr4" { value 406; } enum "ether-media-type-qsfp-100ge-lr4" { value 407; } enum "ether-media-type-10gbase-cu0-5m" { value 408; } enum "ether-media-type-10gbase-cu4m" { value 409; } enum "ether-media-type-qsfp-40g-100g-srbd" { value 410; } enum "ether-media-type-qsfp-h40ge-cu0-5m" { value 411; } } description "Maximum possible values for media type"; } typedef dot3-stats-versions { type enumeration { enum "not-supported" { value 0; description "Dot 3 error counters are not supported"; } enum "dot3-version-2" { value 1; description "Version 2 dot 3 error counters"; } } description "The version of dot 3 error counters."; } typedef serial-crc { type enumeration { enum "serial-crc32" { value 0; description "32-bit Cyclic Redundancy Code"; } enum "serial-crc16" { value 1; description "16 bit Cyclic Redundancy Code"; } } description "The Cyclic Redundancy Code type"; } typedef subrate-speed { type enumeration { enum "dsx1-subrate-56kbps" { value 0; description "56 kilobits per second subrate"; } enum "dsx1-subrate-64kbps" { value 1; description "64 kilobits per second subrate"; } } description "The subrate on a serial interface"; } typedef t1e1-loopback-mode { type enumeration { enum "t1e1-no-loopback" { value 0; description "No loopback mode"; } enum "t1e1-cli-local-loopback" { value 1; description "Command line interface enforced local loopback"; } enum "t1e1-line-cli-local-loopback" { value 2; description "Command line interface enforced line local loopback"; } enum "t1e1-payload-cli-local-loopback" { value 3; description "Command line interface enforced payload local loopback"; } enum "t1e1-local-line-loopback" { value 4; description "Local line loopback"; } enum "t1e1-local-payload-loopback" { value 5; description "Local payload loopback"; } enum "t1e1-local-ansi-fdl-remote-loopback" { value 6; description "Line ANSI FDL remote loopback"; } enum "t1e1-line-att-fdl-remote-loopback" { value 7; description "Line ATT FDL remote loopback"; } enum "t1e1-payload-ansi-fdl-remote-loopback" { value 8; description "Payload ANSI FDL remote loopback"; } enum "t1e1-payload-att-fdl-remote-loopback" { value 9; description "Payload ATT FDL remote loopback"; } enum "t1e1-line-iboc-remote-loopback" { value 10; description "Line IBOC remote loopback"; } enum "t1e1-line-ansi-fdl-local-loopback" { value 11; description "Line ANSI FDL local loopback"; } enum "t1e1-line-att-fdl-local-loopback" { value 12; description "Line ATT FDL local loopback"; } enum "t1e1-payload-ansi-fdl-local-loopback" { value 13; description "Payload ANSI FDL local loopback"; } enum "t1e1-payload-att-fdl-local-loopback" { value 14; description "Payload ATT FDL local loopback"; } enum "t1e1-line-iboc-local-loopback" { value 15; description "Line IBOC local loopback"; } } description "Loopback mode type"; } typedef signal-status { type enumeration { enum "down" { value 0; description "Signal is down"; } enum "up" { value 1; description "Signal is up"; } } description "Synchronous serial interface signal status"; } typedef idle-character-type { type enumeration { enum "flag" { value 0; description "Send HDLC flag characters between packets"; } enum "marks" { value 1; description "Send mark characters between packets"; } } description "Synchronous serial idle character"; } grouping wred-class-counts { description "WRED class count types"; leaf wred-tx-pkts { type uint64; description "Transmitted packets"; } leaf wred-tx-bytes { type uint64; description "Transmitted bytes"; } leaf wred-tail-drop-pkts { type uint64; description "Tail drop packets"; } leaf wred-tail-drop-bytes { type uint64; description "Tail drop bytes"; } leaf wred-early-drop-pkts { type uint64; description "Early drop packets"; } leaf wred-early-drop-bytes { type uint64; description "Early drop bytes"; } } grouping marking-dscp-stats { description "Statistics for set dscp"; leaf dscp { type uint32; description "dscp marking"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-dscp-tunnel-stats { description "Statistics for set dscp tunnel"; leaf dscp-val { type uint32; description "dscp value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-cos-stats { description "Statistics for set cos"; leaf cos-val { type uint32; description "cos value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-cos-inner-stats { description "Statistics for set cos-inner"; leaf cos-inner-val { type uint32; description "cos inner value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-discard-class-stats { description "Statistics for set discard-class"; leaf disc-class-val { type uint32; description "discard-class value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-qos-grp-stats { description "Statistics for set qos-group"; leaf qos-grp-val { type uint32; description "qos group value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-prec-stats { description "Statistics for set precedence"; leaf prec-val { type uint32; description "precedence value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-prec-tunnel-stats { description "Statistics for set precedence tunnel"; leaf prec-val { type uint32; description "precedence value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-mpls-exp-imp-stats { description "Statistics for set mpls exp imposition"; leaf mpls-exp-imp-val { type uint32; description "mpls exp value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-mpls-exp-top-stats { description "Statistics for set mpls exp imposition"; leaf mpls-exp-top-val { type uint32; description "mpls exp value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-fr-de-stats { description "Statistics for set fr-de"; leaf fr-de { type boolean; description "fr de set or not"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-fr-fecn-becn-stats { description "Statistics for set fr-fecn-becn"; leaf fecn-becn-val { type uint32; description "fecn becn value. qos:percent-value-1to100"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-atm-clp-stats { description "Statistics for set atm-clp"; leaf atm-clp-val { type uint8; description "atm clp value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-vlan-inner-stats { description "Statistics for set vlan-inner"; leaf vlan-inner-val { type uint32; description "vlan value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-dei-stats { description "Statistics for set dei"; leaf dei-imp-value { type uint32; description "dei value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-dei-imp-stats { description "Statistics for set dei-imposition"; leaf dei-imp-value { type uint32; description "dei value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-srp-priority-stats { description "Statistics for set srp-priority"; leaf srp-priority-value { type uint8; description "srp priority value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-wlan-user-priority-stats { description "Statistics for set wlan-user-priority"; leaf wlan-user-priority-value { type uint8; description "wlan user priority value"; } leaf marked-pkts { type uint64; description "Number of packets been marked"; } } grouping marking-stats { description "Marking statistics"; container marking-dscp-stats-val { description "Statistics for set dscp"; uses interfaces-ios-xe-oper:marking-dscp-stats; } container marking-dscp-tunnel-stats-val { description "Statistics for set dscp tunnel"; uses interfaces-ios-xe-oper:marking-dscp-tunnel-stats; } container marking-cos-stats-val { description "Statistics for set cos"; uses interfaces-ios-xe-oper:marking-cos-stats; } container marking-cos-inner-stats-val { description "Statistics for set cos-inner"; uses interfaces-ios-xe-oper:marking-cos-inner-stats; } container marking-discard-class-stats-val { description "Statistics for set discard-class"; uses interfaces-ios-xe-oper:marking-discard-class-stats; } container marking-qos-grp-stats-val { description "Statistics for set qos-group"; uses interfaces-ios-xe-oper:marking-qos-grp-stats; } container marking-prec-stats-val { description "Statistics for set precedence"; uses interfaces-ios-xe-oper:marking-prec-stats; } container marking-prec-tunnel-stats-val { description "Statistics for set precedence tunnel"; uses interfaces-ios-xe-oper:marking-prec-tunnel-stats; } container marking-mpls-exp-imp-stats-val { description "Statistics for set mpls exp imposition"; uses interfaces-ios-xe-oper:marking-mpls-exp-imp-stats; } container marking-mpls-exp-top-stats-val { description "Statistics for set mpls exp topmost"; uses interfaces-ios-xe-oper:marking-mpls-exp-top-stats; } container marking-fr-de-stats-val { description "Statistics for set fr-de"; uses interfaces-ios-xe-oper:marking-fr-de-stats; } container marking-fr-fecn-becn-stats-val { description "Statistics for set fr-fecn-becn"; uses interfaces-ios-xe-oper:marking-fr-fecn-becn-stats; } container marking-atm-clp-stats-val { description "Statistics for set atm-clp"; uses interfaces-ios-xe-oper:marking-atm-clp-stats; } container marking-vlan-inner-stats-val { description "Statistics for set vlan-inner"; uses interfaces-ios-xe-oper:marking-vlan-inner-stats; } container marking-dei-stats-val { description "Statistics for set dei"; uses interfaces-ios-xe-oper:marking-dei-stats; } container marking-dei-imp-stats-val { description "Statistics for set dei-imposition"; uses interfaces-ios-xe-oper:marking-dei-imp-stats; } container marking-srp-priority-stats-val { description "Statistics for set srp-priority"; uses interfaces-ios-xe-oper:marking-srp-priority-stats; } container marking-wlan-user-priority-stats-val { description "Statistics for set wlan-user-priority"; uses interfaces-ios-xe-oper:marking-wlan-user-priority-stats; } } grouping cos-key { description "COS key type"; leaf cos-min { type uint32; description "Min COS value"; } leaf cos-max { type uint32; description "Max COS value"; } } grouping disc-class-key { description "Discard class key type"; leaf disc-class-min { type uint32; description "Minimum value for discard class in the range"; } leaf disc-class-max { type uint32; description "Maximum value for discard class in the range"; } } grouping dscp-key { description "DSCP key type"; leaf dscp-min { type uint32; description "Minimum of dscp range"; } leaf dscp-max { type uint32; description "Maximum of dscp range"; } } grouping qos-grp-key { description "QoS group key type"; leaf qos-group-min { type uint32; description "Specifies the minimum value range from 0 to used to identify a QoS group value"; } leaf qos-group-max { type uint32; description "Specifies the maximum value range from 0 to used to identify a QoS group value"; } } grouping mpls-exp-key { description "MPLS EXP key type"; leaf exp-min { type uint32; description "The minimum EXP field value to be used as match criteria. Any number from 0 to 7"; } leaf exp-max { type uint32; description "The maximum EXP field value to be used as match criteria. Any number from 0 to 7"; } } grouping prec-key { description "Precedence key type"; leaf prec-min { type uint32; description "Precedence min"; } leaf prec-max { type uint32; description "Precedence max"; } } grouping dei-key { description "DEI key type"; leaf dei-min { type uint32; description "Dei min"; } leaf dei-max { type uint32; description "Dei max"; } } grouping clp-key { description "CLP key type"; leaf clp-val { type uint32; description "Composed by multiple atm clp values"; } } grouping subclass-list { description "Subclass data"; leaf match-type { type interfaces-ios-xe-oper:qos-match-type; description "Subclass match type"; } list cos-counters { key "cos-min cos-max"; description "Counters for sub-class matching a range of Class-of-Service (COS) value (and, optionally, additional COS range"; uses interfaces-ios-xe-oper:cos-key; uses interfaces-ios-xe-oper:wred-class-counts; } container cos-default { description "statistics for cos default"; uses interfaces-ios-xe-oper:wred-class-counts; } list dscp-counters { key "dscp-min dscp-max"; description "List for statistics based on dscp value range"; uses interfaces-ios-xe-oper:dscp-key; uses interfaces-ios-xe-oper:wred-class-counts; } container dscp-default { description "Statistics for dscp default"; uses interfaces-ios-xe-oper:wred-class-counts; } list discard-class-counters { key "disc-class-min disc-class-max"; description "Composed multiple discard class ranges"; uses interfaces-ios-xe-oper:disc-class-key; uses interfaces-ios-xe-oper:wred-class-counts; } container disc-class-default { description "Statistics for discard class default"; uses interfaces-ios-xe-oper:wred-class-counts; } list precedence-counters { key "prec-min prec-max"; description "List for statistics based on precedence value range"; uses interfaces-ios-xe-oper:prec-key; uses interfaces-ios-xe-oper:wred-class-counts; } container prec-default { description "Precedence default"; uses interfaces-ios-xe-oper:wred-class-counts; } list mpls-exp-counters { key "exp-min exp-max"; description "List for statistics based on mpls exp value range"; uses interfaces-ios-xe-oper:mpls-exp-key; uses interfaces-ios-xe-oper:wred-class-counts; } container mpls-exp-default { description "Statistics for mpls-exp default"; uses interfaces-ios-xe-oper:wred-class-counts; } list dei-counters { key "dei-min dei-max"; description "Composed by multiple dei ranges"; uses interfaces-ios-xe-oper:dei-key; uses interfaces-ios-xe-oper:wred-class-counts; } container dei-counts-default { description "Statistics for dei default"; uses interfaces-ios-xe-oper:wred-class-counts; } list clp-counters { key "clp-val"; description "Statistics for each value range for a specific subclass type"; uses interfaces-ios-xe-oper:clp-key; uses interfaces-ios-xe-oper:wred-class-counts; } container clp-default { description "Statistic for atm clp default"; uses interfaces-ios-xe-oper:wred-class-counts; } } grouping classifier-entry-statistics { description "Classifier entry statistics"; leaf classified-pkts { type uint64; description "Number of total packets which filtered to the classifier-entry"; } leaf classified-bytes { type uint64; description "Number of total bytes which filtered to the classifier-entry"; } leaf classified-rate { type uint64; description "Rate of average data flow through the classifier-entry"; } } grouping diffserv-target-classifier-statistics-key { description "Diffserv classifier statistics key"; leaf classifier-entry-name { type string; description "Classifier Entry Name"; } leaf parent-path { type string; description "Path of the Classifier Entry in a hierarchical policy"; } } grouping wred-stats { description "WRED counters"; leaf early-drop-pkts { type uint64; description "Early drop packets"; } leaf early-drop-bytes { type uint64; description "Early drop bytes"; } leaf mean-queue-depth { type uint16; description "Current mean queue depth"; } leaf transmitted-pkts { type uint64; description "Transmitted packets"; } leaf transmitted-bytes { type uint64; description "Transmitted bytes"; } leaf tail-drop-pkts { type uint64; description "Total number of packets dropped"; } leaf tail-drop-bytes { type uint64; description "Total number of bytes dropped"; } leaf drop-pkts-flow { type uint64; description "Total number of packets dropped"; } leaf drop-pkts-no-buffer { type uint64; description "Number of packets dropped due to buffers being unavailable system-wide or at the associated interface. This is a sub-set of drop-pkts"; } leaf queue-peak-size-pkts { type uint64; description "Queue max que depth Packets"; } leaf queue-peak-size-bytes { type uint64; description "Queue max que depth Bytes"; } leaf bandwidth-exceed-drops { type uint64; description "Priority stats. Bandwidth exceed drops"; } } grouping cac-stats { description "CAC statistics"; leaf num-admitted-flows { type uint32; description "Number of admitted flows"; } leaf num-non-admitted-flows { type uint32; description "Number of non-admitted flows"; } } grouping queuing-statistics { description "Queue related statistics"; leaf output-pkts { type uint64; description "Number of packets transmitted from queue"; } leaf output-bytes { type uint64; description "Number of bytes transmitted from queue"; } leaf queue-size-pkts { type uint64; description "Number of packets currently buffered "; } leaf queue-size-bytes { type uint64; description "Number of bytes currently buffered"; } leaf drop-pkts { type uint64; description "Total number of packets dropped"; } leaf drop-bytes { type uint64; description "Total number of bytes dropped"; } container wred-stats { description "WRED Counters"; uses interfaces-ios-xe-oper:wred-stats; } container cac-stats { description "CAC statistics"; uses interfaces-ios-xe-oper:cac-stats; } } grouping meter-statistics { description "Metering Counters"; leaf meter-id { type uint16; description "Meter Identifier"; } leaf meter-succeed-pkts { type uint64; description "Number of packets which succeed the meter"; } leaf meter-succeed-bytes { type uint64; description "Bytes of packets which succeed the meter"; } leaf meter-failed-pkts { type uint64; description "Number of packets which failed the meter"; } leaf meter-failed-bytes { type uint64; description "Bytes of packets which failed the meter"; } } grouping diffserv-target-classifier-statistics { description "Diffserv classifier statistics"; container classifier-entry-stats { description "Classifier Counters"; uses interfaces-ios-xe-oper:classifier-entry-statistics; } list meter-stats { key "meter-id"; description "Meter statistics"; uses interfaces-ios-xe-oper:meter-statistics; } container queuing-stats { description "Queuing Counters"; uses interfaces-ios-xe-oper:queuing-statistics; } list subclass-list { key "match-type"; description "List of statistics for random-detect based on subclass type and value pair Technically these are a field in the queuing statistics -> wred statistics, but GREEN EI does not allow that nesting structure"; uses interfaces-ios-xe-oper:subclass-list; } container marking-stats { description "Statistics for marking actions"; uses interfaces-ios-xe-oper:marking-stats; } } grouping diffserv-target-entry-key { description "Key to the diffserv"; leaf direction { type interfaces-ios-xe-oper:qos-direction; description "Direction fo the traffic flow either inbound or outbound"; } leaf policy-name { type string; description "Policy entry name"; } } grouping agg-priority-stats { description "Type for counters in aggregate priority"; leaf output-pkts { type uint64; description "Number of packets transmitted from queue"; } leaf output-bytes { type uint64; description "Number of bytes transmitted from queue"; } leaf queue-size-pkts { type uint64; description "Number of packets currently buffered"; } leaf queue-size-bytes { type uint64; description "Number of bytes currently buffered"; } leaf drop-pkts { type uint64; description "Total number of packets dropped"; } leaf drop-bytes { type uint64; description "Total number of bytes dropped"; } leaf drop-pkts-flow { type uint64; description "Number of packets that were dropped by flow-based fair-queuing (fair-queue). This is a sub-set of drop-pkts"; } leaf drop-pkts-no-buffer { type uint64; description "Number of packets dropped due to buffers being unavailable system-wide or at the associated interface. This is a sub-set of drop-pkts"; } } grouping threshold { description "Threshold Parameters"; leaf bytes { type uint64; description "Threshold bytes"; } leaf thresh-size-metric { type uint32; description "Threshold size unit"; } leaf unit-val { type interfaces-ios-xe-oper:thresh-unit; description "Threshold size basic units"; } leaf threshold-interval { type uint64; description "Threshold interval"; } leaf thresh-interval-metric { type uint32; description "Threshold units metric"; } leaf interval-unit-val { type interfaces-ios-xe-oper:thresh-unit; description "Threshold interval basic units"; } } grouping priority-oper-list { description "Priority based statistics"; leaf priority-level { type uint16; description "Priority Level, 0 means no priority level set"; } container agg-priority-stats { description "Counters in aggregate priority"; uses interfaces-ios-xe-oper:agg-priority-stats; } container qlimit-default-thresh { description "queue limit default threshold"; uses interfaces-ios-xe-oper:threshold; } list qlimit-cos-thresh-list { key "cos-min cos-max"; description "cos-based queue limit data"; uses interfaces-ios-xe-oper:cos-key; uses interfaces-ios-xe-oper:threshold; } list qlimit-disc-class-thresh-list { key "disc-class-min disc-class-max"; description "discard-class-based queue limit data"; uses interfaces-ios-xe-oper:disc-class-key; uses interfaces-ios-xe-oper:threshold; } list qlimit-qos-grp-thresh-list { key "qos-group-min qos-group-max"; description "qos-group-based queue limit data"; uses interfaces-ios-xe-oper:qos-grp-key; uses interfaces-ios-xe-oper:threshold; } list qlimit-mpls-exp-thresh-list { key "exp-min exp-max"; description "mpls-exp-based queue limit data"; uses interfaces-ios-xe-oper:mpls-exp-key; uses interfaces-ios-xe-oper:threshold; } list qlimit-dscp-thresh-list { key "dscp-min dscp-max"; description "queue limit per dscp range"; uses interfaces-ios-xe-oper:dscp-key; uses interfaces-ios-xe-oper:threshold; } } grouping diffserv-target-entry { description "Diffserv target data"; list diffserv-target-classifier-stats { key "classifier-entry-name parent-path"; description "Statistics for each Classifier Entry in a Policy"; uses interfaces-ios-xe-oper:diffserv-target-classifier-statistics-key; uses interfaces-ios-xe-oper:diffserv-target-classifier-statistics; } list priority-oper-list { key "priority-level"; description "Statistics for aggregate priority per policy instance"; uses interfaces-ios-xe-oper:priority-oper-list; } } grouping lag-aggregate-state { description "Operational state variables for logical aggregate / LAG interfaces"; leaf aggregate-id { type string; description "Specify the logical aggregate interface to which this id belongs"; } leaf lag-type { type interfaces-ios-xe-oper:aggregation-type; description "Type to define the lag-type, i.e., how the LAG is defined and managed"; } leaf min-links { type uint16; description "Specifies the minimum number of member interfaces that must be active for the aggregate interface to be available"; } leaf lag-speed { type uint32; description "Reports effective speed of the aggregate interface, based on speed of active member interfaces"; } leaf-list members { type string; ordered-by user; description "List of current member interfaces for the aggregate, expressed as references to existing interfaces"; } } grouping protocol-statistics { description "Protocol specific statistics"; leaf in-pkts { type uint64; description "The total number of packets received for the specified address family, including those received in error"; } leaf in-octets { type uint64; description "The total number of octets received in input packets for the specified address family, including those received in error."; } leaf in-error-pkts { type uint64; description "Number of packets discarded due to errors for the specified address family, including errors in the header, no route found to the destination, invalid address, unknown protocol, etc."; } leaf in-forwarded-pkts { type uint64; description "The number of input packets for which the device was not their final destination and for which the device attempted to find a route to forward them to that final destination."; } leaf in-forwarded-octets { type uint64; description "The number of octets received in input packets for the specified address family for which the device was not their final destination and for which the device attempted to find a route to forward them to that final destination."; } leaf in-discarded-pkts { type uint64; description "The number of input IP packets for the specified address family, for which no problems were encountered to prevent their continued processing, but were discarded (e.g., for lack of buffer space)."; } leaf out-pkts { type uint64; description "The total number of IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device."; } leaf out-octets { type uint64; description "The total number of octets in IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device."; } leaf out-error-pkts { type uint64; description "Number of IP packets for the specified address family locally generated and discarded due to errors, including no route found to the IP destination."; } leaf out-forwarded-pkts { type uint64; description "The number of packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination.text"; } leaf out-forwarded-octets { type uint64; description "The number of octets in packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination."; } leaf out-discarded-pkts { type uint64; description "The number of output IP packets for the specified address family for which no problem was encountered to prevent their transmission to their destination, but were discarded (e.g., for lack of buffer space)."; } } grouping intf-statistics { description "Interface statistics"; leaf discontinuity-time { type yang:date-and-time; description "The time on the most recent occasion at which any one or more of this interface's counters suffered a discontinuity. If no such discontinuities have occurred since the last re-initialization of the local management subsystem, then this node contains the time the local management subsystem re-initialized itself"; } leaf in-octets { type uint64; description "The total number of octets received on the interface, including framing characters. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of discontinuity-time"; } leaf in-unicast-pkts { type uint64; description "The number of packets, delivered by this sub-layer to a higher (sub-)layer, that were not addressed to a multicast or broadcast address at this sub-layer. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'."; } leaf in-broadcast-pkts { type uint64; description "The number of packets, delivered by this sub-layer to a higher (sub-)layer, that were addressed to a broadcast address at this sub-layer. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-multicast-pkts { type uint64; description "The number of packets, delivered by this sub-layer to a higher (sub-)layer, that were addressed to a multicast address at this sub-layer. For a MAC-layer protocol, this includes both Group and Functional addresses. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-discards { type uint32; description "The number of inbound packets that were chosen to be discarded even though no errors had been detected to prevent their being deliverable to a higher-layer protocol. One possible reason for discarding such a packet could be to free up buffer space. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-errors { type uint32; description "For packet-oriented interfaces, the number of inbound packets that contained errors preventing them from being deliverable to a higher-layer protocol. For character- oriented or fixed-length interfaces, the number of inbound transmission units that contained errors preventing them from being deliverable to a higher-layer protocol. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-unknown-protos { type uint32; description "For packet-oriented interfaces, the number of packets received via the interface that were discarded because of an unknown or unsupported protocol. For character-oriented or fixed-length interfaces that support protocol multiplexing, the number of transmission units received via the interface that were discarded because of an unknown or unsupported protocol. For any interface that does not support protocol multiplexing, this counter is not present. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-octets { type uint32; description "The total number of octets transmitted out of the interface, including framing characters. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-unicast-pkts { type uint64; description "The total number of packets that higher-level protocols requested be transmitted, and that were not addressed to a multicast or broadcast address at this sub-layer, including those that were discarded or not sent. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-broadcast-pkts { type uint64; description "The total number of packets that higher-level protocols requested be transmitted, and that were addressed to a broadcast address at this sub-layer, including those that were discarded or not sent. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-multicast-pkts { type uint64; description "The total number of packets that higher-level protocols requested be transmitted, and that were addressed to a multicast address at this sub-layer, including those that were discarded or not sent. For a MAC-layer protocol, this includes both Group and Functional addresses. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-discards { type uint64; description "The number of outbound packets that were chosen to be discarded even though no errors had been detected to prevent their being transmitted. One possible reason for discarding such a packet could be to free up buffer space. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-errors { type uint64; description "For packet-oriented interfaces, the number of outbound packets that could not be transmitted because of errors. For character-oriented or fixed-length interfaces, the number of outbound transmission units that could not be transmitted because of errors. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf rx-pps { type uint64; description "The receive packet per second rate on this interface"; } leaf rx-kbps { type uint64; description "The receive kilobits per second rate on this interface"; } leaf tx-pps { type uint64; description "The transmit packet per second rate on this interface"; } leaf tx-kbps { type uint64; description "The transmit kilobits per second rate on this interface"; } leaf num-flaps { type uint64; description "The number of times the interface state transitioned between up and down"; } leaf in-crc-errors { type uint64; description "Number of receive error events due to FCS/CRC check failure"; } leaf in-discards-64 { type uint64; description "The number of inbound packets that were chosen to be discarded even though no errors had been detected to prevent their being deliverable to a higher-layer protocol. One possible reason for discarding such a packet could be to free up buffer space. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-errors-64 { type uint64; description "For packet-oriented interfaces, the number of inbound packets that contained errors preventing them from being deliverable to a higher-layer protocol. For character- oriented or fixed-length interfaces, the number of inbound transmission units that contained errors preventing them from being deliverable to a higher-layer protocol. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf in-unknown-protos-64 { type uint64; description "For packet-oriented interfaces, the number of packets received via the interface that were discarded because of an unknown or unsupported protocol. For character-oriented or fixed-length interfaces that support protocol multiplexing, the number of transmission units received via the interface that were discarded because of an unknown or unsupported protocol. For any interface that does not support protocol multiplexing, this counter is not present. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } leaf out-octets-64 { type uint64; description "The total number of octets transmitted out of the interface, including framing characters. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of 'discontinuity-time'"; } } grouping ethernet-state { description "Ethernet State"; leaf negotiated-duplex-mode { type interfaces-ios-xe-oper:ether-duplex; description "When auto-negotiate is set to TRUE, and the interface has completed auto-negotiation with the remote peer, this value shows the duplex mode that has been negotiated."; } leaf negotiated-port-speed { type interfaces-ios-xe-oper:ether-speed; description "When auto-negotiate is set to TRUE, and the interface has completed auto-negotiation with the remote peer, this value shows the interface speed that has been negotiated."; } leaf auto-negotiate { type boolean; description "Set to TRUE to request the interface to auto-negotiate transmission parameters with its peer interface. When set to FALSE, the transmission parameters are specified manually."; } leaf enable-flow-control { type boolean; description "Enable or disable flow control for this interface. Ethernet flow control is a mechanism by which a receiver may send PAUSE frames to a sender to stop transmission for a specified time. This setting should override auto-negotiated flow control settings. If left unspecified, and auto-negotiate is TRUE, flow control mode is negotiated with the peer interface."; } leaf media-type { type interfaces-ios-xe-oper:media-type-class; description "Type of media attached to the interface"; } } grouping dot3-v2-error-counters { description "dot 3 version 2 error counters"; leaf dot3-alignment-errors { type uint64; description "A count of frames received that are not an integral number of octets in length and do not pass the FCS check."; } leaf dot3-fcs-errors { type uint64; description "A count of frames received that are an integral number of octets in length and do not pass the FCS check."; } leaf dot3-single-collision-frames { type uint64; description "A count of frames that are involved in a single collision, and are subsequently transmitted successfully."; } leaf dot3-multiple-collision-frames { type uint64; description "A count of frames that are involved in more than one collision and are subsequently transmitted successfully."; } leaf dot3-sqe-test-errors { type uint64; description "A count of times that the signal quality error test errors is received on a particular interface."; } leaf dot3-deferred-transmissions { type uint64; description "A count of frames for which the first transmission attempt on a particular interface is delayed because the medium is busy."; } leaf dot3-late-collisions { type uint64; description "The number of times that a collision is detected on a particular interface later than one slot time into the transmission of a packet."; } leaf dot3-excessive-collisions { type uint64; description "A count of frames for which transmission on a particular interface fails due to excessive collisions."; } leaf dot3-internal-mac-transmit-errors { type uint64; description "A count of frames for which transmission on a particular interface fails due to an internal MAC sublayer transmit error."; } leaf dot3-carrier-sense-errors { type uint64; description "The number of times that the carrier sense condition was lost or never asserted when attempting to transmit a frame on a particular interface."; } leaf dot3-frame-too-longs { type uint64; description "A count of frames received on a particular interface that exceed the maximum permitted frame size."; } leaf dot3-internal-mac-receive-errors { type uint64; description "A count of frames for which reception on a particular interface fails due to an internal MAC sublayer receive error."; } leaf dot3-symbol-errors { type uint64; description "For an interface operating at 100 Mb/s, the number of times there was an invalid data symbol when a valid carrier was present."; } leaf dot3-duplex-status { type uint64; description "The current mode of operation of the MAC entity. 'unknown' indicates that the current duplex mode could not be determined. The possible value as defined by RFC 3635 are: unknown 1 half duplex 2 full duplex 3"; } leaf dot3-hc-alignment-errors { type uint64; description "A count of frames received that are not an integral number of octets in length and do not pass the FCS check on interfaces operating at 10 Gb/s or faster."; } leaf dot3-hc-inpause-frames { type uint64; description "MAC layer PAUSE frames received on the interface"; } leaf dot3-hc-outpause-frames { type uint64; description "MAC layer PAUSE frames sent on the interface"; } leaf dot3-hc-fcs-errors { type uint64; description "A count of frames received that are an integral number of octets in length and do not pass the FCS check on interfaces operating at 10 Gb/s or faster."; } leaf dot3-hc-frame-too-longs { type uint64; description "A count of frames received on a particular interface that exceed the maximum permitted frame size on interfaces operating at 10 Gb/s or faster."; } leaf dot3-hc-internal-mac-transmit-errors { type uint64; description "A count of frames for which transmission on a particular interface fails due to an internal MAC sublayer transmit error on interfaces operating at 10 Gb/s or faster."; } leaf dot3-hc-internal-mac-receive-errors { type uint64; description "A count of frames for which reception on a particular interface fails due to an internal MAC sublayer receive error on interfaces operating at 10 Gb/s or faster."; } leaf dot3-hc-symbol-errors { type uint64; description "For an interface operating at 10 Gb/s or higher, the number of times the receiving media is non-idle (a carrier event) for a period of time equal to or greater than minimum frame size, and during which there was at least one occurrence of an event that causes the PHY to indicate 'Receive Error'"; } } grouping dot3-counters { description "Dot 3 error counters"; leaf dot3-stats-version { type interfaces-ios-xe-oper:dot3-stats-versions; description "Version of dot 3 error counters"; } container dot3-error-counters-v2 { description "The Ethernet dot 3 version 2 error counters"; uses interfaces-ios-xe-oper:dot3-v2-error-counters; } } grouping ethernet-statistics { description "Ethernet statistics"; leaf in-mac-control-frames { type uint64; description "MAC layer control frames received on the interface"; } leaf in-mac-pause-frames { type uint64; description "MAC layer PAUSE frames received on the interface"; } leaf in-oversize-frames { type uint64; description "Number of oversize frames received on the interface"; } leaf in-jabber-frames { type uint64; description "Number of jabber frames received on the interface. Jabber frames are typically defined as oversize frames which also have a bad CRC. Implementations may use slightly different definitions of what constitutes a jabber frame. Often indicative of a NIC hardware problem."; } leaf in-fragment-frames { type uint64; description "Number of fragment frames received on the interface."; } leaf in-8021q-frames { type uint64; description "Number of 802.1q tagged frames received on the interface"; } leaf out-mac-control-frames { type uint64; description "MAC layer control frames sent on the interface"; } leaf out-mac-pause-frames { type uint64; description "MAC layer PAUSE frames sent on the interface"; } leaf out-8021q-frames { type uint64; description "Number of 802.1q tagged frames sent on the interface"; } leaf dot3-counters-supported { type empty; description "When present, the dot 3 version 2 error counters are valid"; } container dot3-counters { when "boolean(../dot3-counters-supported)"; description "dot 3 error counters"; uses interfaces-ios-xe-oper:dot3-counters; } } grouping t1e1-serial-state { description "The T1/E1 serial state"; leaf crc-type { type interfaces-ios-xe-oper:serial-crc; description "Cyclic Redundancy Code type configured on the interface"; } leaf loopback { type interfaces-ios-xe-oper:t1e1-loopback-mode; description "Loopback mode the interface is operating in"; } leaf keeplive { type uint32; description "Keep alive interval in seconds"; } leaf timeslot { type uint32; description "Time slots bitmap occupied by this serial interface"; } leaf subrate { type interfaces-ios-xe-oper:subrate-speed; description "Subrate operating per slot"; } } grouping t1e1-serial-stats { description "The serial specific statistics"; leaf in-abort-clock-error { type uint32; description "Number of receive abort packets due to clock slides"; } } grouping dce-state { description "Synchronous serial DCE mode state"; leaf dce-terminal-timing-enable { type boolean; description "Enable DCE terminal timing"; } leaf ignore-dtr { type boolean; description "Ignore DTR signal"; } leaf serial-clock-rate { type uint32; units "bps"; description "Serial clock rate in bps"; } } grouping dte-state { description "Synchronous serial DTE mode state"; leaf tx-invert-clk { type boolean; description "Invert transmit clock"; } leaf ignore-dcd { type boolean; description "Ignore DCD signal"; } leaf rx-clockrate { type uint32; units "bps"; description "Received clock rate"; } leaf rx-clock-threshold { type uint32; units "bps"; description "Received clock rate threshold limit"; } } grouping sync-serial-state { description "The synchronous serial state"; leaf carrier-delay { type uint32; units "milli-seconds"; description "Delay for interface transitions"; } leaf dtr-pulse-time { type uint32; units "milli-seconds"; description "DTR pulse time on reset"; } leaf restart-delay { type uint32; units "milli-seconds"; description "Serial interface restart-delay"; } leaf cable-type { type string; description "Cable type attached on the interface"; } leaf loopback { type boolean; description "Whether the interface is in loopback mode"; } leaf nrzi-encoding { type boolean; description "Enable use of NRZI encoding"; } leaf idle-character { type interfaces-ios-xe-oper:idle-character-type; description "Idle character type"; } leaf rts-signal { type interfaces-ios-xe-oper:signal-status; description "RTS signal state"; } leaf cts-signal { type interfaces-ios-xe-oper:signal-status; description "CTS signal state"; } leaf dtr-signal { type interfaces-ios-xe-oper:signal-status; description "DTR signal state"; } leaf dcd-signal { type interfaces-ios-xe-oper:signal-status; description "DCD signal state"; } leaf dsr-signal { type interfaces-ios-xe-oper:signal-status; description "DSR signal state"; } container dce-mode-state { description "Special state in DCE mode"; uses interfaces-ios-xe-oper:dce-state; } container dte-mode-state { description "Special state in DTE mode"; uses interfaces-ios-xe-oper:dte-state; } } grouping interface-state { description "Interface state details"; leaf name { type string; description "The name of the interface. A server implementation MAY map this leaf to the ifName MIB object. Such an implementation needs to use some mechanism to handle the differences in size and characters allowed between this leaf and ifName. The definition of such a mechanism is outside the scope of this document"; } leaf interface-type { type interfaces-ios-xe-oper:ietf-intf-type; description "When an interface entry is created, a server MAY initialize the type leaf with a valid value, e.g., if it is possible to derive the type from the name of the interface. If a client tries to set the type of an interface to a value that can never be used by the system, e.g., if the type is not supported or if the type does not match the name of the interface, the server MUST reject the request. A NETCONF server MUST reply with an rpc-error with the error-tag 'invalid-value' in this case"; } leaf admin-status { type interfaces-ios-xe-oper:intf-state; description "The desired state of the interface. This leaf has the same read semantics as ifAdminStatus"; } leaf oper-status { type interfaces-ios-xe-oper:oper-state; description "The current operational state of the interface. This leaf has the same semantics as ifOperStatus"; } leaf last-change { type yang:date-and-time; description "The time the interface entered its current operational state. If the current state was entered prior to the last re-initialization of the local network management subsystem, then this node is not present"; } leaf if-index { type int32; description "The ifIndex value for the ifEntry represented by this interface"; } leaf phys-address { type yang:mac-address; description "The interface's address at its protocol sub-layer. For example, for an 802.x interface, this object normally contains a Media Access Control (MAC) address. The interface's media-specific modules must define the bit and byte ordering and the format of the value of this object. For interfaces that do not have such an address (e.g., a serial line), this node is not present"; } leaf-list higher-layer-if { type string; ordered-by user; description "A list of references to interfaces layered on top of this interface"; } leaf-list lower-layer-if { type string; ordered-by user; description "A list of references to interfaces layered underneath this interface"; } leaf speed { type uint64; description "An estimate of the interface's current bandwidth in bits per second. For interfaces that do not vary in bandwidth or for those where no accurate estimation can be made, this node should contain the nominal bandwidth. For interfaces that have no concept of bandwidth, this node is not present"; } container statistics { description "A collection of interface-related statistics objects"; uses interfaces-ios-xe-oper:intf-statistics; } list diffserv-info { key "direction policy-name"; description "diffserv related details"; uses interfaces-ios-xe-oper:diffserv-target-entry-key; uses interfaces-ios-xe-oper:diffserv-target-entry; } leaf vrf { type string; description "VRF to which this interface belongs to. If the interface is not in a VRF then it is 'Global'"; } leaf ipv4 { type inet:ip-address; description "IPv4 address configured on interface"; } leaf ipv4-subnet-mask { type inet:ip-address; description "IPv4 Subnet Mask"; } leaf description { type string; description "Interface description"; } leaf mtu { type uint32; description "Maximum transmission unit"; } leaf input-security-acl { type string; description "Input Security ACL"; } leaf output-security-acl { type string; description "Output Security ACL"; } container v4-protocol-stats { description "IPv4 traffic statistics for this interface"; uses interfaces-ios-xe-oper:protocol-statistics; } container v6-protocol-stats { description "IPv6 traffic statistics for this interface"; uses interfaces-ios-xe-oper:protocol-statistics; } leaf bia-address { type yang:mac-address; description "The burnt-in mac address that was associated with this interface from manufacturing. This is only relevant for interfaces that have the concept of burnt in ethernet addresses, otherwise it is zero."; } leaf-list ipv6-addrs { type inet:ip-address; ordered-by user; description "A list of the IPv6 addresses associated with the interface. This contains all the IPv6 addresses, including the link local addresses, assigned to the interface"; } list lag-aggregate-state { key "aggregate-id"; description "Operational state variables for logical aggregate / LAG interfaces"; uses interfaces-ios-xe-oper:lag-aggregate-state; } leaf ipv4-tcp-adjust-mss { type uint16; description "When ip tcp adjust-mss is configured, this value shows the tcp mss, or the value is zero."; } leaf ipv6-tcp-adjust-mss { type uint16; description "When ipv6 tcp adjust-mss is configured, this value shows the tcp mss, or the value is zero."; } choice interface-class-choice { description "The broad class that the interface belongs"; case interface-class-ethernet { container ether-state { description "The Ethernet state information"; uses interfaces-ios-xe-oper:ethernet-state; } container ether-stats { description "The Ethernet statistics"; uses interfaces-ios-xe-oper:ethernet-statistics; } } case interface-class-t1e1serial { container serial-state { description "The T1E1 serial state information"; uses interfaces-ios-xe-oper:t1e1-serial-state; } container serial-stats { description "The T1E1 statistics"; uses interfaces-ios-xe-oper:t1e1-serial-stats; } } case interface-class-unspecified { leaf intf-class-unspecified { type boolean; description "No specific interface class information"; } } case interface-class-syncserial { container syncserial-state { description "The synchronous serial state information"; uses interfaces-ios-xe-oper:sync-serial-state; } } } } container interfaces { config false; description "Operational state of interfaces"; list interface { key "name"; description "List of interfaces"; uses interfaces-ios-xe-oper:interface-state; } } } ###Markdown That's not so readable. Let's use a utility called ```pyang``` to get something a bit more readable. ###Code from subprocess import Popen, PIPE, STDOUT SCHEMA_TO_GET = 'Cisco-IOS-XE-interfaces-oper' c = m.get_schema(SCHEMA_TO_GET) # Simple pyang tree display # p = Popen(['pyang', '-f', 'tree'], stdout=PIPE, stdin=PIPE, stderr=PIPE) # Restrict display depth # p = Popen(['pyang', '-f', 'tree', '--tree-depth', '2'], stdout=PIPE, stdin=PIPE, stderr=PIPE) # Restrict display path p = Popen(['pyang', '-f', 'tree', '--tree-path', 'interfaces/interface/statistics'], stdout=PIPE, stdin=PIPE, stderr=PIPE) # Push the data from the get_schema through pyang stdout_data = p.communicate(input=c.data.encode())[0] print(stdout_data.decode()) ###Output _____no_output_____ ###Markdown What About Config?The ncclient library provides for some simple operations. Let's skip thinking about schemas and stuff like that. Instead let's focus on config and getting end setting it. For that, ncclient provides two methods:* get_config - takes a target data store and an optional filter* edit_config - takes a target data store and an XML document with the edit request Getting ConfigLet's look at some simple requests... ###Code c = m.get_config(source='running') pretty_print(c) ###Output _____no_output_____ ###Markdown Now let's add in a simple filter: ###Code filter = ''' <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <username/> </native> ''' with m.locked(target='running'): c = m.get_config(source='running', filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <username> <name>vagrant</name> <privilege>15</privilege> <password> <encryption>0</encryption> <password>vagrant</password> </password> </username> </native> </data> ###Markdown Retrieve Interface Config Data (Native Model) ###Code filter = ''' <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <interface/> </native> ''' c = m.get_config(source='running', filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <interface> <GigabitEthernet> <name>1</name> <ip> <address> <dhcp/> </address> <igmp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-igmp"> <explicit-tracking>false</explicit-tracking> <proxy-service>false</proxy-service> <unidirectional-link>false</unidirectional-link> <v3lite>false</v3lite> </igmp> </ip> <mop> <enabled>false</enabled> <sysid>false</sysid> </mop> <speed xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet"> <value-1000/> </speed> <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet"> <auto>false</auto> </negotiation> </GigabitEthernet> <GigabitEthernet> <name>2</name> <shutdown/> <ip> <igmp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-igmp"> <explicit-tracking>false</explicit-tracking> <proxy-service>false</proxy-service> <unidirectional-link>false</unidirectional-link> <v3lite>false</v3lite> </igmp> </ip> <mop> <enabled>false</enabled> <sysid>false</sysid> </mop> <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet"> <auto>true</auto> </negotiation> </GigabitEthernet> <GigabitEthernet> <name>3</name> <shutdown/> <ip> <igmp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-igmp"> <explicit-tracking>false</explicit-tracking> <proxy-service>false</proxy-service> <unidirectional-link>false</unidirectional-link> <v3lite>false</v3lite> </igmp> </ip> <mop> <enabled>false</enabled> <sysid>false</sysid> </mop> <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet"> <auto>true</auto> </negotiation> </GigabitEthernet> <GigabitEthernet> <name>4</name> <shutdown/> <ip> <igmp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-igmp"> <explicit-tracking>false</explicit-tracking> <proxy-service>false</proxy-service> <unidirectional-link>false</unidirectional-link> <v3lite>false</v3lite> </igmp> </ip> <mop> <enabled>false</enabled> <sysid>false</sysid> </mop> <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet"> <auto>true</auto> </negotiation> </GigabitEthernet> <Loopback> <name>100</name> <description>CLEU Demo</description> <ip> <address> <primary> <address>172.16.1.1</address> <mask>255.255.255.255</mask> </primary> </address> <igmp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-igmp"> <explicit-tracking>false</explicit-tracking> <proxy-service>false</proxy-service> <unidirectional-link>false</unidirectional-link> <v3lite>false</v3lite> </igmp> </ip> </Loopback> </interface> </native> </data> ###Markdown Retrieve Interface Data (Native Model) With XPath QueryAs well as subtree filters, **IOS-XE** supports XPath-based filters. ###Code filter = '/native/interface/GigabitEthernet/name' c = m.get_config(source='running', filter=('xpath', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <interface> <GigabitEthernet> <name>1</name> </GigabitEthernet> <GigabitEthernet> <name>2</name> </GigabitEthernet> <GigabitEthernet> <name>3</name> </GigabitEthernet> <GigabitEthernet> <name>4</name> </GigabitEthernet> </interface> </native> </data> ###Markdown Retrieve All BGP DataNow let's look at the BGP native model: ###Code filter = ''' <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"/> </router> </native> ''' c = m.get_config(source='running', filter=('subtree', filter)) pretty_print(c) ###Output _____no_output_____ ###Markdown Look At A Specific BGP NeighborAnd can we look at a specific neighbor only? Say the one with id (address) ```2.2.2.3```? ###Code filter = ''' <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id>100</id> <neighbor> <id>2.2.2.3</id> </neighbor> <address-family> <no-vrf> <ipv4> <af-name>unicast</af-name> <ipv4-unicast> <neighbor> <id>2.2.2.3</id> </neighbor> </ipv4-unicast> </ipv4> </no-vrf> </address-family> </bgp> </router> </native> ''' c = m.get_config(source='running', filter=('subtree', filter)) pretty_print(c) ###Output _____no_output_____ ###Markdown Create New BGP NeighborOk, so, yes we can get a specific neighbor. Now, can we create a new neighbor? Let's create one with an id of `2.2.2.4`, with a remote-as of 666. ###Code from ncclient.operations import TimeoutExpiredError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id>100</id> <neighbor> <id>2.2.2.4</id> <remote-as>666</remote-as> </neighbor> <address-family> <no-vrf> <ipv4> <af-name>unicast</af-name> <ipv4-unicast> <neighbor> <id>2.2.2.4</id> <activate/> </neighbor> </ipv4-unicast> </ipv4> </no-vrf> </address-family> </bgp> </router> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Now let's pull back some of the data for that neighbor: ###Code filter = ''' <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id>100</id> <neighbor> <id>2.2.2.4</id> </neighbor> </bgp> </router> </native> ''' c = m.get_config(source='running', filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">100</id> <neighbor> <id xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">2.2.2.4</id> <remote-as>666</remote-as> <timers> <keepalive-interval>60</keepalive-interval> <holdtime>180</holdtime> </timers> </neighbor> </bgp> </router> </native> </data> ###Markdown Modify The BGP Neighbor DescriptionCan modify something in the neighbor we just created? Let's keep it simple and modify the description: ###Code from ncclient.operations import TimeoutExpiredError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id>100</id> <neighbor> <id>2.2.2.4</id> <description nc:operation="merge">*** MODIFIED DESCRIPTION ***</description> </neighbor> </bgp> </router> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Delete A BGP Neighbor ###Code from ncclient.operations import TimeoutExpiredError from lxml.etree import XMLSyntaxError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp"> <id>100</id> <neighbor nc:operation="delete"> <id>2.2.2.4</id> </neighbor> <address-family> <no-vrf> <ipv4> <af-name>unicast</af-name> <ipv4-unicast> <neighbor nc:operation="delete"> <id>2.2.2.4</id> </neighbor> </ipv4-unicast> </ipv4> </no-vrf> </address-family> </bgp> </router> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except XMLSyntaxError as e: print(e) print(e.args) print(dir(e)) except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output severity=error, tag=data-missing {'type': 'application', 'tag': 'data-missing', 'severity': 'error', 'info': '<?xml version="1.0" encoding="UTF-8"?><error-info xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"><bad-element>neighbor</bad-element>\n</error-info>\n', 'path': "\n /nc:rpc/nc:edit-config/nc:config/ios:native/ios:router/ios-bgp:bgp[ios-bgp:id='100']/ios-bgp:neighbor[ios-bgp:id='2.2.2.4']\n ", 'message': None} ###Markdown Other Stuff Get interface operational data from native model: ###Code filter = ''' <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface/> </interfaces> ''' c = m.get(filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface> <name>Control Plane</name> <interface-type>iana-iftype-other</interface-type> <admin-status>if-state-up</admin-status> <oper-status>if-oper-state-ready</oper-status> <last-change>2020-01-19T15:11:26.873+00:00</last-change> <if-index>0</if-index> <phys-address>00:00:00:00:00:00</phys-address> <speed>10240000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>0</in-octets> <in-unicast-pkts>0</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>0</out-octets> <out-unicast-pkts>0</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>0</out-octets-64> </statistics> <vrf/> <description/> <mtu>0</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>00:00:00:00:00:00</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <intf-class-unspecified>true</intf-class-unspecified> </interface> <interface> <name>GigabitEthernet1</name> <interface-type>iana-iftype-ethernet-csmacd</interface-type> <admin-status>if-state-up</admin-status> <oper-status>if-oper-state-ready</oper-status> <last-change>2020-01-19T21:34:03.078+00:00</last-change> <if-index>1</if-index> <phys-address>08:00:27:2f:96:1b</phys-address> <speed>1024000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>795763</in-octets> <in-unicast-pkts>7629</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>6678326</out-octets> <out-unicast-pkts>6714</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>6678326</out-octets-64> </statistics> <vrf/> <ipv4>10.0.2.15</ipv4> <ipv4-subnet-mask>255.255.255.0</ipv4-subnet-mask> <description/> <mtu>1500</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>1725</in-pkts> <in-octets>182181</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>1533</out-pkts> <out-octets>1593544</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>1533</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>08:00:27:2f:96:1b</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <ether-state> <negotiated-duplex-mode>full-duplex</negotiated-duplex-mode> <negotiated-port-speed>speed-1gb</negotiated-port-speed> <auto-negotiate>false</auto-negotiate> <enable-flow-control>false</enable-flow-control> <media-type>ether-media-type-virtual</media-type> </ether-state> <ether-stats> <in-mac-control-frames>0</in-mac-control-frames> <in-mac-pause-frames>0</in-mac-pause-frames> <in-oversize-frames>0</in-oversize-frames> <in-jabber-frames>0</in-jabber-frames> <in-fragment-frames>0</in-fragment-frames> <in-8021q-frames>0</in-8021q-frames> <out-mac-control-frames>0</out-mac-control-frames> <out-mac-pause-frames>0</out-mac-pause-frames> <out-8021q-frames>0</out-8021q-frames> </ether-stats> </interface> <interface> <name>GigabitEthernet2</name> <interface-type>iana-iftype-ethernet-csmacd</interface-type> <admin-status>if-state-down</admin-status> <oper-status>if-oper-state-no-pass</oper-status> <last-change>2020-01-19T15:11:28.941+00:00</last-change> <if-index>2</if-index> <phys-address>08:00:27:8f:64:dc</phys-address> <speed>1024000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>0</in-octets> <in-unicast-pkts>0</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>0</out-octets> <out-unicast-pkts>0</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>0</out-octets-64> </statistics> <vrf/> <description/> <mtu>1500</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>08:00:27:8f:64:dc</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <ether-state> <negotiated-duplex-mode>full-duplex</negotiated-duplex-mode> <negotiated-port-speed>speed-1gb</negotiated-port-speed> <auto-negotiate>true</auto-negotiate> <enable-flow-control>false</enable-flow-control> <media-type>ether-media-type-virtual</media-type> </ether-state> <ether-stats> <in-mac-control-frames>0</in-mac-control-frames> <in-mac-pause-frames>0</in-mac-pause-frames> <in-oversize-frames>0</in-oversize-frames> <in-jabber-frames>0</in-jabber-frames> <in-fragment-frames>0</in-fragment-frames> <in-8021q-frames>0</in-8021q-frames> <out-mac-control-frames>0</out-mac-control-frames> <out-mac-pause-frames>0</out-mac-pause-frames> <out-8021q-frames>0</out-8021q-frames> </ether-stats> </interface> <interface> <name>GigabitEthernet3</name> <interface-type>iana-iftype-ethernet-csmacd</interface-type> <admin-status>if-state-down</admin-status> <oper-status>if-oper-state-no-pass</oper-status> <last-change>2020-01-19T15:11:28.942+00:00</last-change> <if-index>3</if-index> <phys-address>08:00:27:72:d6:8f</phys-address> <speed>1024000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>0</in-octets> <in-unicast-pkts>0</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>0</out-octets> <out-unicast-pkts>0</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>0</out-octets-64> </statistics> <vrf/> <description/> <mtu>1500</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>08:00:27:72:d6:8f</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <ether-state> <negotiated-duplex-mode>full-duplex</negotiated-duplex-mode> <negotiated-port-speed>speed-1gb</negotiated-port-speed> <auto-negotiate>true</auto-negotiate> <enable-flow-control>false</enable-flow-control> <media-type>ether-media-type-virtual</media-type> </ether-state> <ether-stats> <in-mac-control-frames>0</in-mac-control-frames> <in-mac-pause-frames>0</in-mac-pause-frames> <in-oversize-frames>0</in-oversize-frames> <in-jabber-frames>0</in-jabber-frames> <in-fragment-frames>0</in-fragment-frames> <in-8021q-frames>0</in-8021q-frames> <out-mac-control-frames>0</out-mac-control-frames> <out-mac-pause-frames>0</out-mac-pause-frames> <out-8021q-frames>0</out-8021q-frames> </ether-stats> </interface> <interface> <name>GigabitEthernet4</name> <interface-type>iana-iftype-ethernet-csmacd</interface-type> <admin-status>if-state-down</admin-status> <oper-status>if-oper-state-no-pass</oper-status> <last-change>2020-01-19T15:11:28.943+00:00</last-change> <if-index>4</if-index> <phys-address>08:00:27:86:41:2a</phys-address> <speed>1024000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>0</in-octets> <in-unicast-pkts>0</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>0</out-octets> <out-unicast-pkts>0</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>0</out-octets-64> </statistics> <vrf/> <description/> <mtu>1500</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>08:00:27:86:41:2a</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <ether-state> <negotiated-duplex-mode>full-duplex</negotiated-duplex-mode> <negotiated-port-speed>speed-1gb</negotiated-port-speed> <auto-negotiate>true</auto-negotiate> <enable-flow-control>false</enable-flow-control> <media-type>ether-media-type-virtual</media-type> </ether-state> <ether-stats> <in-mac-control-frames>0</in-mac-control-frames> <in-mac-pause-frames>0</in-mac-pause-frames> <in-oversize-frames>0</in-oversize-frames> <in-jabber-frames>0</in-jabber-frames> <in-fragment-frames>0</in-fragment-frames> <in-8021q-frames>0</in-8021q-frames> <out-mac-control-frames>0</out-mac-control-frames> <out-mac-pause-frames>0</out-mac-pause-frames> <out-8021q-frames>0</out-8021q-frames> </ether-stats> </interface> <interface> <name>Loopback100</name> <interface-type>iana-iftype-sw-loopback</interface-type> <admin-status>if-state-up</admin-status> <oper-status>if-oper-state-ready</oper-status> <last-change>2020-01-19T21:49:44.163+00:00</last-change> <if-index>7</if-index> <phys-address>00:1e:49:ea:3c:00</phys-address> <speed>8192000000</speed> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>0</in-octets> <in-unicast-pkts>0</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>0</out-octets> <out-unicast-pkts>0</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>0</out-octets-64> </statistics> <vrf/> <ipv4>172.16.1.1</ipv4> <ipv4-subnet-mask>255.255.255.255</ipv4-subnet-mask> <description>CLEU Demo</description> <mtu>1514</mtu> <input-security-acl/> <output-security-acl/> <v4-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v4-protocol-stats> <v6-protocol-stats> <in-pkts>0</in-pkts> <in-octets>0</in-octets> <in-error-pkts>0</in-error-pkts> <in-forwarded-pkts>0</in-forwarded-pkts> <in-forwarded-octets>0</in-forwarded-octets> <in-discarded-pkts>0</in-discarded-pkts> <out-pkts>0</out-pkts> <out-octets>0</out-octets> <out-error-pkts>0</out-error-pkts> <out-forwarded-pkts>0</out-forwarded-pkts> <out-forwarded-octets>0</out-forwarded-octets> <out-discarded-pkts>0</out-discarded-pkts> </v6-protocol-stats> <bia-address>00:00:00:00:00:00</bia-address> <ipv4-tcp-adjust-mss>0</ipv4-tcp-adjust-mss> <ipv6-tcp-adjust-mss>0</ipv6-tcp-adjust-mss> <intf-class-unspecified>true</intf-class-unspecified> </interface> </interfaces> </data> ###Markdown Get all interface names ###Code filter = ''' <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface> <name/> </interface> </interfaces> ''' c = m.get(filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface> <name>Control Plane</name> </interface> <interface> <name>GigabitEthernet1</name> </interface> <interface> <name>GigabitEthernet2</name> </interface> <interface> <name>GigabitEthernet3</name> </interface> <interface> <name>GigabitEthernet4</name> </interface> <interface> <name>Loopback100</name> </interface> </interfaces> </data> ###Markdown Get the statistics from a specific interface: ###Code filter = ''' <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface> <name>GigabitEthernet1</name> <statistics/> </interface> </interfaces> ''' c = m.get(filter=('subtree', filter)) pretty_print(c) ###Output <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <interfaces xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-interfaces-oper"> <interface> <name xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">GigabitEthernet1</name> <statistics> <discontinuity-time>2020-01-19T15:09:37+00:00</discontinuity-time> <in-octets>797761</in-octets> <in-unicast-pkts>7650</in-unicast-pkts> <in-broadcast-pkts>0</in-broadcast-pkts> <in-multicast-pkts>0</in-multicast-pkts> <in-discards>0</in-discards> <in-errors>0</in-errors> <in-unknown-protos>0</in-unknown-protos> <out-octets>6697678</out-octets> <out-unicast-pkts>6734</out-unicast-pkts> <out-broadcast-pkts>0</out-broadcast-pkts> <out-multicast-pkts>0</out-multicast-pkts> <out-discards>0</out-discards> <out-errors>0</out-errors> <rx-pps>0</rx-pps> <rx-kbps>0</rx-kbps> <tx-pps>0</tx-pps> <tx-kbps>0</tx-kbps> <num-flaps>0</num-flaps> <in-crc-errors>0</in-crc-errors> <in-discards-64>0</in-discards-64> <in-errors-64>0</in-errors-64> <in-unknown-protos-64>0</in-unknown-protos-64> <out-octets-64>6697678</out-octets-64> </statistics> </interface> </interfaces> </data> ###Markdown Exercise Constraints Create a VRF and put an interface into it ###Code from ncclient.operations import TimeoutExpiredError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <interface> <GigabitEthernet> <name>4</name> <vrf> <forwarding>TEST</forwarding> </vrf> <ip> <address> <primary> <address>192.168.1.222</address> <mask>255.255.255.0</mask> </primary> </address> </ip> </GigabitEthernet> </interface> <vrf> <definition> <name>TEST</name> <address-family> <ipv4/> </address-family> </definition> </vrf> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Try to delete the VRF ###Code from ncclient.operations import TimeoutExpiredError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <vrf> <definition nc:operation="delete"> <name>TEST</name> </definition> </vrf> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Delete the VRF right ###Code from ncclient.operations import TimeoutExpiredError import textwrap # get all interfaces where VRF "TEST" is bound xpath = "/native/interface/*/vrf[forwarding='TEST']" c = m.get(filter=('xpath', xpath)) # set operation=delete on every VRF found for e in c.data.xpath('//*[local-name()="vrf"]'): e.attrib['{urn:ietf:params:xml:ns:netconf:base:1.0}operation'] = "delete" # find the node "native" and add it to a config node and then run an edit config = etree.Element( "config", nsmap = {None: 'urn:ietf:params:xml:ns:netconf:base:1.0'}) config.append(c.data.xpath('//*[local-name()="native"]')[0]) # display what we will try to delete print('What we will no try to delete:\n') to_delete = etree.tostring(config, pretty_print=True).decode() print(textwrap.indent(to_delete, ' ') ) # now delete the VRF from, the interface try: with m.locked(target='running'): edit_reply = m.edit_config(config, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Try put an interface into a non-existent VRF ###Code from ncclient.operations import TimeoutExpiredError edit_data = ''' <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <interface> <GigabitEthernet> <name>3</name> <vrf> <forwarding>DOES_NOT_EXIST</forwarding> </vrf> <ip> <address> <primary> <address>192.168.2.222</address> <mask>255.255.255.0</mask> </primary> </address> </ip> </GigabitEthernet> </interface> </native> </config> ''' try: with m.locked(target='running'): edit_reply = m.edit_config(edit_data, target='running', format='xml') except TimeoutExpiredError as e: print("Operation timeout!") except Exception as e: print("severity={}, tag={}".format(e.severity, e.tag)) print(e) ###Output _____no_output_____ ###Markdown Alternate XML Creation ###Code from lxml import etree def create_interface_filter(intf_name): interfaces = etree.Element( "interfaces", nsmap = {None: 'http://openconfig.net/yang/interfaces'}) interface = etree.SubElement(interfaces, "interface") etree.SubElement(interface, 'name').text = intf_name state = etree.SubElement(interface, 'state') etree.SubElement(state, 'counters') return interfaces print(etree.tostring(create_interface_filter('MgmtEth0/RP0/CPU0/0'), pretty_print=True)) print(etree.tostring(create_interface_filter('GigabitEthernet1'), pretty_print=True)) ###Output _____no_output_____ ###Markdown Enable Debugging ###Code import logging handler = logging.StreamHandler() for l in ['ncclient.transport.ssh', 'ncclient.transport.session', 'ncclient.operations.rpc']: logger = logging.getLogger(l) logger.addHandler(handler) logger.setLevel(logging.DEBUG) ###Output _____no_output_____
hello-jupyter/hello.ipynb
###Markdown Getting Started with PythonA [love letter](https://code.visualstudio.com/docs/python/python-tutorial) from Microsoft: “Let’s get started by creating the simplest "Hello World" Python application.” ###Code msg = 'Hello World!' print(msg) ###Output Hello World! ###Markdown The code above is taken directly from my hello [sample](../hello/hello.py).Of course, for the sake of completion, I would like to run the plottting [sample](../hello/standardplot.py) as well. However this will not work. It will produce unexpected output as described in a StackOverflow.com [post](https://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline). The solution to this problem introduces the concept of the `inline` backend ([magic command](http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=backendsmagic-matplotlib)): ###Code %matplotlib inline #%% import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np x = np.linspace(0, 20, 100) plt.plot(x, np.sin(x)) plt.show() ###Output _____no_output_____
header_footer/biosignalsnotebooks_environment/categories/Connect/pairing_device.ipynb
###Markdown <div id="image_img" class="header_image_14"> Pairing a Device at Windows 10 [biosignalsplux] Difficulty Level: Tags connect&9729;pairing&9729;biosignalsplux&9729;bluetooth&9729;windows10 For acquiring physiological data there are three systems in interaction: human body (system under exploration); signal acquisition system/sensors (system responsible for collecting data from the human body) and computer/mobile device (system that receives and processes the data collected by the acquisition system).Plux&39;s acquisition systems (biosignalsplux and bitalino ) valorize wireless communication between the acquisition system and computer (using Bluetooth technology).The current Jupyter Notebook is intended to explain how Plux&39;s acquisition systems (biosignalsplux in our example) can be quickly connect to a computer in order to ensure future real-time acquisitions through OpenSignals . 0 - Before starting an acquisition it is mandatory that your Plux acquisition system (in our case biosignalsplux) is paired with the computer. It will be described, in the following steps, relevant instructions to fulfill this prerequisite ! The example is focused on Microsoft Windows 10 Users. For Mac users there are some relevant pages explaining how a Bluetooth device, like biosignalsplux can be paired. https://support.apple.com/en-us/HT201171 https://support.apple.com/guide/mac-help/connect-a-bluetooth-device-blth1004/mac*It is possible to use the internal Bluetooth of your computer, however to improve the connectivity and have more freedom of movement and avoid communication losses, we strongly recommend to use a Bluetooth Dongle like the one available at Plux Store . 1 - Turn on your biosignalsplux device 2 - Navigate until the Bluetooth communication system windowThis action is achievable through the "Start Menu" icon [bottom-left corner of the screen ] >> Settings >> Devices >> Bluetooth & other devices 3 - Enable Bluetooth communication system in your computer 4 - Click on "Add Bluetooth or other device"We are reaching the pairing stage between our computer and biosignalsplux device 5 - Click on "Bluetooth" option and wait for the list of available devices 6 - Find and click on the entry labeled with "biosignalsplux" 7 - Type the predefined password >> "123" Mission almost accomplished ! Now you should have your biosignalsplux device ready to use in OpenSignals software. 8 - Execute OpenSignals application in order to get access to the main page 9 - Press the "Device Configuration" icon for enabling your device 10 - Check which is your device mac-address (at the back of your device) 11 - Find your device on the "Device Configuration" pageYou should press the "Search" icon in order to the previously added device (through Windows interface) can appear For finishing the pairing between biosignalsplux and the computer, it is only necessary to click on the device box. When a set of configurable options appear the pairing process is officially completed ! The previous instructions represents a reasonable interactive guide for establishing a connection between Plux&39;s devices and your computer.If you follow these steps, now you are connected with biosignalsplux, which can be the start of an amazing journey ! We hope that you have enjoyed this guide. biosignalsnotebooks is an environment in continuous expansion, so don't stop your journey and learn more with the remaining Notebooks ! &9740; Project Presentation &9740; GitHub Repository &9740; How to install biosignalsnotebooks Python package ? &9740; Signal Library &9740; Notebook Categories &9740; Notebooks by Difficulty &9740; Notebooks by Signal Type &9740; Notebooks by Tag ###Code from biosignalsnotebooks.__notebook_support__ import css_style_apply css_style_apply() %%html <script> // AUTORUN ALL CELLS ON NOTEBOOK-LOAD! require( ['base/js/namespace', 'jquery'], function(jupyter, $) { $(jupyter.events).on("kernel_ready.Kernel", function () { console.log("Auto-running all cells-below..."); jupyter.actions.call('jupyter-notebook:run-all-cells-below'); jupyter.actions.call('jupyter-notebook:save-notebook'); }); } ); </script> ###Output _____no_output_____
immune_macrophages_GO.ipynb
###Markdown Functional characterization of novel macrophage phenotypes ###Code import numpy as np import pandas as pd import scanpy as sc import os import sys import warnings import anndata warnings.filterwarnings('ignore') def MovePlots(plotpattern, subplotdir): os.system('mkdir -p '+str(sc.settings.figdir)+'/'+subplotdir) os.system('mv '+str(sc.settings.figdir)+'/*'+plotpattern+'** '+str(sc.settings.figdir)+'/'+subplotdir) sc.settings.verbosity = 3 # verbosity: errors (0), warnings (1), info (2), hints (3) sc.settings.figdir = './final-figures/merged/myeloid/functional_analysis/' sc.logging.print_versions() sc.settings.set_figure_params(dpi=80) # low dpi (dots per inch) yields small inline figures sys.executable ###Output WARNING: If you miss a compact list, please try `print_header`! ###Markdown Took this function from: https://github.com/theislab/single-cell-tutorial/blob/master/latest_notebook/gprofiler_plotting.py ###Code # Plotting functions - 'GProfiler-official version' import matplotlib.pyplot as plt import seaborn as sb from matplotlib import colors from matplotlib import rcParams def scale_data_5_75(data): mind = np.min(data) maxd = np.max(data) if maxd == mind: maxd=maxd+1 mind=mind-1 drange = maxd - mind return ((((data - mind)/drange*0.70)+0.05)*100) def plot_enrich(data, n_terms=9, save=False): # Test data input if not isinstance(data, pd.DataFrame): raise ValueError('Please input a Pandas Dataframe output by gprofiler.') if not np.all([term in data.columns for term in ['p_value', 'name', 'intersection_size']]): raise TypeError('The data frame {} does not contain enrichment results from gprofiler.'.format(data)) data_to_plot = data.iloc[:n_terms,:].copy() data_to_plot['go.id'] = data_to_plot.index min_pval = data_to_plot['p_value'].min() max_pval = data_to_plot['p_value'].max() # Scale intersection_size to be between 5 and 75 for plotting #Note: this is done as calibration was done for values between 5 and 75 data_to_plot['scaled.overlap'] = scale_data_5_75(data_to_plot['intersection_size']) norm = colors.LogNorm(min_pval, max_pval) sm = plt.cm.ScalarMappable(cmap="OrRd", norm=norm) sm.set_array([]) rcParams.update({'font.size': 12, 'font.weight': 'normal'}) sb.set(style="whitegrid") path = plt.scatter(x='recall', y="name", c='p_value', cmap='OrRd', norm=colors.LogNorm(min_pval, max_pval), data=data_to_plot, linewidth=1, edgecolor="grey", s=[(i+10)**1.5 for i in data_to_plot['scaled.overlap']]) ax = plt.gca() ax.invert_yaxis() ax.set_ylabel('') ax.set_xlabel('Gene ratio', fontsize=12, fontweight='normal') ax.xaxis.grid(False) ax.yaxis.grid(True) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Get tick marks for this plot #Note: 6 ticks maximum min_tick = np.floor(np.log10(min_pval)).astype(int) max_tick = np.ceil(np.log10(max_pval)).astype(int) tick_step = np.ceil((max_tick - min_tick)/6).astype(int) # Ensure no 0 values if tick_step == 0: tick_step = 1 min_tick = max_tick-1 ticks_vals = [10**i for i in range(max_tick, min_tick-1, -tick_step)] ticks_labs = ['$10^{'+str(i)+'}$' for i in range(max_tick, min_tick-1, -tick_step)] #Colorbar fig = plt.gcf() cbaxes = fig.add_axes([0.8, 0.10, 0.03, 0.4]) cbar = ax.figure.colorbar(sm, ticks=ticks_vals, shrink=0.2, anchor=(0,0.1), cax=cbaxes) cbar.ax.set_yticklabels(ticks_labs) cbar.set_label("Adjusted p-value", fontsize=12, fontweight='normal') #Size legend min_olap = data_to_plot['intersection_size'].min() max_olap = data_to_plot['intersection_size'].max() olap_range = max_olap - min_olap #Note: approximate scaled 5, 25, 50, 75 values are calculated # and then rounded to nearest number divisible by 5 size_leg_vals = [np.round(i/5)*5 for i in [min_olap, min_olap+(20/70)*olap_range, min_olap+(45/70)*olap_range, max_olap]] size_leg_scaled_vals = scale_data_5_75(size_leg_vals) l1 = plt.scatter([],[], s=(size_leg_scaled_vals[0]+10)**1.5, edgecolors='none', color='black') l2 = plt.scatter([],[], s=(size_leg_scaled_vals[1]+10)**1.5, edgecolors='none', color='black') l3 = plt.scatter([],[], s=(size_leg_scaled_vals[2]+10)**1.5, edgecolors='none', color='black') l4 = plt.scatter([],[], s=(size_leg_scaled_vals[3]+10)**1.5, edgecolors='none', color='black') labels = [str(int(i)) for i in size_leg_vals] leg = plt.legend([l1, l2, l3, l4], labels, ncol=1, frameon=False, fontsize=12, handlelength=1, loc = 'center left', borderpad = 1, labelspacing = 1.4, handletextpad=2, title='Gene overlap', scatterpoints = 1, bbox_to_anchor=(-2, 1.5), facecolor='black') if save: plt.savefig(save, dpi=300, format='pdf') plt.show() from gprofiler import GProfiler ###Output _____no_output_____ ###Markdown Load data ###Code path_to_gonads = '/nfs/team292/vl6/immune_fetal_gonads/' adata = sc.read(path_to_gonads + 'macrophages.h5ad') sc.pl.umap(adata, color = 'clusters') adata.obs.to_csv(path_to_gonads + 'macrophage_annotations.csv') ###Output _____no_output_____ ###Markdown Differential expression analysis ###Code import rpy2.rinterface_lib.callbacks import logging # Ignore R warning messages #Note: this can be commented out to get more verbose R output rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR) import anndata2ri anndata2ri.activate() %load_ext rpy2.ipython import anndata adata = anndata.AnnData(X = adata.raw.X, var = adata.raw.var, obs = adata.obs) %%R -i adata adata %%R -o mrks library(SoupX) counts <- assay(adata, "X") colnames(counts) <- colnames(adata) rownames(counts) <- rownames(adata) mrks = quickMarkers(counts, colData(adata)$clusters, N = 100) # where clusters is the cell type assignment and 20 means I want the top 20 genes per cluster that pass the hypergeometric test mrks mrks.to_csv("/home/jovyan/Macrophages_markersTFIDF.csv") tissue_repair_markers = mrks[mrks['cluster'] == 'tissue-repair mac']['gene'].to_list() ifng_induced_markers = mrks[mrks['cluster'] == 'ifn-induced mac']['gene'].to_list() microglialike_markers = mrks[mrks['cluster'] == 'microglia-like mac']['gene'].to_list() osteoclastlike_markers = mrks[mrks['cluster'] == 'SIGLEC15+ mac']['gene'].to_list() len(tissue_repair_markers) ###Output _____no_output_____ ###Markdown gProfiler (GO-Biological Process enrichment)1. Tissue-repair mac ###Code gp = GProfiler( user_agent='ExampleTool', #optional user agent return_dataframe=True, #return pandas dataframe or plain python structures ) tissue_repair_enrichment = gp.profile(organism='hsapiens', sources=['GO:BP'], user_threshold=0.1, significance_threshold_method='fdr', background=adata.var_names.tolist(), query=tissue_repair_markers) tissue_repair_results = tissue_repair_enrichment.set_index('native').sort_values('p_value').iloc[:,[2,5,7,10,1]] pd.set_option("display.max_colwidth", 800) tissue_repair_results.iloc[:30,:] selected_terms_tissue_repair = ['response to stimulus', 'inflammatory response', 'response to oxygen-containing compound'] selected_terms_tissue_repair = tissue_repair_results[tissue_repair_results['name'].isin(selected_terms_tissue_repair)] selected_terms_tissue_repair selected_terms_tissue_repair.reset_index(level=0, inplace=True) selected_terms_tissue_repair.style.hide_index() style = selected_terms_tissue_repair.style.set_table_styles([{'selector' : '', 'props' : [('border', '3px solid #d9abb7'), ('background-color', '#d9abb7')]}]) style.hide_index() tissue_repair_results.iloc[:100,:].to_csv('/home/jovyan/TissueRepair_GO.csv') ###Output _____no_output_____ ###Markdown 2. IFN-induced mac ###Code gp = GProfiler( user_agent='ExampleTool', #optional user agent return_dataframe=True, #return pandas dataframe or plain python structures ) ifn_induced_enrichment = gp.profile(organism='hsapiens', sources=['GO:BP'], user_threshold=0.1, significance_threshold_method='fdr', background=adata.var_names.tolist(), query=ifng_induced_markers) ifn_induced_results = ifn_induced_enrichment.set_index('native').sort_values('p_value').iloc[:,[2,5,7,10,1]] pd.set_option("display.max_colwidth", 800) ifn_induced_results.iloc[:30,:] selected_terms_IFN = ['response to cytokine', 'type I interferon signaling pathway', 'response to interferon-gamma'] selected_results_IFN = ifn_induced_results[ifn_induced_results['name'].isin(selected_terms_IFN)] selected_results_IFN selected_results_IFN.reset_index(level=0, inplace=True) selected_results_IFN selected_results_IFN.style.hide_index() style = selected_results_IFN.style.set_table_styles([{'selector' : '', 'props' : [('border', '3px solid #e64e74'), ('background-color', '#e64e74')]}]) style.hide_index() ifn_induced_results.iloc[:100,:].to_csv('/home/jovyan/IFNInduced_GO.csv') ###Output _____no_output_____ ###Markdown 3. Microglia-like mac ###Code gp = GProfiler( user_agent='ExampleTool', #optional user agent return_dataframe=True, #return pandas dataframe or plain python structures ) microglia_enrichment = gp.profile(organism='hsapiens', sources=['GO:BP'], user_threshold=0.1, significance_threshold_method='fdr', background=adata.var_names.tolist(), query=microglialike_markers) microglia_results = microglia_enrichment.set_index('native').sort_values('p_value').iloc[:,[2,5,7,10,1]] pd.set_option("display.max_colwidth", 800) microglia_results.iloc[:30,:] selected_terms_microglia = ['regulation of microglial cell migration', 'regulation of glial cell migration', 'positive regulation of macrophage migration'] selected_results_microglia = microglia_results[microglia_results['name'].isin(selected_terms_microglia)] selected_results_microglia selected_results_microglia.reset_index(level=0, inplace=True) style1 = selected_results_microglia.style.set_table_styles([{'selector' : '', 'props' : [('border', '3px solid #d9a5c3'), ('background-color', '#d9a5c3')]}]) style1.hide_index() microglia_results.iloc[:100,:].to_csv('/home/jovyan/Microglia_GO.csv') ###Output _____no_output_____ ###Markdown 4. Osteoclast-like mac ###Code gp = GProfiler( user_agent='ExampleTool', #optional user agent return_dataframe=True, #return pandas dataframe or plain python structures ) osteoclast_enrichment = gp.profile(organism='hsapiens', sources=['GO:BP'], user_threshold=0.1, significance_threshold_method='fdr', background=adata.var_names.tolist(), query=osteoclastlike_markers) osteoclast_results = osteoclast_enrichment.set_index('native').sort_values('p_value').iloc[:,[2,5,7,10,1]] pd.set_option("display.max_colwidth", 800) osteoclast_results.iloc[:30,:] selected_terms_osteoclast = ['extracellular matrix organization', 'bone remodeling', 'osteoclast differentiation'] selected_results_osteoclast = osteoclast_results[osteoclast_results['name'].isin(selected_terms_osteoclast)] selected_results_osteoclast selected_results_osteoclast.reset_index(level=0, inplace=True) style2 = selected_results_osteoclast.style.set_table_styles([{'selector' : '', 'props' : [('border', '3px solid #cc8fdb'), ('background-color', '#cc8fdb')]}]) style2.hide_index() osteoclast_results.iloc[:100,:].to_csv('/home/jovyan/SIGLEC15_GO.csv') ###Output _____no_output_____
utf-8''module_3_assignment.ipynb
###Markdown Module 3 AssignmentYour objective in this assignment is to implement a tennis ball detector using a pre-trained image classification network from GluonCV. We'll step through the pipeline, from loading and transforming an input image, to loading and using a pre-trained model. Since we're only interested in detecting tennis balls, this is a binary classification problem, which is slightly different to the multi-class classification setup we've seen so far. 0) SetupWe start with some initial setup: importing packages and setting the path to the data. ###Code import mxnet as mx import gluoncv as gcv import matplotlib.pyplot as plt import numpy as np import os from pathlib import Path M3_DATA = Path(os.getenv('DATA_DIR', '../../data'), 'module_3') M3_IMAGES = Path(M3_DATA, 'images') M3_MODELS = Path(M3_DATA, 'models') ###Output _____no_output_____ ###Markdown 1) Loading an imageYour first task is to implement a function that loads an image from disk given a filepath.It should return an 8-bit image array, that's in MXNet's NDArray format and in HWC layout (i.e. height, width then channel). ###Code def load_image(filepath): """ Should load image from disk. :param filepath: relative or absolute filepath to RGB image file in JPG format. :type filepath: str :return: an array with pixel intensities (in HWC layout). :rtype: mx.nd.NDArray """ # YOUR CODE HERE image = mx.image.imread(filepath) return image test_filepath = Path(M3_IMAGES, 'ben-hershey-VEW78A1YZ6I-unsplash.jpg') test_output = load_image(test_filepath) assert test_output.shape[2] == 3 # RGB assert test_output.dtype == np.uint8 # 0 - 255 assert isinstance(test_output, mx.nd.NDArray) # MXNet NDArray, not NumPy Array. test_output.shape ###Output _____no_output_____ ###Markdown 2) Transforming an imageUp next, you should transform the image so it can be used as input to the pre-trained network.Since we're going to use an ImageNet pre-trained network, we need to follow the same steps used for ImageNet pre-training.See the docstring for more details, but don't forget that GluonCV contains a number of utilities and helper functions to make your life easier! Check out the preset transforms. ###Code def transform_image(array): """ Should transform image by: 1) Resizing the shortest dimension to 224. e.g (448, 1792) -> (224, 896). 2) Cropping to a center square of dimension (224, 224). 3) Converting the image from HWC layout to CHW layout. 4) Normalizing the image using ImageNet statistics (i.e. per colour channel mean and variance). 5) Creating a batch of 1 image. :param filepath: array (in HWC layout). :type filepath: mx.nd.NDArray :return: a batch of a single transformed images (in NCHW layout) :rtype: mx.nd.NDArray """ transformed_img = gcv.data.transforms.presets.imagenet.transform_eval(array) # YOUR CODE HERE return transformed_img transformed_test_output = transform_image(test_output) assert transformed_test_output.shape == (1, 3, 224, 224) assert transformed_test_output.dtype == np.float32 transformed_test_output.shape ###Output _____no_output_____ ###Markdown 3) Loading a modelWith the image loaded and transformed, you now need to load a pre-trained classification model.Choose a MobileNet 1.0 image classification model that's been pre-trained on ImageNet.**CAUTION!**: Although the notebook interface has internet connectivity, the **autograders are not permitted to access the internet**. We have already downloaded the correct models and data for you to use so you don't need access to the internet. However, you do need to specify the correct path to the models when loading a model from the Gluon CV Model Zoo using `get_model` or otherwise. Set the `root` parameter to `M3_MODELS`. As an example, you should have something similar to `gcv.model_zoo.get_model(..., root=M3_MODELS)`. Usually, in the real world, you have internet access, so setting the `root` parameter isn't required (and it's set to `~/.mxnet` by default). ###Code def load_pretrained_classification_network(): """ Loads a MobileNet 1.0 network that's been pre-trained on ImageNet. :return: a pre-trained network :rtype: mx.gluon.Block """ # YOUR CODE HERE model = gcv.model_zoo.get_model('MobileNet1.0', pretrained=True, root = M3_MODELS) return model network = load_pretrained_classification_network() assert isinstance(network, mx.gluon.Block), 'Model should be a Gluon Block' assert network.name.startswith('mobilenet'), 'Select MobileNet' params = network.collect_params(select=network.name + '_conv0_weight') assert list(params.items())[0][1].shape[0] == 32, 'Select MobileNet1.0' #3network ###Output _____no_output_____ ###Markdown 4) Using a modelYour next task is to pass your transformed image through the network to obtain predicted probabilities for all ImageNet classes.We'll ignore the requirement of creating just a tennis ball classifier for now.**Hint 1**: Don't forget that you're typically working with a batch of images, even when you only have one image.**Hint 2**: Remember that the direct outputs of our network aren't probabilities. ###Code def predict_probabilities(network, data): """ Should return the predicted probabilities of ImageNet classes for the given image. :param network: pre-trained image classification model :type network: mx.gluon.Block :param data: batch of transformed images of shape (1, 3, 224, 224) :type data: mx.nd.NDArray :return: array of probabilities of shape (1000,) :rtype: mx.nd.NDArray """ # YOUR CODE HERE prediction = network(data) prediction = prediction[0] probability = mx.nd.softmax(prediction) return probability pred_probas = predict_probabilities(network, transformed_test_output) assert pred_probas.shape == (1000,) np.testing.assert_almost_equal(pred_probas.sum().asscalar(), 1, decimal=5) assert pred_probas.dtype == np.float32 pred_probas pred_probas.shape pred_probas.dtype ###Output _____no_output_____ ###Markdown 5) Finding Class LabelSince we're only interested in tennis ball classification for now, we need a method of finding the probability associated with tennis ball out of the 1000 classes.You should implement a function that returns the index of a given class label (e.g. `admiral` is index `321`)**Hint**: you're allowed to use variables that are defined globally on this occasion. You should think about which objects that have been previously defined has a list of class labels. ###Code def find_class_idx(label): """ Should return the class index of a particular label. :param label: label of class :type label: str :return: class index :rtype: int """ # YOUR CODE HERE for i in range(len(network.classes)): if label == network.classes[i]: return i assert find_class_idx('tennis ball') == 852 assert find_class_idx('spiny lobster') == 123 assert find_class_idx('admiral') == 321 ###Output _____no_output_____ ###Markdown 6) Slice Tennis Ball ClassUsing the above function to find the correct index for tennis ball, you should implement a function to slice the calculated probability for tennis ball from the 1000 class probabilities calculated by the network. It should also convert the probability from MXNet `NDArray` to a NumPy `float32`.We'll use this for our confidence score that the image is a tennis ball. ###Code def slice_tennis_ball_class(pred_probas): """ Extracts the probability associated with tennis ball. :param pred_probas: array of ImageNet probabilities of shape (1000,) :type pred_probas: mx.nd.NDArray :return: probability of tennis ball :rtype: np.float32 """ # YOUR CODE HERE tennis_prob = pred_probas[find_class_idx('tennis ball')] return tennis_prob.astype('float32').asscalar() pred_proba_tennis_ball = slice_tennis_ball_class(pred_probas) assert isinstance(pred_proba_tennis_ball, np.float32) np.testing.assert_almost_equal(pred_proba_tennis_ball, 0.9987876, decimal=3) pred_proba_tennis_ball ###Output _____no_output_____ ###Markdown 7) Classify Tennis Ball ImagesWe'll finish this assignment by bringing all of the components together and creating a `TennisBallClassifier` to classify images. You should implement the entire classification pipeline inside the `classify` function using the functions defined earlier on in the assignment. You should notice that the pre-trained model is loaded once during initialization, and then it should be used inside the `classify` method. ###Code class TennisBallClassifier(): def __init__(self): self._network = load_pretrained_classification_network() def classify(self, filepath): # YOUR CODE HERE image = load_image(filepath) transformed_image = transform_image(image) self._visualize(transformed_image) # YOUR CODE HERE pred_probas = predict_probabilities(self._network, transformed_image) pred_proba = slice_tennis_ball_class(pred_probas) print('{0:.2%} confidence that image is a tennis ball.'.format(pred_proba)) return pred_proba def _visualize(self, transformed_image): """ Since the transformed_image is in NCHW layout and the values are normalized, this method slices and transposes to give CHW as required by matplotlib, and scales (-2, +2) to (0, 255) linearly. """ chw_image = transformed_image[0].transpose((1,2,0)) chw_image = ((chw_image * 64) + 128).clip(0, 255).astype('uint8') plt.imshow(chw_image.asnumpy()) classifier = TennisBallClassifier() filepath = Path(M3_IMAGES, 'erik-mclean-D23_XPbsx-8-unsplash.jpg') pred_proba = classifier.classify(filepath) np.testing.assert_almost_equal(pred_proba, 2.0355723e-05, decimal=3) filepath = Path(M3_IMAGES, 'marvin-ronsdorf-CA998Anw2Lg-unsplash.jpg') pred_proba = classifier.classify(filepath) np.testing.assert_almost_equal(pred_proba, 0.9988895, decimal=3) ###Output 99.92% confidence that image is a tennis ball.
docs/pages/examples/minimum_energy_fast.ipynb
###Markdown Energy settings ###Code # setup states n_nodes = A.shape[0] n_states = int(n_nodes/10) state_size = int(n_nodes/n_states) states = np.array([]) for i in np.arange(n_states): states = np.append(states, np.ones(state_size) * i) states = states.astype(int) print(states) ###Output [ 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 11 11 11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 12 12 12 13 13 13 13 13 13 13 13 13 13 14 14 14 14 14 14 14 14 14 14 15 15 15 15 15 15 15 15 15 15 16 16 16 16 16 16 16 16 16 16 17 17 17 17 17 17 17 17 17 17 18 18 18 18 18 18 18 18 18 18 19 19 19 19 19 19 19 19 19 19] ###Markdown Minimum energy ###Code from network_control.utils import matrix_normalization from network_control.energies import minimum_energy # settings # time horizon T = 1 # set all nodes as control nodes B = np.eye(n_nodes) # normalize A matrix for a continuous-time system A = matrix_normalization(A, version='continuous') import time start_time = time.time() # start timer e = np.zeros((n_states, n_states, n_nodes)) for i in np.arange(n_states): x0 = states == i # get ith initial state for j in np.arange(n_states): xf = states == j # get jth target state m_x, m_u, n_err = minimum_energy(A, T, B, x0, xf) e[i, j, :] = np.sum(np.square(m_u), axis=0) end_time = time.time() # stop timer elapsed_time = end_time - start_time print('time elapsed in seconds: {:.2f}'.format(elapsed_time)) # print elapsed time ###Output time elapsed in seconds: 38.15 ###Markdown Minimum energy fast ###Code from network_control.utils import expand_states x0_mat, xf_mat = expand_states(states) print(x0_mat.shape, xf_mat.shape) from network_control.energies import minimum_energy_fast start_time = time.time() # start timer e_fast = minimum_energy_fast(A, T, B, x0_mat, xf_mat) e_fast = e_fast.transpose().reshape(n_states, n_states, n_nodes) end_time = time.time() # stop timer elapsed_time = end_time - start_time print('time elapsed in seconds: {:.2f}'.format(elapsed_time)) # print elapsed time print(e.shape) print(e_fast.shape) ###Output (20, 20, 200) (20, 20, 200) ###Markdown Plots ###Code import matplotlib.pyplot as plt import seaborn as sns from network_control.plotting import set_plotting_params, reg_plot set_plotting_params() # sum energy over regions e_sum = np.sum(e, axis=2) e_fast_sum = np.sum(e_fast, axis=2) # compute correlations across regional energy for each transition separately r = np.zeros((n_states, n_states)) for i in np.arange(n_states): for j in np.arange(n_states): r[i, j] = sp.stats.pearsonr(e[i, j, :], e_fast[i, j, :])[0] # plot f, ax = plt.subplots(1, 2, figsize=(5, 2.5)) # correlation between whole-brain energy across state transitions mask = ~np.eye(n_states, dtype=bool) indices = np.where(mask) reg_plot(x=e_sum[indices], y=e_fast_sum[indices], xlabel='minumum energy', ylabel='minumum energy (fast)', ax=ax[0], add_spearman=True, kdeplot=False, regplot=False) # energy correlated across regions for each state transition separately sns.heatmap(r, square=True, ax=ax[1], cbar_kws={"shrink": 0.80}) ax[1].set_ylabel("initial states", labelpad=-1) ax[1].set_xlabel("target states", labelpad=-1) ax[1].set_yticklabels('') ax[1].set_xticklabels('') ax[1].tick_params(pad=-2.5) plt.show() f.savefig('minimum_energy_fast', dpi=300, bbox_inches='tight', pad_inches=0.1) plt.close() ###Output _____no_output_____
Course 2- NLP with probabilistic Model/Labs/NLP Week 3 Lab/NLP_C2_W3_lecture_nb_03.ipynb
###Markdown Out of vocabulary words (OOV) VocabularyIn the video about the out of vocabulary words, you saw that the first step in dealing with the unknown words is to decide which words belong to the vocabulary. In the code assignment, you will try the method based on minimum frequency - all words appearing in the training set with frequency >= minimum frequency are added to the vocabulary.Here is a code for the other method, where the target size of the vocabulary is known in advance and the vocabulary is filled with words based on their frequency in the training set. ###Code # build the vocabulary from M most frequent words # use Counter object from the collections library to find M most common words from collections import Counter # the target size of the vocabulary M = 3 # pre-calculated word counts # Counter could be used to build this dictionary from the source corpus word_counts = {'happy': 5, 'because': 3, 'i': 2, 'am': 2, 'learning': 3, '.': 1} vocabulary = Counter(word_counts).most_common(M) # remove the frequencies and leave just the words vocabulary = [w[0] for w in vocabulary] print(f"the new vocabulary containing {M} most frequent words: {vocabulary}\n") ###Output _____no_output_____ ###Markdown Now that the vocabulary is ready, you can use it to replace the OOV words with $$ as you saw in the lecture. ###Code # test if words in the input sentences are in the vocabulary, if OOV, print <UNK> sentence = ['am', 'i', 'learning'] output_sentence = [] print(f"input sentence: {sentence}") for w in sentence: # test if word w is in vocabulary if w in vocabulary: output_sentence.append(w) else: output_sentence.append('<UNK>') print(f"output sentence: {output_sentence}") ###Output _____no_output_____ ###Markdown When building the vocabulary in the code assignment, you will need to know how to iterate through the word counts dictionary. Here is an example of a similar task showing how to go through all the word counts and print out only the words with the frequency equal to f. ###Code # iterate through all word counts and print words with given frequency f f = 3 word_counts = {'happy': 5, 'because': 3, 'i': 2, 'am': 2, 'learning':3, '.': 1} for word, freq in word_counts.items(): if freq == f: print(word) ###Output _____no_output_____ ###Markdown As mentioned in the videos, if there are many $$ replacements in your train and test set, you may get a very low perplexity even though the model itself wouldn't be very helpful. Here is a sample code showing this unwanted effect. ###Code # many <unk> low perplexity training_set = ['i', 'am', 'happy', 'because','i', 'am', 'learning', '.'] training_set_unk = ['i', 'am', '<UNK>', '<UNK>','i', 'am', '<UNK>', '<UNK>'] test_set = ['i', 'am', 'learning'] test_set_unk = ['i', 'am', '<UNK>'] M = len(test_set) probability = 1 probability_unk = 1 # pre-calculated probabilities bigram_probabilities = {('i', 'am'): 1.0, ('am', 'happy'): 0.5, ('happy', 'because'): 1.0, ('because', 'i'): 1.0, ('am', 'learning'): 0.5, ('learning', '.'): 1.0} bigram_probabilities_unk = {('i', 'am'): 1.0, ('am', '<UNK>'): 1.0, ('<UNK>', '<UNK>'): 0.5, ('<UNK>', 'i'): 0.25} # got through the test set and calculate its bigram probability for i in range(len(test_set) - 2 + 1): bigram = tuple(test_set[i: i + 2]) probability = probability * bigram_probabilities[bigram] bigram_unk = tuple(test_set_unk[i: i + 2]) probability_unk = probability_unk * bigram_probabilities_unk[bigram_unk] # calculate perplexity for both original test set and test set with <UNK> perplexity = probability ** (-1 / M) perplexity_unk = probability_unk ** (-1 / M) print(f"perplexity for the training set: {perplexity}") print(f"perplexity for the training set with <UNK>: {perplexity_unk}") ###Output _____no_output_____ ###Markdown Smoothing Add-k smoothing was described as a method for smoothing of the probabilities for previously unseen n-grams. Here is an example code that shows how to implement add-k smoothing but also highlights a disadvantage of this method. The downside is that n-grams not previously seen in the training dataset get too high probability. In the code output bellow you'll see that a phrase that is in the training set gets the same probability as an unknown phrase. ###Code def add_k_smooting_probability(k, vocabulary_size, n_gram_count, n_gram_prefix_count): numerator = n_gram_count + k denominator = n_gram_prefix_count + k * vocabulary_size return numerator / denominator trigram_probabilities = {('i', 'am', 'happy') : 2} bigram_probabilities = {( 'am', 'happy') : 10} vocabulary_size = 5 k = 1 probability_known_trigram = add_k_smooting_probability(k, vocabulary_size, trigram_probabilities[('i', 'am', 'happy')], bigram_probabilities[( 'am', 'happy')]) probability_unknown_trigram = add_k_smooting_probability(k, vocabulary_size, 0, 0) print(f"probability_known_trigram: {probability_known_trigram}") print(f"probability_unknown_trigram: {probability_unknown_trigram}") ###Output _____no_output_____ ###Markdown Back-offBack-off is a model generalization method that leverages information from lower order n-grams in case information about the high order n-grams is missing. For example, if the probability of an trigram is missing, use bigram information and so on.Here you can see an example of a simple back-off technique. ###Code # pre-calculated probabilities of all types of n-grams trigram_probabilities = {('i', 'am', 'happy'): 0} bigram_probabilities = {( 'am', 'happy'): 0.3} unigram_probabilities = {'happy': 0.4} # this is the input trigram we need to estimate trigram = ('are', 'you', 'happy') # find the last bigram and unigram of the input bigram = trigram[1: 3] unigram = trigram[2] print(f"besides the trigram {trigram} we also use bigram {bigram} and unigram ({unigram})\n") # 0.4 is used as an example, experimentally found for web-scale corpuses when using the "stupid" back-off lambda_factor = 0.4 probability_hat_trigram = 0 # search for first non-zero probability starting with trigram # to generalize this for any order of n-gram hierarchy, # you could loop through the probability dictionaries instead of if/else cascade if trigram not in trigram_probabilities or trigram_probabilities[trigram] == 0: print(f"probability for trigram {trigram} not found") if bigram not in bigram_probabilities or bigram_probabilities[bigram] == 0: print(f"probability for bigram {bigram} not found") if unigram in unigram_probabilities: print(f"probability for unigram {unigram} found\n") probability_hat_trigram = lambda_factor * lambda_factor * unigram_probabilities[unigram] else: probability_hat_trigram = 0 else: probability_hat_trigram = lambda_factor * bigram_probabilities[bigram] else: probability_hat_trigram = trigram_probabilities[trigram] print(f"probability for trigram {trigram} estimated as {probability_hat_trigram}") ###Output _____no_output_____ ###Markdown InterpolationThe other method for using probabilities of lower order n-grams is the interpolation. In this case, you use weighted probabilities of n-grams of all orders every time, not just when high order information is missing. For example, you always combine trigram, bigram and unigram probability. You can see how this in the following code snippet. ###Code # pre-calculated probabilities of all types of n-grams trigram_probabilities = {('i', 'am', 'happy'): 0.15} bigram_probabilities = {( 'am', 'happy'): 0.3} unigram_probabilities = {'happy': 0.4} # the weights come from optimization on a validation set lambda_1 = 0.8 lambda_2 = 0.15 lambda_3 = 0.05 # this is the input trigram we need to estimate trigram = ('i', 'am', 'happy') # find the last bigram and unigram of the input bigram = trigram[1: 3] unigram = trigram[2] print(f"besides the trigram {trigram} we also use bigram {bigram} and unigram ({unigram})\n") # in the production code, you would need to check if the probability n-gram dictionary contains the n-gram probability_hat_trigram = lambda_1 * trigram_probabilities[trigram] + lambda_2 * bigram_probabilities[bigram] + lambda_3 * unigram_probabilities[unigram] print(f"estimated probability of the input trigram {trigram} is {probability_hat_trigram}") ###Output _____no_output_____
[DIR] corporation_list_by_state_2016/corporation_list_by_state_2016.ipynb
###Markdown Corporation List By State**Authors:** Patrick Guo Documenting file sizes of Corporations Lists by State in 2016 ###Code import boto3 import numpy as np import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt %matplotlib inline from collections import Counter import statistics client = boto3.client('s3') resource = boto3.resource('s3') my_bucket = resource.Bucket('daanmatchdatafiles') ###Output _____no_output_____ ###Markdown Files ###Code companies = 0 ###Output _____no_output_____ ###Markdown Andaman_Nicobar_Islands_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Andaman_Nicobar_Islands_2016.xlsx" Andaman_Nicobar_Islands_2016 = pd.ExcelFile(path) print(Andaman_Nicobar_Islands_2016.sheet_names) # Combine both sheets Andaman_Nicobar_Islands_2016_1 = Andaman_Nicobar_Islands_2016.parse('Sheet1') Andaman_Nicobar_Islands_2016_2 = Andaman_Nicobar_Islands_2016.parse('Sheet2') Andaman_Nicobar_Islands_2016_merged = Andaman_Nicobar_Islands_2016_1.append(Andaman_Nicobar_Islands_2016_2) # Reset index Andaman_Nicobar_Islands_2016_merged = Andaman_Nicobar_Islands_2016_merged.reset_index(drop=True) Andaman_Nicobar_Islands_2016_merged.head() shape = Andaman_Nicobar_Islands_2016_merged.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (24979, 15) ###Markdown Andhra_Pradesh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Andhra_Pradesh_2016.xlsx" Andhra_Pradesh_2016 = pd.ExcelFile(path) print(Andhra_Pradesh_2016.sheet_names) Andhra_Pradesh_2016 = Andhra_Pradesh_2016.parse("Sheet3") Andhra_Pradesh_2016.head() shape = Andhra_Pradesh_2016.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (24661, 15) ###Markdown Arunachal_Pradesh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Arunachal_Pradesh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) Arunachal_Pradesh_2016 = xl.parse("Sheet3") Arunachal_Pradesh_2016.head() shape = Arunachal_Pradesh_2016.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (507, 15) ###Markdown Bihar_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Bihar_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (23550, 15) ###Markdown Chandigarh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Chandigarh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (13418, 15) ###Markdown Chattisgarh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Chattisgarh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (8413, 15) ###Markdown Dadar_Nagar_Haveli_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Dadar_Nagar_Haveli_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (472, 15) ###Markdown Daman_and_Diu_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Daman_and_Diu_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (327, 15) ###Markdown Goa_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Goa_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (7756, 15) ###Markdown Gujarat_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Gujarat_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (87613, 15) ###Markdown Haryana_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Haryana_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Haryana") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (32014, 15) ###Markdown Himachal_Pradesh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Himachal_Pradesh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (5200, 15) ###Markdown Jammu_and_Kashmir_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Jammu_and_Kashmir_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (4426, 15) ###Markdown Jharkhand_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Jharkhand_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) # Sheet 1 does not provide helpful information df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (10409, 15) ###Markdown Karnataka_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Karnataka_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (91425, 15) ###Markdown Kerala_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Kerala_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (41851, 15) ###Markdown Lakshadweep_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Lakshadweep_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (13, 15) ###Markdown Madhya Pradesh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Madhya Pradesh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (32463, 15) ###Markdown Maharastra_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Maharastra_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (320957, 15) ###Markdown Manipur_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Manipur_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (477, 15) ###Markdown Meghalaya_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Meghalaya_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (966, 15) ###Markdown Mizoram_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Mizoram_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (113, 15) ###Markdown Nagaland_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Nagaland_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (512, 15) ###Markdown Odisha_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Odisha_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (20543, 15) ###Markdown Puducherry_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Puducherry_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (2894, 15) ###Markdown Punjab_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Punjab_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (27607, 15) ###Markdown Rajasthan_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Rajasthan_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (49808, 15) ###Markdown Tamil_Nadu_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Tamil_Nadu_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (124522, 15) ###Markdown Telangana_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Telangana_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (86553, 15) ###Markdown Tripura_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Tripura_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (387, 15) ###Markdown Uttar_Pradesh_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Uttar_Pradesh_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (77818, 15) ###Markdown Uttarakhand_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/Uttarakhand_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (5598, 15) ###Markdown West_Bengal_2016 ###Code path = "s3://daanmatchdatafiles/corporation_list_by_state_2016/West_Bengal_2016.xlsx" xl = pd.ExcelFile(path) print(xl.sheet_names) df = xl.parse("Sheet3") df.head() shape = df.shape print("Shape:", shape) companies += shape[0] ###Output Shape: (191029, 15) ###Markdown Total ###Code print("Number of comapnies:", companies) ###Output _____no_output_____
sandbox/generate_regression_sp-Copy1.ipynb
###Markdown Generating Simpson's ParadoxWe have been maually setting, but now we should also be able to generate it more programatically. his notebook will describe how we develop some functions that will be included in the `sp_data_util` package. ###Code # %load code/env # standard imports we use throughout the project import numpy as np import pandas as pd import seaborn as sns import scipy.stats as stats import matplotlib.pyplot as plt import mlsim from mlsim import sp_plot ###Output _____no_output_____ ###Markdown We have been thinking of SP hrough gaussian mixture data, so we'll first work wih that. To cause SP we need he clusters to have an opposite trend of the per cluster covariance. ###Code # setup r_clusters = -.6 # correlation coefficient of clusters cluster_spread = .8 # pearson correlation of means p_sp_clusters = .5 # portion of clusters with SP k = 5 # number of clusters cluster_size = [2,3] domain_range = [0, 20, 0, 20] N = 200 # number of points p_clusters = [1.0/k]*k # keep all means in the middle 80% mu_trim = .2 # sample means center = [np.mean(domain_range[:2]),np.mean(domain_range[2:])] mu_transform = np.repeat(np.diff(domain_range)[[0,2]]*(mu_trim),2) mu_transform[[1,3]] = mu_transform[[1,3]]*-1 # sign flip every other mu_domain = [d + m_t for d, m_t in zip(domain_range,mu_transform)] corr = [[1, cluster_spread],[cluster_spread,1]] d = np.sqrt(np.diag(np.diff(mu_domain)[[0,2]])) cov = np.dot(d,corr).dot(d) # sample a lot of means, just for vizualization # mu = np.asarray([np.random.uniform(*mu_domain[:2],size=k*5), # uniform in x # np.random.uniform(*mu_domain[2:],size=k*5)]).T # uniform in y mu = np.random.multivariate_normal(center, cov,k*50) sns.regplot(mu[:,0], mu[:,1]) plt.axis(domain_range); # mu ###Output /home/smb/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1706: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval ###Markdown However independent sampling isn't really very uniform and we'd like to ensure the clusters are more spread out, so we can use some post processing to thin out close ones. ###Code mu_thin = [mu[0]] # keep the first one p_dist = [1] # we'll use a gaussian kernel around each to filter and only the closest point matters dist = lambda mu_c,x: stats.norm.pdf(min(np.sum(np.square(mu_c -x),axis=1))) for m in mu: p_keep = 1- dist(mu_thin,m) if p_keep > .99: mu_thin.append(m) p_dist.append(p_keep) mu_thin = np.asarray(mu_thin) sns.regplot(mu_thin[:,0], mu_thin[:,1]) plt.axis(domain_range) ###Output /home/smb/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1706: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval ###Markdown Now, we can sample points on top of that, also we'll only use the first k ###Code sns.regplot(mu_thin[:k,0], mu_thin[:k,1]) plt.axis(domain_range) ###Output /home/smb/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py:1706: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval ###Markdown Keeping only a few, we can end up with ones in the center, but if we sort them by the distance to the ones previously selected, we get them spread out a little more ###Code # sort by distance mu_sort, p_sort = zip(*sorted(zip(mu_thin,p_dist), key = lambda x: x[1], reverse =True)) mu_sort = np.asarray(mu_sort) sns.regplot(mu_sort[:k,0], mu_sort[:k,1]) plt.axis(domain_range) # cluster covariance cluster_corr = np.asarray([[1,r_clusters],[r_clusters,1]]) cluster_std = np.diag(np.sqrt(cluster_size)) cluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std) # sample from a GMM z = np.random.choice(k,N,p_clusters) x = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_cov) for z_i in z]) # make a dataframe latent_df = pd.DataFrame(data=x, columns = ['x1', 'x2']) # code cluster as color and add it a column to the dataframe latent_df['color'] = z sp_plot(latent_df,'x1','x2','color') ###Output _____no_output_____ ###Markdown We might not want all of the clusters to have the reveral though, so we can also sample the covariances ###Code # cluster covariance p_sp_clusters =.8 cluster_size = [4,4] cluster_std = np.diag(np.sqrt(cluster_size)) cluster_corr_sp = np.asarray([[1,r_clusters],[r_clusters,1]]) # correlation with sp cluster_cov_sp = np.dot(cluster_std,cluster_corr_sp).dot(cluster_std) #cov with sp cluster_corr = np.asarray([[1,-r_clusters],[-r_clusters,1]]) #correlation without sp cluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std) #cov wihtout sp cluster_covs = [cluster_corr_sp, cluster_corr] # sample the[0,1] k times c_sp = np.random.choice(2,k,p=[p_sp_clusters,1-p_sp_clusters]) print(c_sp) # sample from a GMM z = np.random.choice(k,N,p_clusters) print(z) cov_noise = lambda : np.random.permutation([.5*np.random.random(),np.random.random()]) # cluster_covs_all = [cluster_covs[c_i]*np.random.random()/5*(c_i+1) for c_i in c_sp] cluster_covs_all = [cluster_covs[c_i]*np.random.random()*2*(i+1) for i,c_i in enumerate(c_sp)] mu_p = [np.random.multivariate_normal(mu,cov) for mu,cov in zip(mu_sort,cluster_covs_all)] x = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_covs_all[z_i]) for z_i in z]) x2 = np.asarray([np.random.multivariate_normal(mu_p[z_i],cluster_covs_all[z_i]) for z_i in z]) # x = np.asarray([np.random.multivariate_normal(mu_sort[z_i],[[1,.5],[.5,.1]]) for z_i in z]) x = np.concatenate((x,x2),axis=0) # make a dataframe latent_df = pd.DataFrame(data=x, columns = ['x1', 'x2']) # code cluster as color and add it a column to the dataframe latent_df['color'] = list(z)*2 sp_plot(latent_df,'x1','x2','color') b.shape x.shape np.random.permutation cluster_covs[0]*.1 [p_sp_clusters,1-p_sp_clusters] c_sp ###Output _____no_output_____ ###Markdown We'll call this construction of SP `geometric_2d_gmm_sp` and it's included in the `sp_data_utils` module now, so it can be called as follows. We'll change the portion of clusters with SP to 1, to ensure that all are SP. ###Code p_sp_clusters = .9 sp_df2 = mlsim.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread, p_sp_clusters, domain_range,k,N,p_clusters) sp_plot(sp_df2,'x1','x2','color') ###Output _____no_output_____ ###Markdown With this, we can start to see how the parameters control a little ###Code # setup r_clusters = -.9 # correlation coefficient of clusters cluster_spread = .8 # pearson correlation of means p_sp_clusters = 1 # portion of clusters with SP k = 5 # number of clusters cluster_size = [1,5] domain_range = [0, 20, 0, 20] N = 200 # number of points p_clusters = [.5, .2, .1, .1, .1] sp_df3 = mlsim.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread, p_sp_clusters, domain_range,k,N,p_clusters) sp_plot(sp_df3,'x1','x2','color') sp_df3.head() plot_df = sp_df3.copy() def adjust(row): ad = np.random.rand()*4 row['x1'] += ad + np.random.rand() row['x2'] -= ad + np.random.rand() return row plot_df[plot_df['color']==2] = plot_df[plot_df['color']==2].apply(adjust, axis=1) plot_df.rename(columns={'color':'name','x1':'alcohol intake','x2':'IQ'},inplace=True) plot_df.replace({0:'Sam',1:'Carl',2:'Mark',3:'Becky',4:'Mary'},inplace=True) plot_df.head() plot_min = plot_df.groupby('name').apply(lambda x: x.sample(10)) sns.lmplot('alcohol intake','IQ' , plot_min, hue='name',ci=None) # adda whole data regression line, but don't cover the scatter data sns.regplot('alcohol intake','IQ' , plot_min, color='black', scatter=False,ci=None ) sns.set(font_scale=1.5) sp_df3.head() ###Output _____no_output_____ ###Markdown We might want to add multiple views, so we added a function that takes the same parameters or lists to allow each view to have different parameters. We'll look first at just two views with the same parameters, both as one another and as above ###Code many_sp_df = mlsim.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters, domain_range,k,N,p_clusters) sp_plot(many_sp_df,'x1','x2','A') sp_plot(many_sp_df,'x3','x4','B') many_sp_df.head() ###Output 200 4 ###Markdown We can also look at the pairs of variables that we did not design SP into and see that they have vey different structure ###Code # f, ax_grid = plt.subplots(2,2) # , fig_size=(10,10) sp_plot(many_sp_df,'x1','x4','A') sp_plot(many_sp_df,'x2','x4','B') sp_plot(many_sp_df,'x2','x3','B') sp_plot(many_sp_df,'x1','x3','B') ###Output _____no_output_____ ###Markdown And we can set up the views to be different from one another by design ###Code # setup r_clusters = [.8, -.2] # correlation coefficient of clusters cluster_spread = [.8, .2] # pearson correlation of means p_sp_clusters = [.6, 1] # portion of clusters with SP k = [5,3] # number of clusters cluster_size = [4,4] domain_range = [0, 20, 0, 20] N = 200 # number of points p_clusters = [[.5, .2, .1, .1, .1],[1.0/3]*3] many_sp_df_diff = mlsim.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters, domain_range,k,N,p_clusters) sp_plot(many_sp_df_diff,'x1','x2','A') sp_plot(many_sp_df_diff,'x3','x4','B') many_sp_df.head() ###Output 200 4 ###Markdown And we can run our detection algorithm on this as well. ###Code many_sp_df_diff_result = dsp.detect_simpsons_paradox(many_sp_df_diff) many_sp_df_diff_result ###Output _____no_output_____ ###Markdown We designed in SP to occur between attributes `x1` and `x2` with respect to `A` and 2 & 3 in grouby by B, for portions fo the subgroups. We detect other occurences. It can be interesting to exmine trends between the deisnged and spontaneous occurences of SP, so ###Code designed_SP = [('x1','x2','A'),('x3','x4','B')] des = [] for i,r in enumerate(many_sp_df_diff_result[['attr1','attr2','groupbyAttr']].values): if tuple(r) in designed_SP: des.append(i) many_sp_df_diff_result['designed'] = 'no' many_sp_df_diff_result.loc[des,'designed'] = 'yes' many_sp_df_diff_result.head() r_clusters = -.9 # correlation coefficient of clusters cluster_spread = .6 # pearson correlation of means p_sp_clusters = .5 # portion of clusters with SP k = 5 # number of clusters cluster_size = [5,5] domain_range = [0, 20, 0, 20] N = 200 # number of points p_clusters = [1.0/k]*k many_sp_df_diff = mlsim.geometric_indep_views_gmm_sp(3,r_clusters,cluster_size,cluster_spread,p_sp_clusters, domain_range,k,N,p_clusters) sp_plot(many_sp_df_diff,'x1','x2','A') sp_plot(many_sp_df_diff,'x3','x4','B') sp_plot(many_sp_df_diff,'x3','x4','A') many_sp_df_diff.head() ###Output 200 6
Mission_to_Mars/Mision_to_Mars.ipynb
###Markdown NASA Mars News* Scrape the [NASA Mars News Site](https://mars.nasa.gov/news/) and collect the latest News Title and Paragraph Text. Assign the text to variables that you can reference later. ###Code #website url= 'https://mars.nasa.gov/news/' #visit the website browser.visit(url) Title=browser.find_by_css('div.content_title a').text Title #html object html = browser.html #parse with a beautiful soup soup = BeautifulSoup(html, 'html.parser') #browser.find_by_css('div.class_=rollover_description_inner').text Paragraph = soup.find('div',class_='article_teaser_body').text Paragraph ###Output _____no_output_____ ###Markdown JPL Mars Space Images - Featured Image ###Code #set up Splinter executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser ('chrome', **executable_path, headless = False) #website url= 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html' #visit the website browser.visit(url) #Find and Save the featured image browser.click_link_by_partial_text('FULL IMAGE') browser.find_by_css('img.fancybox-image')['src'] #website url= 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html' #visit the website browser.visit(url) html=browser.html #create beautifulsoup object with parse soup = BeautifulSoup(html, 'html.parser') #get the results and return those as a list #get the featured image featured_image_url = soup.find_all('img',class_='headerimage fade-in') featured_image_url ###Output _____no_output_____ ###Markdown Mars Facts* Visit the Mars Facts webpage [here](https://space-facts.com/mars/) and use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc. ###Code pd.read_html('https://space-facts.com/mars/')[0].to_html() ###Output _____no_output_____ ###Markdown Mars Hemispheres * Visit the USGS Astrogeology site [here](https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars) to obtain high resolution images for each of Mar's hemispheres.* You will need to click each of the links to the hemispheres in order to find the image url to the full resolution image.* Save both the image url string for the full resolution hemisphere image, and the Hemisphere title containing the hemisphere name. Use a Python dictionary to store the data using the keys `img_url` and `title`.* Append the dictionary with the image url string and the hemisphere title to a list. This list will contain one dictionary for each hemisphere.```python Example:hemisphere_image_urls = [ {"title": "Valles Marineris Hemisphere", "img_url": "..."}, {"title": "Cerberus Hemisphere", "img_url": "..."}, {"title": "Schiaparelli Hemisphere", "img_url": "..."}, {"title": "Syrtis Major Hemisphere", "img_url": "..."},]```- - - ###Code url='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' #visit the website browser.visit(url) links = browser.find_by_css('a.itemLink h3') List=[] for i in range(len(links)): hemisphere = {} hemisphere['title']=browser.find_by_css('a.itemLink h3')[i].text browser.find_by_css('a.itemLink h3').click() hemisphere['url']=browser.find_by_text('Sample')['href'] browser.back() List.append(hemisphere) browser.quit() List ###Output _____no_output_____
ml/11-pytorch/tensor-index.ipynb
###Markdown tensor的索引操作 ###Code import torch tensor = torch.arange(2,10) tensor print(tensor[3]) print(tensor[2:5]) print(tensor[:4]) print(tensor[-3:]) index = [1,3,5] print(tensor[index]) ###Output tensor([3, 5, 7])
16.NLP/Natural_Language_Processing.ipynb
###Markdown Cleaning text ###Code import re import nltk nltk.download('stopwords') # for removing all stopwrods as they does not contain any value from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer # for stemming corpus = [] for i in range(len(dataset)): review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) review = review.lower() review = review.split() ps = PorterStemmer() allStopWord = stopwords.words('english') allStopWord.remove('not') allStopWord.remove("aren't") allStopWord.remove("isn't") review = [ps.stem(word) for word in review if not word in set(allStopWord)] review = ' '.join(review) corpus.append(review) corpus[:4] ###Output _____no_output_____ ###Markdown Creating a Bag of Words model ###Code from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features=1500) X = cv.fit_transform(corpus).toarray() y = dataset['Liked'] print(X) len(X[0]) 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, random_state=101) from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train, y_train) prediction = classifier.predict(X_test) from sklearn.metrics import confusion_matrix, classification_report print(confusion_matrix(y_test, prediction)) print(classification_report(y_test, prediction)) from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators=100) classifier.fit(X_train, y_train) prediction = classifier.predict(X_test) print(confusion_matrix(y_test, prediction)) print(classification_report(y_test, prediction)) ###Output [[87 15] [18 80]] precision recall f1-score support 0 0.83 0.85 0.84 102 1 0.84 0.82 0.83 98 accuracy 0.83 200 macro avg 0.84 0.83 0.83 200 weighted avg 0.84 0.83 0.83 200 ###Markdown New Positive review ###Code def newReview(new_review): new_review = re.sub('[^a-zA-Z]', ' ', new_review) new_review = new_review.lower() new_review = new_review.split() ps = PorterStemmer() all_stopwords = stopwords.words('english') all_stopwords.remove('not') new_review = [ps.stem(word) for word in new_review if not word in set(all_stopwords)] new_review = ' '.join(new_review) new_corpus = [new_review] new_X_test = cv.transform(new_corpus).toarray() new_y_pred = classifier.predict(new_X_test) print(new_y_pred) newReview('I hate this restaurant so much') newReview('I love this restaurant so much') ###Output _____no_output_____
notebooks/training/pygeode-virtualenv.ipynb
###Markdown Re-runnable virtual environment setupThis notebook is a re-runnable set of instructions to set up a virtual environment and install a package `pygeode` into it. ###Code # Import the required packages import os # Change current working directory to top of the repository: ~/ceda-notebooks/ os.chdir('../..') from scripts.utils import venv_utils # Define the name of your venv you wish to create venv_name = 'venv-notebook' # List all the packages you want to install into a variable: packages = [ "pygeode", ] # Setup the venv to create, activate and install packages venv_utils.setup_venv(venv_name=venv_name, packages=packages) import pygeode ?pygeode ###Output _____no_output_____
src/posts/2018-11-26-galton-board/main.ipynb
###Markdown title: Simulating a Galton board with Markov chains, eigenvalues and Pythondescription: Use the stationary distribution of an absorbing markov chain to simulate a Galton board ###Code from IPython.display import set_matplotlib_formats set_matplotlib_formats('png', 'svg') ###Output _____no_output_____ ###Markdown The [galton board](https://en.wikipedia.org/wiki/Bean_machine) (also sometimes called a "Bean machine") is a lovely way of visualising the normal distribution.This can be modelled mathematically using [Markov chains](https://en.wikipedia.org/wiki/Markov_chain).We first need to set up the state space we're going to use. Here is a small diagram showing how it will be done:There are a few things there that don't look immediately like the usual galton board:- It is essentially rotated: this is purely to make the mathematical formulation simpler.- There is a probability \\(p\\): this is to play with later, it is taken as the probability of a given bead to fall to the left when hitting an obstacle. In the usual case: \\(p=1/2\\).- We limit our number of rows of obstacles to \\(N\\).Using this, our state space can be written as:\\[ S = \{(i, j) \in \mathbb{R}^2| 0 \leq i \leq N, 0 \leq j \leq i\}\\]A straight forward combinatorial argument gives:\\[ |S| = \binom{N + 1}{2} = \frac{(N + 1)(N + 2)}{2}\\]We are going to use Python throughout this blog post to explore the mathematical objects as we go. First let us create a [python generator](https://medium.freecodecamp.org/how-and-why-you-should-use-python-generators-f6fb56650888) to create our states and also a function to get the size of the state space efficiently: ###Code import numpy as np def all_states(number_of_rows): for i in range(number_of_rows + 1): for j in range(i + 1): yield np.array([i, j]) def get_number_of_states(number_of_rows): return int((number_of_rows + 1) * (number_of_rows + 2) / 2) list(all_states(number_of_rows=4)) ###Output _____no_output_____ ###Markdown We can test that we have the correct count: ###Code for number_of_rows in range(10): assert len(list(all_states(number_of_rows=number_of_rows))) == get_number_of_states(number_of_rows=number_of_rows) ###Output _____no_output_____ ###Markdown Now that we have our state space, to fully define our Markov chain we need to define our transitions. Given two elements \\(s^{(1)}, s^{(2)}\in S\\) we have:\\[ P_{s^{(1)}, s^{(2)}} = \begin{cases} p & \text{ if }s^{(2)} - s^{(1)} = (1, 0)\text{ and }{s_1^{(2)}} < N \\ 1 - p & \text{ if }s^{(2)} - s^{(1)} = (1, 1)\text{ and }{s_1^{(2)}} < N \\ 1 & \text{ if }s^{(2)} = N\\ 0 & \text{otherwise} \\ \end{cases}\\]The first two values ensure the beads bounce to the left and right accordingly and the third line ensures the final row is absorbing (the beads stay put once they've hit the bottom).Here's some Python code that replicates this: ###Code def transition_probability(in_state, out_state, number_of_rows, probability_of_falling_left): if in_state[0] == number_of_rows and np.array_equal(in_state, out_state): return 1 if np.array_equal(out_state - in_state, np.array([1, 0])): return probability_of_falling_left if np.array_equal(out_state - in_state, np.array([1, 1])): return 1 - probability_of_falling_left return 0 ###Output _____no_output_____ ###Markdown We can use the above and the code to get all states to create the transition matrix: ###Code def get_transition_matrix(number_of_rows, probability_of_falling_left): number_of_states = get_number_of_states(number_of_rows=number_of_rows) P = np.zeros((number_of_states, number_of_states)) for row, in_state in enumerate(all_states(number_of_rows=number_of_rows)): for col, out_state in enumerate(all_states(number_of_rows=number_of_rows)): P[row, col] = transition_probability(in_state, out_state, number_of_rows, probability_of_falling_left) return P P = get_transition_matrix(number_of_rows=3, probability_of_falling_left=1/2) P ###Output _____no_output_____ ###Markdown Once we have done this we are more of less there. With \\(\pi=(1,...0)\\), the product: \\(\pi P\\) gives the distribution of our beads after they drop past the first row. Thus the following gives us the final distribution over all the states after the beads get to the last row:\\[ \pi P ^ N\\]Here is some Python code that does exactly this: ###Code def expected_bean_drop(number_of_rows, probability_of_falling_left): number_of_states = get_number_of_states(number_of_rows) pi = np.zeros(number_of_states) pi[0] = 1 P = get_transition_matrix(number_of_rows=number_of_rows, probability_of_falling_left=probability_of_falling_left) return (pi @ np.linalg.matrix_power(P, number_of_rows))[-(number_of_rows + 1):] expected_bean_drop(number_of_rows=3, probability_of_falling_left=1/2) ###Output _____no_output_____ ###Markdown We can then plot this (using `matplotlib`): ###Code import matplotlib.pyplot as plt def plot_bean_drop(number_of_rows, probability_of_falling_left, label=None, color=None): plt.plot(expected_bean_drop(number_of_rows=number_of_rows, probability_of_falling_left=probability_of_falling_left), label=label, color=color) return plt ###Output _____no_output_____ ###Markdown Let us use this to plot over \\(N=30\\) rows and also overlay with the normal pdf: ###Code from scipy.stats import norm plt.figure() plot_bean_drop(number_of_rows=30, probability_of_falling_left=1 / 2) plt.ylabel("Probability") plt.xlabel("Bin position"); ###Output _____no_output_____ ###Markdown We can also plot this for a changing value of \\(p\\): ###Code from matplotlib import cm number_of_rows = 30 plt.figure() for p in np.linspace(0, 1, 10): plot_bean_drop( number_of_rows=number_of_rows, probability_of_falling_left=p, label=f"p={p:0.02f}", color=cm.viridis(p) ) plt.ylabel("Probability") plt.xlabel("Bin position") plt.legend(); ###Output _____no_output_____ ###Markdown We see that as the probability of falling left moves from 0 to 1 the distribution slow shifts across the bins. ###Code import pathlib p = pathlib.Path("./gif/") p.mkdir(exist_ok=True) for p in np.linspace(0, 1, 200): title = f"{p:0.02f}" plt.figure() plot_bean_drop( number_of_rows=number_of_rows, probability_of_falling_left=p, color=cm.viridis(p) ) plt.title(f"Probability of falling left: $p={title}$") plt.ylabel("Probability") plt.xlabel("Bin position") plt.savefig(f"./gif/{title}.pdf"); ###Output /home/vince/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py:537: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). max_open_warning, RuntimeWarning)
Wi20_content/chan_vese_segmentation.ipynb
###Markdown Many segmentation algorithms rely on the existence of clear edges. But what happens when there are no clear edges? Can segmentation still be performed? You perhaps can attenpt a segmentation by performing some smoothing first, but these aren't guaranteed to be successful. Take the following image, for instance: ###Code import numpy as np from skimage.segmentation import chan_vese from skimage.morphology import disk, binary_closing, binary_opening from skimage.filters import rank from skimage.data import camera import matplotlib.pyplot as plt from skimage.util import img_as_float from scipy.ndimage.morphology import binary_fill_holes #im = plt.imread('https://i.stack.imgur.com/xHJHC.png') #im = camera() im = plt.imread('https://www.researchgate.net/profile/Peter_Bankhead/publication/260261544/figure/fig30/AS:669432326135812@1536616512124/A-demonstration-that-Poisson-noise-changes-throughout-an-image-a-Part-of-a-spinning.ppm') im = im[:, :, 0] plt.imshow(im, cmap='gray') plt.axis('off') im.shape # cv = chan_vese(im, mu=0.25, lambda1=1.0, lambda2=1.5, tol=1e-3, max_iter=250, dt=0.5, # init_level_set='checkerboard', extended_output=True) cv = chan_vese(im, mu=0.2, lambda1=1.0, lambda2=1.0, tol=5e-4, max_iter=4000, dt=0.5, init_level_set='checkerboard', extended_output=True) fig, axes = plt.subplots(2,2, figsize=(10,10)) axes = axes.flatten() titles = ['Original Image', 'Chan-Vese Segmentation', 'Final Level Set', 'Evolution of Energy'] C = binary_fill_holes(np.abs(cv[1]) < 0.01) axes[0].imshow(im, cmap='gray') axes[1].imshow(cv[0], cmap='gray') axes[2].imshow(cv[1], cmap='gray') axes[3].imshow(cv[0] | C, cmap='gray') #axes[3].plot(cv[2]) #axes[3].imshow(img_as_float(im) - cv[1], cmap='gray') for i, ax in enumerate(axes): ax.axis('off') ###Output _____no_output_____
tutorial/09_Functions.ipynb
###Markdown Functions 1) IntroductionFunctions are very useful to apply multiple time a block of instructions. Software written with such sets of instructions is also more readable and easy to debug.A function takes argument in input, apply a block of instruction on these, and return a result. 2) DefinitionTo define a new function in Python, one just need tto use the keyword def, for instance: ###Code def square(x): return x**2 print(square(2)) ###Output _____no_output_____ ###Markdown As for the loops and the tests, in Python a new function is defined in an indented block of instruction after "def funcname():". Functions can be used to instentiate variables: ###Code k=square(3) print(k) ###Output _____no_output_____ ###Markdown It is also possible to define functions that do not take any argument and do not return anything. For example: ###Code def hello(): print("hello") hello() var=hello() print(var) ###Output _____no_output_____ ###Markdown The number of arguments taken by the function is free. It is not necessary to type the argument used by a function. This will work as long as the operations performed on the arguments are accepted by the language. For instance let's define the multiply function: ###Code def multiply(x,y): return x*y print(multiply(2,3)) print(multiply(2.,3.)) print(multiply(2,"three")) print(multiply("two","three")) ###Output _____no_output_____ ###Markdown It is possible to return multiple values at the same time. For instance on cae use tuple (we will see this later) or lists: ###Code def square_cube(x): return x**2 , x**3 def square_cube2(x): return [x**2,x**3] ntuple=square_cube(3) print(ntuple,type(ntuple)) lists=square_cube2(3) print(lists,type(lists)) ###Output _____no_output_____ ###Markdown One can use these functions to instentiate multiple values ate the same time, for instance: ###Code z1,z2=square_cube2(3) print(z1,z2) ###Output _____no_output_____ ###Markdown 2) ArgumentsWhat happen if we define a function that expects two arguments, and we use this function only with a single number: ###Code def multiply(x,y): return x*y print(multiply(2,3)) print(multiply(2)) ###Output _____no_output_____ ###Markdown Python return an error, because the positional arguments that were used in the function declaration were not provided correctly. Note that it is mandatory to use the arguments defined in the function in the proper order. It is possible to define a default assignement value to the variables used, or keyword argument: ###Code def ret(x=1): return x print(ret()) print(ret(10)) ###Output _____no_output_____ ###Markdown This can be done for multiple arguments: ###Code def fct (x=0, y=0, z =0): return x, y, z print(fct()) print(fct(10)) print(fct(10,8)) print(fct(10,8,3)) ###Output _____no_output_____ ###Markdown It is possible to change the order of the keyword arguments when a function is called if one explicitely give the name of the variable: ###Code print(fct (z=10 , x=3, y =80)) print(fct (z=10 , y =80)) ###Output _____no_output_____ ###Markdown It is possible to mix definitions with positionnal and keywords arguments, but the positionnal arguments have to be declared first: ###Code def fct(a, b, x=0, y=0, z =0): return a, b, x, y, z print(fct(1,1)) ###Output _____no_output_____ ###Markdown 3) local and global variablesA variable is local when it is created inside a function. A variable is global when it is created in the main program. For instance: ###Code # functions definition def square (x): y = x **2 return y # Main program z = 5 result = square (z) print ( result ) print(y) ###Output _____no_output_____ ###Markdown In this code, x and y are local variables because they were used to defined the square function, while z and results are global variables. If one try to access y in the main program, Python return a crash. It is however possible to use global variable in functions: ###Code # functions definition def func(): print(x) # Main program x = 3 func() ###Output _____no_output_____ ###Markdown It is not possible to modify a global variable in a function: ###Code # functions definition def func2(): x2+=1 # Main program x2 = 3 func2() x2 ###Output _____no_output_____ ###Markdown Except if one uses the global word: ###Code # functions definition def func3(): global x3 x3+=1 # Main program x3 = 3 func3() x3 ###Output _____no_output_____ ###Markdown In general, it is not very wise to use global functions across different functions, since the code will be harder to read and to debug. 4) Calling a function from another functionIt is possible to call a function from another function, if the first function has been loaded by Python. For instance: ###Code # functions definition def polynom (x): return (x **2 - 2*x + 1) def calc_vals (beg , end ): list_vals = [] for x in range (beg , end + 1): list_vals . append ( polynom (x)) return list_vals # Main program print ( calc_vals (-5, 5)) ###Output _____no_output_____ ###Markdown A function can even call itself, such a function will be called a recusive function. For instance if one need to define the mathematical operator Factorial: $n!=n \times n-1 \times ... \times 2 \times 1$, this can be obtained using the following lines: ###Code # functions definition def factorial (n): if n == 1: return 1 else : return n * factorial(n - 1) # Main program print ( factorial(4)) ###Output _____no_output_____ ###Markdown In summary the function call itself until the moment where n is 1, and decrease n by one at each iteration. 5) Functions and modifiable types:When using modifiable types such as lists in functions one need to pay attention. For instance: ###Code def func(): list[1] = -127 print(id(list)) # Main program list = [1 ,2 ,3] print(id(list)) func() list ###Output 4591805192 4591805192 ###Markdown Modify the list. One can observe that the addresses of the two variables displayed using the ``id()`` function return the same number. By default if a list is passed as argument to a function, it is its reference that is passed to the function, and therefore the list can be modified: ###Code def func(x): x[1] = -15 # Main program list = [1 ,2 ,3] func(list) list ###Output _____no_output_____ ###Markdown If one want to avoid this behavior, one need to pass the list explicitely: ###Code def func(x): x[1] = -15 # Main program list = [1 ,2 ,3] func(list[:]) list ###Output _____no_output_____
ex10_Utilisation_des_vues_pour_simplifier_les_requêtes.ipynb
###Markdown ex10 - Utilisation des vues pour simplifier les requêtesL'un des beaux aspects du modèle de données relationnel et SQL est que la sortie d'une requête est également une table, une relation pour être précis. Il peut s'agir d'une seule colonne ou d'une seule ligne, mais il s'agit néanmoins d'un tableau. Une vue est une requête qui peut être utilisée comme une table. Une vue peut être considérée comme une table virtuelle qui ne contient pas de données. Elle correspond juste à une requête. Chaque fois qu'une vue est accédée, la requête sous-jacente est exécutée et les résultats renvoyés peuvent être utilisés comme s'ils constituaient une table réelle.Il y a plusieurs raisons (http://www.sqlitetutorial.net/sqlite-create-view/) pour utiliser les vues. Gardez à l’esprit le principe de programmation DRY: ne vous répétez pas. Éviter les répétitions permet de gagner du temps et d'éviter les erreurs inutiles. C'est l'une des bonnes raisons pour lesquelles nous enregistrons les requêtes sous forme de vues de base de données réutilisables.Les vues SQLite sont créées à l'aide de l'instruction CREATE VIEW. Les vues SQLite peuvent être créées à partir d'une seule table, de plusieurs tables ou d'une autre vue. Voici la syntaxe de la commande ***CREATE VIEW*** de base (http://www.sqlitetutorial.net/sqlite-create-view/):>CREATE [TEMP | TEMPORARY] VIEW view_name AS>SELECT column1, column2.....>FROM table_name>WHERE [condition];La vue dans SQLite est en lecture seule. Cela signifie que vous ne pouvez pas utiliser les instructions INSERT, DELETE et UPDATE pour mettre à jour les données dans les tables de base via la vue. ###Code %load_ext sql from google.colab import drive # drive.mount('/content/gdrive') drive.mount("/content/gdrive", force_remount=True) ###Output Mounted at /content/gdrive ###Markdown 1. Connection à la database demo.db3 ###Code %sql sqlite:////content/gdrive/MyDrive/Partage/Notebooks_Serie_1/demo.db3 ###Output _____no_output_____ ###Markdown Si vous ne vous souvenez pas des tables présentes dans la database de démonstration, vous pouvez toujours utiliser la commande suivante pour les retrouver. ###Code %sql SELECT name FROM sqlite_master WHERE type='table' ###Output * sqlite:////content/gdrive/MyDrive/Partage/Notebooks_Serie_1/demo.db3 Done. ###Markdown 2. Simplifier les requêtes avec l'utilisation de vuesDans le Notebook précédent, nous avons utilisé CASE et Subquery pour calculer le ruissellement saisonnier à partir du tableau de rch. Ici, nous utiliserons une vue pour simplifier le calcul. 2.1 Rappel sur le calcul du ruissellement saisonnier ###Code %%sql sqlite:// SELECT RCH, Quarter, AVG(FLOW_OUTcms) as Runoff FROM( SELECT RCH, YR, CASE WHEN (MO) BETWEEN 3 AND 5 THEN 'MAM' WHEN (MO) BETWEEN 6 and 8 THEN 'JJA' WHEN (MO) BETWEEN 9 and 11 THEN 'SON' ELSE 'DJF' END Quarter, FLOW_OUTcms from rch) GROUP BY RCH, Quarter LIMIT 5 ###Output Done. ###Markdown 2.2 Création d'une view ###Code %%sql sqlite:// CREATE VIEW RCH_VW AS SELECT RCH, YR, CASE WHEN (MO) BETWEEN 3 AND 5 THEN 'MAM' WHEN (MO) BETWEEN 6 and 8 THEN 'JJA' WHEN (MO) BETWEEN 9 and 11 THEN 'SON' ELSE 'DJF' END Quarter, FLOW_OUTcms from rch ###Output Done. ###Markdown Requêtons maintenant la vue SSN_RCH ###Code %%sql sqlite:// SELECT * FROM RCH_VW LIMIT 5 ###Output Done. ###Markdown 2.3 Recalculons le ruissellement avec la vue :Le code est réellement simplifié et plus court ###Code %%sql sqlite:// SELECT RCH, Quarter, AVG(FLOW_OUTcms) as Runoff FROM RCH_VW GROUP BY RCH, Quarter LIMIT 5 ###Output Done. ###Markdown 2.4 Suppression de vuesIl est de plus assez facile de supprimer des vues : ###Code %sql DROP VIEW RCH_VW ###Output * sqlite:////content/gdrive/MyDrive/Partage/Notebooks_Serie_1/demo.db3 Done.
notebooks/04_exercises_without_sol.ipynb
###Markdown Exercises for workshop 4 Even though we do not have a strong focus on mathematics in this workshop series, we encourage you to get familiar with some mathematical topics since machine learning in general is highly depending on them. If you want to you can use the following materials provided by the Standford university to review or refresh your mathematical knowledge:- Linear algebra http://cs229.stanford.edu/section/cs229-linalg.pdf- Probability theory http://cs229.stanford.edu/summer2020/cs229-prob.pdf ###Code import math as m import numpy as np ###Output _____no_output_____ ###Markdown We have 10 samples from the cities Berlin, Munich, Stuttgart, Nuremberg, Hamburg, Hannover, Augsburg, Halle, Fürth and Ingolstadt (for an actual good model that might not be enough, but it suffices for showing the concepts).To make things easier we include the bias term in our feature array by adding a 1 to every sample of longitude and latitude data. We get the following feature, label and weight arrays: ###Code features = np.array([[1, 52.5167, 13.3833], [1, 48.1372, 11.5755], [1, 48.7761, 9.1775], [1, 49.4539, 11.0775], [1, 53.55, 10], [1, 52.3744, 9.7386], [1, 48.3717, 10.8983], [1, 51.4828, 11.9697], [1, 49.4783, 10.9903], [1, 48.7636, 11.4261]]) # [biasTerm, lat, lng] labels = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1]) # is in Bavaria weights = np.array([1,.5,.5]) def sigmoid(z): return 1.0 /(1 + np.exp(-z)) def predict(features, weights): return sigmoid(np.dot(features, weights)) predict(features, weights) ###Output _____no_output_____ ###Markdown Task 1:You are given the mentioned parametric function, the sigmoid function, which outputs values between 0 and 1. It is thus suitable for a simple classifier by providing the probability of belonging to a certain class. You can check out how it looks on wikipedia.$$ \sigma(z_i)=\frac{1}{1+e^{-z_i}} $$with $ z_i = w_0 + w_1\cdot x_{i,lat} + w_2\cdot x_{i,lng}$Compute the binary cross entropy loss for every sample. It is defined as following:$$ l(\hat{y}_i, y_i) = -(y_i \cdot log(\hat{y}_i) + (1-y_i)\cdot log(1-\hat{y}_i)) $$ ###Code def BCE(features, weights, labels): # TODO return pass BCE(features, weights, labels) def EmpiricalLoss(features, weights, labels): N = len(features) BiCrEn = BCE(features, weights, labels) loss = BiCrEn.sum() / N return loss EmpiricalLoss(features, weights, labels) ###Output _____no_output_____ ###Markdown Task 2:Compute the gradient of the empirical loss (also called cost function) with the binarycross entropy loss function with regards to the weight vectorw.The gradient for a function $f: \mathbb{R}^n \rightarrow \mathbb{R}$, is defined as follows:$$\nabla f = (\frac{\delta f}{\delta x_1}, ..., \frac{\delta f}{\delta x_n}) $$ ###Code def Gradient(features,weights,labels): # TODO return pass Gradient(features, weights, labels) ###Output _____no_output_____ ###Markdown Task 3:Gradient descent update steps:$$g^{(t)} = \nabla L(X,Y;w^{(t-1)})$$ $$w^{(t)} = w^{(t-1)} - \eta \cdot g^{(t)}$$Implement the gradient descent method and execute it with a learning rate of $\eta = 0.001$ and about 3000 iterations ###Code def GradientDescent(eta, features, labels, weights, iterations): # TODO return pass updated_weights = GradientDescent(0.001, features, labels, weights, 3001) updated_weights ###Output iteration: 0 loss: 15.449124167438217 iteration: 1000 loss: 0.6036136116977191 iteration: 2000 loss: 0.5981876720530922 iteration: 3000 loss: 0.5950049075701982 ###Markdown Task 4:In the following we want to test how good our small modell is performing. For that we need a classifier which determines acording to our probalities given by our modell if a city is located in bavaria. After implementing the classifier compute the accuracy of your training data and the given test data. You can also take a look at the actual probabillities. Did the empirical loss improve? ###Code # test data: Würzburg, Rostock, Trier, Rosenheim, Regensburg test_features = np.array([[1, 49.7944, 9.9294], [1, 54.0833, 12.1333], [1, 49.7567, 6.6414], [1, 47.8561, 12.1289], [1, 49.0167, 12.0833]]) # [biasTerm, lat, lng] test_labels = np.array([1, 0, 0, 1, 1]) # is in Bavaria def classify(features, weights): # TODO return pass # Accuracy and probabilities of training data # TODO # Empirical loss change # TODO # Accuracy and probabilities of test data # TODO ###Output _____no_output_____
demos/presidential-elections/Elections.ipynb
###Markdown Presidential Election NotebookThis notebook takes the raw Presidential Elections spreadsheet in elections.csv and the electoral college sheet in electoral_college.csv and converts them into a number of tables suitable for the presidential elections dashboard. This involves:1. Splitting the combined field \ - \ into two fields, candidate and party2. Converting years to integers and putting in the missing years (converting '2016', '', '' to 2016, 2016, 20163. Collecting the cells of a particular state and year into a structure, with the individual candidates as a list4. Converting the votes into integers, and then, for each result, adding a percentage float5. generating the individual records (state, year, candidate, party, votes, percentage) as a list6. Creating the data table as a Galyleo Table and sending it to the dashboard. This will form the basis of the Candidate Votes by State and Year and Party Percent by State and Year Charts7. Selecting the rows of this table for Nationwide results. This will be the basis of the pie chart for national share of the vote. Send this to the dashboard.8. Forming a pivot table of percentage of the vote for each party, by state and year. This will form the basis of the Vote history line chart. Send this to the dashboard9. Converting the pivot table to a margin table, which will form the basis of the colored map. Send this to the dashboard.10. Finally, reading in the electoral college results from the CSV file and turning this into a set of records (Year, EV-Democrat, EV-Republican, EV-Other). Send this to the dashboard.All in, we compute five tables to send to the dashboard. These will be filtered using widgets on the dashboard to form six graphs, which respond to the filters to show results for a specific state and year. Step 0: read in the table from the CSV file. After this, the data will be in the variable rows. ###Code import csv f = open('elections.csv', 'r') election_reader = csv.reader(f) rows = [row for row in election_reader] f.close() ###Output _____no_output_____ ###Markdown In the raw data, the candidate field is - . Parse into pairs a dictionary {"name": , "total": }. If the string is "Total", then the party and candidate are both "Total". If there is no dash, there is no name and party is "Other". ###Code def clean_candidate(raw): if (raw == 'Total'): return {"Name": "Total", "Party": "Total"} else: parsed = raw.split(' - ') return {"Name": parsed[0], "Party": parsed[1]} if len(parsed) == 2 else {"Name": "", "Party": "Other"} candidates = [clean_candidate(entry) for entry in rows[1][1:]] candidates ###Output _____no_output_____ ###Markdown Parties have gone by various aliases throughout the years; moreover, our dataset goes back to 1828, but the Republican party wasn't formed until 1854 from the Whig Party, which was itself a descendant of the Federalists. As a result, we consolidate parties using this function, and then make sure that every candidate's party is canonized. ###Code def canonical_name(party): party_aliases = {'National Republican': "Republican", 'National Union (Republican)': "Republican", 'Whig': "Republican", 'Liberal Republican/Democratic': "Democratic", '(Northern) Democratic': "Democratic", 'Progressive "Bull Moose"': 'Progressive'} return party_aliases[party] if party in party_aliases else party for candidate in candidates: candidate["Party"] = canonical_name(candidate["Party"]) ###Output _____no_output_____ ###Markdown The years are blank except for the first column in every group, leading to the following messy bit of code to assign a year to every record ###Code class YearCanonizer: def __init__(self, years): self.years = [self.canonize_year(year)for year in years] def canonize_year(self, year): if (year != ""): self.prev_year = int(year) return self.prev_year canonizer = YearCanonizer(rows[0][1:]) for i in range(len(candidates)): candidates[i]["Year"] = canonizer.years[i] ###Output _____no_output_____ ###Markdown Code which, from the row for a state, and the records {"Name", "Party", "Year"} computes {{"Name", "Party", "Year", "State", "Votes"}, using the fact that the votes are in the same order as the candidates ###Code # First, convert a string which may be blank or contain commas to a number def compute_int_from_delimited_string(string): string = string.strip() string = string.replace(',', '') return int(string) if len(string) > 0 else 0 def compute_state_record(state_row): state_name = state_row[0] votes = state_row[1:] result = [candidate.copy() for candidate in candidates] for candidate in result: candidate["State"] = state_name for i in range(len(result)): result[i]["Votes"] = compute_int_from_delimited_string(votes[i]) return result state_records = [compute_state_record(row) for row in rows[2:]] state_list = [] for record in state_records: state_list.extend(record) ###Output _____no_output_____ ###Markdown Trim the records with 0 votes and then get the totals for each state and year ###Code state_list = [record for record in state_list if record["Votes"] > 0] total_records = [record for record in state_list if record["Name"] == "Total"] party_records = [record for record in state_list if record["Name"] != "Total"] totals = {} for record in total_records: totals[(record["State"], record["Year"])] = record["Votes"] ###Output _____no_output_____ ###Markdown Compute the percentages ###Code for record in party_records: record["Percentage"] = 100* record["Votes"]/totals[(record["State"], record["Year"])] ###Output _____no_output_____ ###Markdown Create first table ###Code from galyleo.galyleo_table import GalyleoTable from galyleo.galyleo_constants import GALYLEO_STRING, GALYLEO_NUMBER table = GalyleoTable("presidential_vote") schema = [("Year", GALYLEO_NUMBER), ("State", GALYLEO_STRING), ("Name", GALYLEO_STRING), ("Party", GALYLEO_STRING), ("Votes", GALYLEO_NUMBER), ("Percentage", GALYLEO_NUMBER)] data = [[record["Year"], record["State"], record["Name"], record["Party"], record["Votes"], record["Percentage"]] for record in party_records] table.load_from_schema_and_data(schema, data) ###Output _____no_output_____ ###Markdown Send the first table to the dashboard ###Code from galyleo.galyleo_jupyterlab_client import GalyleoClient client = GalyleoClient() client.send_data_to_dashboard(table) ###Output _____no_output_____ ###Markdown A filtered table, nationwide vote only -- this will drive a pie chart with the national percentage of the vote. ###Code print('Hello, world') nationwide_records = [[record[0], record[3], record[5]] for record in data if record[1] == "Nationwide"] nationwide_schema = [("Year", GALYLEO_NUMBER), ("Party", GALYLEO_STRING), ("Percentage", GALYLEO_NUMBER)] table = GalyleoTable("nationwide_vote") table.load_from_schema_and_data(nationwide_schema, nationwide_records) client.send_data_to_dashboard(table) ###Output _____no_output_____ ###Markdown Time to form the pivot and margin tables, which we will use for the map and the history graph. One note is that there have been a _lot_ of parties in American history; the Cook database shows 26, and even after we have removed 7 as aliases, above, this leaves 19. This makes for a busy history chart. So what we will do here is choose a party list, and everything else becomes "Other". The party list is a matter of taste; it will of course include Republican and Democrat, but the remainder are personal preference. I'm using "Progressive", "Socialist", and "Reform", since they showed well in 2 or more elections and/or captured 20% of the national vote in one ###Code parties = ['Democratic', 'Republican', 'Progressive', 'Socialist', 'Reform'] ###Output _____no_output_____ ###Markdown Pivot on percentage to break out by party. The idea here is to create records of the form {State, Year, P1,...,Pn} where each Pi is the name of a party and the value is the percentage of the vote ###Code # A function which creates an empty pivot record for state and year def pivot_record(state, year): result = {"State": state, "Year": year} for party in parties: result[party] = 0 result["Other"] = 0 return result # Compute the pivot table. For each record in stripped_list, add the vote to the entry for state and year. If # none exists, create the record first pivot_table = {} party_set = set(parties) for record in party_records: if not ((record["State"], record["Year"]) in pivot_table): pivot_table[(record["State"], record["Year"])] = pivot_record(record["State"], record["Year"]) if record["Party"] in party_set: pivot_table[(record["State"], record["Year"])][record["Party"]] = record["Percentage"] else: pivot_table[(record["State"], record["Year"])]["Other"] = max(record["Percentage"], pivot_table[(record["State"], record["Year"])]["Other"]) ###Output _____no_output_____ ###Markdown The pivot table is now complete. Just prepare the table and send it to the dashboard. Add "Other" to the list of parties, then form the Schema ("State" is a string, everything else is a number), create the table, load it with the data, and send to a dashboard. ###Code parties.append("Other") pivot_schema = [("State", GALYLEO_STRING), ("Year", GALYLEO_NUMBER)] + [(party, GALYLEO_NUMBER) for party in parties] pivot_data = [[record["State"], record["Year"]] + [record[party] for party in parties] for record in pivot_table.values()] galyleo_pivot_table = GalyleoTable("presidential_vote_history") galyleo_pivot_table.load_from_schema_and_data(pivot_schema, pivot_data) client.send_data_to_dashboard(galyleo_pivot_table) ###Output _____no_output_____ ###Markdown Prepare the margin table. This is going to drive a red/blue/green map, where a Democratic victory is going to be on the scale 5-10, Republican on the scale -5 to -10, and "Other" will be 0. We only need three parties for this one, Democratic, Republican, and Other, so we consolidate the margin table down to a list of length 3 ###Code from functools import reduce def consolidate(pivot_record): other = pivot_record[parties[2]] for party in parties[3:]: other = max(other, pivot_record[party]) result = {"Other": other} for field in ["State", "Year", "Democratic", "Republican"]: result[field] = pivot_record[field] return result margin_party_records = [consolidate(pivot_record) for pivot_record in pivot_table.values()] ###Output _____no_output_____ ###Markdown Now we have the margin records, and we want to convert them into 5-10 (state lightly to heavily Democratic) (-10 - -5) (state heavily to lightly Republican), and 0 (other). We'll just use a linear scale, capped at 10, so 0-2% is light, 2-4% is next, and 10% or above is heavy. This is adjustable. ###Code def compute_margin(margin_party_record): if (margin_party_record["Other"] > max(margin_party_record["Republican"], margin_party_record["Democratic"])): return 0 multiplier = 1 if margin_party_record["Democratic"] > margin_party_record["Republican"] else -1 raw_margin = min(round(abs(margin_party_record["Democratic"] - margin_party_record["Republican"])/2), 5) return multiplier * (5 + raw_margin) margins = [[record["State"], record["Year"], compute_margin(record)] for record in margin_party_records] margin_table = GalyleoTable('presidential_margins') margin_table.load_from_schema_and_data([('State', GALYLEO_STRING), ('Year', GALYLEO_NUMBER), ('Margin', GALYLEO_NUMBER)], margins) client.send_data_to_dashboard(margin_table) ###Output _____no_output_____ ###Markdown Finally, get the electoral college. This is very simple. Just create one record per year, with three fields: Republican, Democratic, Other ###Code ec_aliases = {'Republican': {'National Republican', 'Whig', 'Republican'}, 'Democratic': {'Democratic/Liberal Republican', 'Independent-Democratic', 'Democratic', 'Democrat'}} f = open('electoral_college.csv', 'r') ec_reader = csv.reader(f) rows = [row for row in ec_reader] f.close() class EC_Record: def __init__(self, year): self.year = int(year) self.republican = 0 self.democratic = 0 self.other = 0 def add_record(self, record): value = int(record[3]) if (record[2] in ec_aliases['Republican']): self.republican = self.republican + value elif (record[2] in ec_aliases['Democratic']): self.democratic = self.democratic + value else: self.other = self.other + value def as_list(self): return [self.year, self.democratic, self.republican, self.other] def __repr__(self): l1 = self.as_list() return ', '.join([str(elt) for elt in l1]) ec_records = {} for row in rows[1:]: year = row[0] if year not in ec_records: ec_records[year] = EC_Record(year) ec_records[year].add_record(row) ###Output _____no_output_____ ###Markdown Load the Electoral College records into a table and send it to the dashboard ###Code schema = [("Year", GALYLEO_NUMBER), ("Democratic", GALYLEO_NUMBER), ("Republican", GALYLEO_NUMBER), ("Other", GALYLEO_NUMBER)] ec_table = GalyleoTable("electoral_college") ec_table.load_from_schema_and_data(schema, [record.as_list() for record in ec_records.values()]) client.send_data_to_dashboard(ec_table) ###Output _____no_output_____
scripts/pub_test/identify_theory_games.ipynb
###Markdown Find deviations from Lichess masters DB ###Code import os import time import requests from dotenv import load_dotenv load_dotenv() token = os.environ.get("LICHESS_TOKEN") import requests import chess import chess.pgn import time import sys import berserk import io from IPython.display import SVG from tqdm import tqdm session = berserk.TokenSession(token) client = berserk.Client(session) # Check FEN against Lichess masters DB def check_fen_against_mastersdb(fen): FENdict = {} cachedfen = FENdict.get(fen) if cachedfen: r = cachedfen else: while True: payload = {'fen': fen, 'topGames': 0, 'moves': 30} r = requests.get(f'https://explorer.lichess.ovh/master', params = payload) if r.status_code == 200: time.sleep(0.2) r = r.json() break if r.status_code == 429: print("Waiting 5 seconds") time.sleep(5) continue # FENdict[fen] = r matches = r['white'] + r['black'] + r['draws'] return matches fen = 'rn1qkb1r/pp3ppp/2p1pn2/3p1b2/2PP4/1Q3NP1/PP2PPBP/RNB1K2R b KQkq -' check_fen_against_mastersdb(fen) # Identify when a Lichess game was last in "theory" (aka matched at least one masters DB game) def find_last_ply_found_in_mastersdb(id, start_ply = 0): pgn = client.games.export(id, as_pgn=True) game_num = 0 while True: with io.StringIO(pgn) as f: game = chess.pgn.read_game(f) if not game or game_num >= 1: break game_num += 1 board = game.board() masters_matches = 99999 while masters_matches > 0: for n, move in enumerate(game.mainline_moves()): if n < start_ply: board.push(move) else: masters_matches = check_fen_against_mastersdb(board.epd()) if masters_matches == 0: # stop when no matches are found break else: board.push(move) return n-1 find_last_ply_found_in_mastersdb('5fULpU0u') # Check a ply in a game against the masters DB and return the number of matches def check_ply_against_mastersdb(id, ply): pgn = client.games.export(id, as_pgn=True) game_num = 0 while True: with io.StringIO(pgn) as f: game = chess.pgn.read_game(f) if not game or game_num >= 1: break game_num += 1 board = game.board() for n, move in enumerate(game.mainline_moves()): if n < ply: board.push(move) else: matches = check_fen_against_mastersdb(board.epd()) break return matches # Find game with the latest ply matched in the masters DB def find_latest_deviation_from_mastersdb(ids): latest_deviation_ply = 9999 latest_deviation_id = '' for i in range(0, len(ids)): print('Checking game', i+1, '/', len(ids), ':', ids[i]) if i == 0: latest_deviation_ply = find_last_ply_found_in_mastersdb(ids[i], 1) latest_deviation_id = ids[i] print('Current latest ply matched in masters DB:', latest_deviation_ply, 'in', latest_deviation_id) if i > 0: new_matches = check_ply_against_mastersdb(ids[i], latest_deviation_ply) if new_matches == 0: continue if new_matches > 0: latest_deviation_ply = find_last_ply_found_in_mastersdb(ids[i], latest_deviation_ply) latest_deviation_id = ids[i] print('New latest ply matched in masters DB:', latest_deviation_ply, 'in', latest_deviation_id) if i > 0 and i % 100 == 0: print('Current latest ply matched in masters DB:', latest_deviation_ply, 'in', latest_deviation_id) return [latest_deviation_id, latest_deviation_ply] find_latest_deviation_from_mastersdb(['0oht8pGP', 'JSyE55lM', '42UIwlRN', 'YsMWRKcn', '2QnQM1ns']) # More games to test... # 'rpT0BJkr', 'elDXjTwi', 'HqYHBLxl', 'LmSs5zO5', 'zssiRcV2', # 'zssiRcV2', 'QqY5HUCU', 'BSB32D9z', '5lFmsjoC', 'SG4cXHBZ', # '45KDSsll' ###Output Checking game 1 / 5 : 0oht8pGP Current latest ply matched in masters DB: 16 in 0oht8pGP Checking game 2 / 5 : JSyE55lM Checking game 3 / 5 : 42UIwlRN New latest ply matched in masters DB: 17 in 42UIwlRN Checking game 4 / 5 : YsMWRKcn New latest ply matched in masters DB: 17 in YsMWRKcn Checking game 5 / 5 : 2QnQM1ns New latest ply matched in masters DB: 20 in 2QnQM1ns
community_tutorials_and_guides/taxi/NYCTaxi-E2E-pandas.ipynb
###Markdown Predicting NYC Taxi Fares with RAPIDS RAPIDS is a suite of GPU accelerated data science libraries with APIs that should be familiar to users of Pandas, Dask, and Scikitlearn.This notebook focuses on showing how to use cuDF with Dask & XGBoost to scale GPU DataFrame ETL-style operations & model training out to multiple GPUs on mutliple nodes as part of Google Cloud Dataproc.Anaconda has graciously made some of the NYC Taxi dataset available in a public Google Cloud Storage bucket. We'll use our Dataproc Cluster of GPUs to process it and train a model that predicts the fare amount.For EDA we show the examples using [Holoviews](http://holoviews.org/) and [hvplot](https://hvplot.holoviz.org/). Best way to install Holoviews is to from `conda-forge` channel `conda install -c conda-forge holoviews`and for hvplot `pyviz` channel. `conda install -c pyviz hvplot` ###Code %matplotlib inline import matplotlib.pyplot as plt import socket, time import pandas as pd import xgboost as xgb #To install Holoviews and hvplot #conda install -c conda-forge holoviews #conda install -c pyviz hvplot import holoviews as hv from holoviews import opts import numpy as np import hvplot.pandas hv.extension('bokeh') ###Output _____no_output_____ ###Markdown Inspecting the DataNow that we have a cluster of GPU workers, we'll use [dask-cudf](https://github.com/rapidsai/dask-cudf/) to load and parse a bunch of CSV files into a distributed DataFrame. ###Code '''if you get 'ModuleNotFoundError: No module named 'gcsfs', run `!pip install gcsfs` ''' base_path = '/localdisk/benchmark_datasets/yellow-taxi-dataset/' df_2014 = pd.read_csv(base_path+'2014/yellow_tripdata_2014-01.csv', parse_dates=[' pickup_datetime', ' dropoff_datetime']) df_2014.head() ###Output _____no_output_____ ###Markdown Data CleanupAs usual, the data needs to be massaged a bit before we can start adding features that are useful to an ML model.For example, in the 2014 taxi CSV files, there are `pickup_datetime` and `dropoff_datetime` columns. The 2015 CSVs have `tpep_pickup_datetime` and `tpep_dropoff_datetime`, which are the same columns. One year has `rate_code`, and another `RateCodeID`.Also, some CSV files have column names with extraneous spaces in them.Worst of all, starting in the July 2016 CSVs, pickup & dropoff latitude and longitude data were replaced by location IDs, making the second half of the year useless to us.We'll do a little string manipulation, column renaming, and concatenating of DataFrames to sidestep the problems. ###Code #Dictionary of required columns and their datatypes must_haves = { 'pickup_datetime': 'datetime64[s]', 'dropoff_datetime': 'datetime64[s]', 'passenger_count': 'int32', 'trip_distance': 'float32', 'pickup_longitude': 'float32', 'pickup_latitude': 'float32', 'rate_code': 'int32', 'dropoff_longitude': 'float32', 'dropoff_latitude': 'float32', 'fare_amount': 'float32' } def clean(ddf, must_haves): # replace the extraneous spaces in column names and lower the font type tmp = {col:col.strip().lower() for col in list(ddf.columns)} ddf = ddf.rename(columns=tmp) ddf = ddf.rename(columns={ 'tpep_pickup_datetime': 'pickup_datetime', 'tpep_dropoff_datetime': 'dropoff_datetime', 'ratecodeid': 'rate_code' }) # ddf['pickup_datetime'] = ddf['pickup_datetime'].astype('datetime64[ms]') # ddf['dropoff_datetime'] = ddf['dropoff_datetime'].astype('datetime64[ms]') for col in ddf.columns: if col not in must_haves: ddf = ddf.drop(columns=col) continue # if column was read as a string, recast as float if ddf[col].dtype == 'object': ddf[col] = ddf[col].fillna('-1') # ddf[col] = ddf[col].astype('float32') # else: # downcast from 64bit to 32bit types # Tesla T4 are faster on 32bit ops # if 'int' in str(ddf[col].dtype): # ddf[col] = ddf[col].astype('int32') # if 'float' in str(ddf[col].dtype): # ddf[col] = ddf[col].astype('float32') # ddf[col] = ddf[col].fillna(-1) return ddf ###Output _____no_output_____ ###Markdown NOTE: We will realize that some of 2015 data has column name as `RateCodeID` and others have `RatecodeID`. When we rename the columns in the clean function, it internally doesn't pass meta while calling map_partitions(). This leads to the error of column name mismatch in the returned data. For this reason, we will call the clean function with map_partition and pass the meta to it. Here is the link to the bug created for that: https://github.com/rapidsai/cudf/issues/5413 ###Code df_2014 = clean(df_2014, must_haves) ###Output _____no_output_____ ###Markdown We still have 2015 and the first half of 2016's data to read and clean. Let's increase our dataset. ###Code df_2015 = pd.read_csv(base_path+'2015/yellow_tripdata_2015-01.csv', parse_dates=['tpep_pickup_datetime', 'tpep_dropoff_datetime']) df_2015 = clean(df_2015, must_haves) ###Output _____no_output_____ ###Markdown Handling 2016's Mid-Year Schema Change In 2016, only January - June CSVs have the columns we need. If we try to read base_path+2016/yellow_*.csv, Dask will not appreciate having differing schemas in the same DataFrame.Instead, we'll need to create a list of the valid months and read them independently. ###Code months = [str(x).rjust(2, '0') for x in range(1, 7)] valid_files = [base_path+'2016/yellow_tripdata_2016-'+month+'.csv' for month in months] #read & clean 2016 data and concat all DFs df_2016 = clean(pd.read_csv(valid_files[0], parse_dates=['tpep_pickup_datetime', 'tpep_dropoff_datetime']), must_haves) #concatenate multiple DataFrames into one bigger one taxi_df = pd.concat([df_2014, df_2015, df_2016]) # taxi_df = taxi_df.persist() taxi_df.dtypes len(taxi_df) ###Output _____no_output_____ ###Markdown Exploratory Data Analysis (EDA) Here, we are checking out if there are any non-sensical records and outliers, and in such case, we need to remove them from the dataset. ###Code # check out if there is any negative total trip time taxi_df[taxi_df.dropoff_datetime <= taxi_df.pickup_datetime].head() # check out if there is any abnormal data where trip distance is short, but the fare is very high. taxi_df[(taxi_df.trip_distance < 10) & (taxi_df.fare_amount > 300)].head() # check out if there is any abnormal data where trip distance is long, but the fare is very low. taxi_df[(taxi_df.trip_distance > 50) & (taxi_df.fare_amount < 50)].head() #Using only 2016-01 data for visuals. #taxi_df_cdf = clean(cudf.read_csv(valid_files[0]),must_haves) #Using entire 2016 data for visualization taxi_df_cdf = taxi_df ###Output _____no_output_____ ###Markdown The plot below visualizes the histogram of trip_distance and we can see some abnormal trip_distance values for some records. Taking this and also the NYC map coordinates into consideration, we will only select records where tripdistance < 500 miles. ###Code %%time #Histogram using cupy and Holoviews # frequencies, edges = cupy.histogram(x=cupy.array(taxi_df_cdf["trip_distance"]) , bins=20) # hist = hv.Histogram((np.array(edges.tolist()), np.array(frequencies.tolist()))) #Histogram using hvplot hist = taxi_df_cdf.hvplot.hist("trip_distance", bins=20, bin_range=(0, 10)) #Customizing the plot hist.opts(xlabel="trip distance (miles)",ylabel="count",color="green",width=900, height=400) ###Output _____no_output_____ ###Markdown Similarly, the plot below visualizes the histogram of fare_amount and we can see some abnormal fare_amount values for some records. Taking this and also the NYC map coordinates into consideration, we will only select records where fare_amount < 500$. ###Code %%time #Histogram using cupy and Holoviews # frequencies, edges = cupy.histogram(x=cupy.array(taxi_df_cdf["fare_amount"]) , bins=20) # hist = hv.Histogram((np.array(edges.tolist()), np.array(frequencies.tolist()))) #Histogram using hvplot hist = taxi_df_cdf.hvplot.hist("fare_amount", bins=20, bin_range=(0, 50)) #Customizing the plot hist.opts(xlabel="fare amount ($)",ylabel="count",color="green",width=900, height=400) %%time # Plot the number of passengers per trip. We'll remove the records where passenger_count > 5. # Plotting using Holoviews #bar = hv.Bars(taxi_df_cdf.groupby("passenger_count").size().to_frame().rename(columns={0:"count"})) # Plotting using hvplot df_bar = taxi_df_cdf.groupby("passenger_count").size().to_frame().rename(columns={0:"count"}).reset_index() bar = df_bar.hvplot.bar(x="passenger_count",y="count") #Customizing the plot bar.opts(color="green",width=900, height=400) ###Output _____no_output_____ ###Markdown EDA visuals and additional analysis yield the filter logic below. ###Code taxi_df # apply a list of filter conditions to throw out records with missing or outlier values query_frags = [ 'fare_amount > 1 and fare_amount < 500', 'passenger_count > 0 and passenger_count < 6', 'pickup_longitude > -75 and pickup_longitude < -73', 'dropoff_longitude > -75 and dropoff_longitude < -73', 'pickup_latitude > 40 and pickup_latitude < 42', 'dropoff_latitude > 40 and dropoff_latitude < 42', 'trip_distance > 0 and trip_distance < 500', 'not (trip_distance > 50 and fare_amount < 50)', 'not (trip_distance < 10 and fare_amount > 300)', 'not dropoff_datetime <= pickup_datetime' ] taxi_df = taxi_df.query(' and '.join(query_frags)) # reset_index and drop index column taxi_df = taxi_df.reset_index(drop=True) taxi_df ###Output _____no_output_____ ###Markdown Adding Interesting FeaturesDask & cuDF provide standard DataFrame operations, but also let you run "user defined functions" on the underlying data. Here we use [dask.dataframe's map_partitions](https://docs.dask.org/en/latest/dataframe-api.htmldask.dataframe.DataFrame.map_partitions) to apply user defined python function on each DataFrame partition.We'll use a Haversine Distance calculation to find total trip distance, and extract additional useful variables from the datetime fields. ###Code ## add features taxi_df['hour'] = taxi_df['pickup_datetime'].dt.hour taxi_df['year'] = taxi_df['pickup_datetime'].dt.year taxi_df['month'] = taxi_df['pickup_datetime'].dt.month taxi_df['day'] = taxi_df['pickup_datetime'].dt.day taxi_df['day_of_week'] = taxi_df['pickup_datetime'].dt.weekday taxi_df['is_weekend'] = (taxi_df['day_of_week']>=5).astype('int32') #calculate the time difference between dropoff and pickup. taxi_df['diff'] = taxi_df['dropoff_datetime'].astype('int64') - taxi_df['pickup_datetime'].astype('int64') taxi_df['diff']=(taxi_df['diff']/1000).astype('int64') taxi_df['pickup_latitude_r'] = taxi_df['pickup_latitude']//.01*.01 taxi_df['pickup_longitude_r'] = taxi_df['pickup_longitude']//.01*.01 taxi_df['dropoff_latitude_r'] = taxi_df['dropoff_latitude']//.01*.01 taxi_df['dropoff_longitude_r'] = taxi_df['dropoff_longitude']//.01*.01 taxi_df = taxi_df.drop('pickup_datetime', axis=1) taxi_df = taxi_df.drop('dropoff_datetime', axis=1) geo_columns = ['pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude'] radians = {x: np.radians(taxi_df[x]) for x in geo_columns} dlon = radians['pickup_longitude'] - radians['dropoff_longitude'] dlat = radians['pickup_latitude'] - radians['dropoff_latitude'] taxi_df['h_distance'] = 6367 * 2 * np.arcsin( np.sqrt( np.sin(dlat / 2)**2 + np.cos(radians['pickup_latitude']) * np.cos(radians['dropoff_latitude']) * np.sin(dlon / 2)**2)) taxi_df ###Output _____no_output_____ ###Markdown Pick a Training SetLet's imagine you're making a trip to New York on the 25th and want to build a model to predict what fare prices will be like the last few days of the month based on the first part of the month. We'll use a query expression to identify the `day` of the month to use to divide the data into train and test sets.The wall-time below represents how long it takes your GPU cluster to load data from the Google Cloud Storage bucket and the ETL portion of the workflow. ###Code #since we calculated the h_distance let's drop the trip_distance column, and then do model training with XGB. taxi_df = taxi_df.drop('trip_distance', axis=1) # this is the original data partition for train and test sets. X_train = taxi_df.query('day < 25') # create a Y_train ddf with just the target variable Y_train = X_train[['fare_amount']] # drop the target variable from the training ddf X_train = X_train[X_train.columns.difference(['fare_amount'])] ###Output _____no_output_____ ###Markdown Train the XGBoost Regression ModelThe wall time output below indicates how long it took your GPU cluster to train an XGBoost model over the training set. ###Code X_train Y_train dtrain = xgb.DMatrix(X_train, Y_train) %%time trained_model = xgb.train({ 'learning_rate': 0.3, 'max_depth': 8, 'objective': 'reg:squarederror', 'subsample': 0.6, 'gamma': 1, 'silent': True, 'verbose_eval': True, 'tree_method':'hist' }, dtrain, num_boost_round=100, evals=[(dtrain, 'train')]) ax = xgb.plot_importance(trained_model, height=0.8, max_num_features=10, importance_type="gain") ax.grid(False, axis="y") ax.set_title('Estimated feature importance') ax.set_xlabel('importance') plt.show() ###Output _____no_output_____ ###Markdown How Good is Our Model?Now that we have a trained model, we need to test it with the 25% of records we held out.Based on the filtering conditions applied to this dataset, many of the DataFrame partitions will wind up having 0 rows. This is a problem for XGBoost which doesn't know what to do with 0 length arrays. We'll repartition the data. ###Code X_test = taxi_df.query('day >= 25') # Create Y_test with just the fare amount Y_test = X_test[['fare_amount']] # Drop the fare amount from X_test X_test = X_test[X_test.columns.difference(['fare_amount'])] # display test set size len(X_test) ###Output _____no_output_____ ###Markdown Calculate Prediction ###Code # generate predictions on the test set '''feed X_test as a dask.dataframe''' booster = trained_model # history = trained_model['history'] # "History" is a dictionary containing evaluation results # booster.set_param({'predictor': 'gpu_predictor'}) prediction = pd.Series(booster.predict(xgb.DMatrix(X_test))) prediction.head() # prediction = prediction.map_partitions(lambda part: cudf.Series(part)).reset_index(drop=True) actual = Y_test['fare_amount'].reset_index(drop=True) ###Output _____no_output_____ ###Markdown NOTE: We mapped each partition of the result from `xgb.dask.predict` into `cudf.Series` to be able to substract it from `actual` data. Here is the issue asking XGBoost to solve that before returning data from `xgb.dask.predict` https://github.com/dmlc/xgboost/issues/5823issuecomment-648526888 ###Code prediction.head() actual.head() # Calculate RMSE squared_error = ((prediction-actual)**2) # compute the actual RMSE over the full test set np.sqrt(squared_error.mean()) ###Output _____no_output_____ ###Markdown Save Trained Model for Later Use¶ To make a model maximally useful, you need to be able to save it for later use. We'll use Google Cloud Storage to persist the trained model in a dill file. ###Code import gcsfs, dill fs = gcsfs.GCSFileSystem() # replace with a bucket you own bucket = 'rapidsai-test-1/' with fs.open(bucket+'trained_model.dill', 'wb') as file: dill.dump(trained_model, file) ###Output _____no_output_____ ###Markdown As an alternative, you can save the trained model on your system as below. ###Code # Save the model to file booster.save_model('xgboost-model') print('Training evaluation history:', history) ###Output _____no_output_____ ###Markdown Reload a Saved Model from Disk You can also read the saved model back out of Google Cloud Storage and into a normal XGBoost model object. ###Code with fs.open(bucket+'trained_model.dill', 'rb') as file: model_from_disk = dill.load(file) # Generate predictions on the test set again, but this time using the reloaded model prediction = xgb.dask.predict(client, model_from_disk, X_test).persist() wait(prediction) # Verify that the predictions result in the same RMSE error prediction = prediction.map_partitions(lambda part: cudf.Series(part)).reset_index(drop=True) actual = Y_test['fare_amount'].reset_index(drop=True) squared_error = ((prediction-actual)**2) # compute the actual RMSE over the full test set cupy.sqrt(squared_error.mean().compute()) ###Output _____no_output_____
examples/measuring/do2d_multi.ipynb
###Markdown Buffered Messurenment SR830Example notebook of buffered measurement for a bundle of SR830 lock-ins. This notebook is shipped together with the file do2d_multi.py containing the function do2d_multi. The do2d_multi is just a function wrapping the QCoDeS Measurement context manager. The do2d_multi takes a list of SR830 lock-ins and perform a buffered measurement, of either channel 1, channel 2 or both. Optionally a list of non-buffered parameters can be provided to be measured on the same grid as the lock-ins. However, adding a nonbuffered parameter will slow the measurement down. ###Code # IMPORTS import qcodes as qc import os import numpy as np from qcodes.instrument_drivers.stanford_research.SR830 import SR830 from qdev_wrappers.measurement_helpers.do2d_multi import do2d_multi from qcodes.instrument.base import Instrument from qcodes.utils.validators import Numbers, Arrays import qcodes.instrument_drivers.agilent.Agilent_34400A as agi from qcodes.dataset.plotting import plot_dataset ###Output _____no_output_____ ###Markdown Dummy GeneratorVirtual instrument to be used instead of af DAC or other external setting parameter ###Code class DummyGenerator(Instrument): def __init__(self, name, **kwargs): super().__init__(name, **kwargs) self.add_parameter('v_start', initial_value=0, unit='V', label='v start', vals=Numbers(0,1e3), get_cmd=None, set_cmd=None) self.add_parameter('v_stop', initial_value=1, unit='V', label='v stop', vals=Numbers(1,1e3), get_cmd=None, set_cmd=None) self.add_parameter('v_now', initial_value=0, unit='V', label='v_now', vals=Numbers(self.v_start(),self.v_stop()), get_cmd=None, set_cmd=None) # The parameter to be set in the outer loop slow = DummyGenerator('slow') # The parameter to be set in the inner loop fast = DummyGenerator('fast') ###Output _____no_output_____ ###Markdown Connect to and Initialze the SR830s ###Code sr = SR830('lockin', 'GPIB0::2::INSTR') sr2 = SR830('lockin2', 'GPIB0::1::INSTR') a1 = agi.Agilent_34400A('Agilent1', 'GPIB0::4::INSTR') sr.ch1_display('X') sr.ch1_ratio('none') sr2.ch1_display('X') sr2.ch1_ratio('none') sr.ch2_display('Y') sr.ch2_ratio('none') sr2.ch2_display('Y') sr2.ch2_ratio('none') a1.reset() a1.NPLC.set(10) ###Output Connected to: Stanford_Research_Systems SR830 (serial:s/n70597, firmware:ver1.07) in 1.02s Connected to: Stanford_Research_Systems SR830 (serial:s/n47762, firmware:ver1.07) in 0.13s Connected to: HEWLETT-PACKARD 34401A (serial:0, firmware:10-5-2) in 0.11s ###Markdown Tuple of lock-ins ###Code lockins = (sr,sr2) ###Output _____no_output_____ ###Markdown do2d_multiThis is a do2d to be used for a collection of SR830. Args:* param_slow: The QCoDeS parameter to sweep over in the outer loop* start_slow: Starting point of sweep in outer loop* stop_slow: End point of sweep in the outer loop* num_points_slow: Number of points to measure in the outer loop* delay_slow: Delay after setting parameter in the outer loop* param_fast: The QCoDeS parameter to sweep over in the inner loop* start_fast: Starting point of sweep in inner loop* stop_fast: End point of sweep in the inner loop* num_points_fast: Number of points to measure in the inner loop* delay_fast: Delay after setting parameter before measurement is performed* lockins: Tuple of lockins* devices_no_buffer: Iterable of Parameters to be measured alongside the lockins* write_period: The time after which the data is actually written to the database.* threading: For each element which are True, write_in_background, buffer_reset, and send_trigger and get_trace will be threaded respectively* channels: channels to get from the buffer. 0 gets both channels* attempts_to_get: Maximum number of attempts to try to get the buffer if it fails* delay_fast_increase: Amount to increase delay_fast if getting the buffer fails ###Code datatuple = do2d_multi(param_slow = slow.v_now, start_slow = 0, stop_slow = 0.5, num_points_slow = 10, delay_slow = 0.05, param_fast = fast.v_now, start_fast = 0, stop_fast = 0.5, num_points_fast = 10, delay_fast = 0.07, lockins = lockins, write_period = 1, threading=[True,False,False,True], channels = 0, attempts_to_get=50, delay_fast_increase=0.00 ) # ploting the data plot_dataset(datatuple[0]) ###Output _____no_output_____ ###Markdown Adding a non-buffered parameter to measure ###Code devices_no_buffer = (a1.volt,) datatuple = do2d_multi(param_slow = slow.v_now, start_slow = 0, stop_slow = 0.5, num_points_slow = 10, delay_slow = 0.05, param_fast = fast.v_now, start_fast = 0, stop_fast = 0.5, num_points_fast = 10, delay_fast = 0.07, lockins = lockins, devices_no_buffer = devices_no_buffer, channels = 1, threading=[True,False,False,True], attempts_to_get=50, delay_fast_increase=0.00 ) plot_dataset(datatuple[0]) plot_dataset(datatuple[1]) ###Output _____no_output_____
prob-stats-data-analysis/foundational/probfunctions-displaying.ipynb
###Markdown Probability functions and displaying data How probability is best formalised and represented, mathematically as well as visually, depends on the type of data you have. In the following, we will use $X$ to indicate a random variable taking values in space $\Omega$. To mathematically express probabilities attached to certain values in $\Omega$, people use the *probability mass function* in the case of discrete variables and *probability density functions* in the case of continuous variables. Let's see them both. The Probability Mass FunctionThe *probability mass function*, aka **pmf**, expresses, at each possible value of a discrete random variable, the probability related to it. We'll call it $p_m$. So, the pfm expresses the probability that $X$ takes a given value $x$:$$p_m(x) = P(X=x) \ ,$$and by normalisation property of probability it obeys$$\sum_{x \in \Omega} p_m(x) = 1$$ The Probability Density FunctionThe **pdf**, *probability density function*, which we'll here call $p_d(x)$, expresses the probability for a continuous random variable $X$ to take values within a certain range, so it is effectively a density of probability.What this means is that taken range of values $[x_a, x_b]$, we have $$P(x_a \leq X \leq x_b) = \int_{x_a}^{x_b} \text{d} x \ p_d(x) \ ,$$and by the normalisation property of probability we have$$\int_\Omega \text{d} x \ p_d(x) = 1$$ Some distributions and using histograms Histogramming data means segmenting it into ranges (*bins*) and counting how many data points fall in each range. It is what you typically do when you have some real-world data and you need to understand how it is distributed. A uniform distribution Let's say we uniformly extract $10^5$ integer data points in the interval $[0, 10)$: ###Code n = 100000 data = [random.randint(0, 9) for i in range(n)] ###Output _____no_output_____ ###Markdown and then let's compute, for each of the 10 possible values, how many of these points are there, which is equivalent to say that we are binning with a bin width of 1: ###Code bins = np.arange(0, 11, 1) # Count the number of items falling in each bin bin_counts = [data.count(item) for item in range(0, 10)] plt.bar(range(0, 10), bin_counts, width=1, edgecolor='k') plt.xticks(bins) plt.title('Histogram of $10^5$ uniformly distributed data, counts') plt.xlabel('Value') plt.ylabel('Count items') plt.show(); ###Output _____no_output_____ ###Markdown It's plain visible that bins contain pretty much the same number of values, namely around $10^4$, which is our total divided by the number of bins itself. Indeed, the difference between the highest and the lowest counts in a bins is ###Code max(bin_counts) - min(bin_counts) ###Output _____no_output_____ ###Markdown corresponding to a proportion of the total number of points equal to ###Code (max(bin_counts) - min(bin_counts) ) / n ###Output _____no_output_____ ###Markdown very little! This histogram is doing a good job in showing us the data is uniformly distributed. What we have shown is, again, the *number* of values in each bin, which is not the probability. In order to have a PMF instead, we'd have to ideally take, for each of the values extracted, its count and then divide it by the total number of values to obtain frequency counts. Note that these are the probabilities of each possible value and they sum up to 1: ###Code freq_counts = [item / n for item in bin_counts] sum(freq_counts) ###Output _____no_output_____ ###Markdown Then we can easily plot them to obtain the PMF histogram: ###Code plt.bar(range(0, 10), freq_counts, width=1, edgecolor='k') plt.xticks(range(0, 10)) plt.title('Histogram of $10^5$ uniformly distributed data, probs') plt.xlabel('Value') plt.ylabel('Frequency (prob) items') plt.show(); ###Output _____no_output_____ ###Markdown A gaussian distribution Now let's consider a gaussian distribution instead, taking the same amount ($10^5$) of numbers and plotting the bins counts again. This time we extract float numbers, randomly sampled from a gaussian distribution of mean 0 and standard deviation 1. We then separate the range in 20 bins and plot the histogram of the counts of each bin as above. We use a line to signify that effectively our variable is meant to be continuous.We attribute counts for a bin to the middle point of the bin. ###Code data = np.random.normal(size=n) bins = 20 # choose to separate into 20 bins hist = np.histogram(data, bins=bins) hist_vals, bin_edges = hist[0], hist[1] bin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)] # mids of bins again plt.plot(bin_mids, hist_vals, marker='o') plt.title('Histogram $10^5$ normally distributed data') plt.xlabel('Bin mid') plt.ylabel('Count items') plt.show(); ###Output _____no_output_____ ###Markdown Each bin is large ###Code bin_edges[1] - bin_edges[0] ###Output _____no_output_____ ###Markdown So, it is quite clear from the plot that the mean is indeed at 0. We can also do the same histogram but showing the pdf instead: ###Code bins = 20 hist = np.histogram(data, bins=bins, density=True) hist_vals, bin_edges = hist[0], hist[1] bin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)] plt.plot(bin_mids, hist_vals, marker='o') plt.title('Histogram $10^5$ normally distributed data') plt.xlabel('Bin mid') plt.ylabel('Count items') plt.show(); ###Output _____no_output_____ ###Markdown Because what we plotted above here^ is a density of probability, what sums up to 1 is not those values but the product of value times the bin width: ###Code sum([(bin_edges[i+1] - bin_edges[i]) * hist_vals[i] for i in range(len(hist_vals))]) ###Output _____no_output_____ ###Markdown Effectively indeed, if we take for instance the first bin, its density represents the probability of being in that bin divided by the bin width itself, which is: ###Code hist_vals[0] ###Output _____no_output_____ ###Markdown Using boxplots as a visualisation tool Another very useful and quite comprehensive way to display distributions is through the use of *boxplots*. Boxplots let you see, in one go, the quartiles, the mean and the potential outliers in a distribution.To start off with, let's generate $10^5$ random numbers extracting them from a (in order):* uniform distribution* gaussian distribution with mean 0 and standard deviation 1* exponential distribution* Zipf distribution $\propto x^{-2}$ Let's set the styles of our boxplots: the mean will be a red romboid point, the median a red line, the outliers blue circles.Also, we identify as outliers those points which exceed the first or the third quartiles (on the respective sides) by 1.5 their value, according to [Tukey's criterion](http://www.physics.csbsju.edu/stats/box2.html).Following on, we create boxplots for each of our distributions. ###Code # Extract the random points n = 100000 # the number of points to extract u = np.random.uniform(size=n) g = np.random.normal(size=n) # gaussian e = np.random.exponential(size=n) # exponential z = np.random.zipf(a=2, size=n) # Zipf (power-law) x^{-2} # Set style of the plot # Style of the point for the mean meanpointprops = dict(marker='D', markeredgecolor='black', markerfacecolor='firebrick') # Style of the outliers points flierpointprops = dict(marker='o', markeredgecolor='blue', linestyle='none') # Style of the median line medianlineprops = dict(linewidth=2.5, color='firebrick') # Uniform distribution ax = plt.subplot() ax.boxplot(u, whis=1.5, showmeans=True, vert=False, meanprops=meanpointprops, flierprops=flierpointprops, medianprops=medianlineprops) plt.title('Box plot of a uniform distribution') plt.show(); ###Output _____no_output_____ ###Markdown Clearly the mean is in the middle of values and there are no outliers. ###Code # The gaussian distribution ax = plt.subplot() ax.boxplot(g, whis=1.5, showmeans=True, vert=False, meanprops=meanpointprops, flierprops=flierpointprops, medianprops=medianlineprops) plt.title('Box plot of a gaussian distribution with mean 0 and std 1') plt.show(); ###Output _____no_output_____ ###Markdown The symmetrical tail of "outliers" is visibile. ###Code # The exponential distribution ax = plt.subplot() ax.boxplot(e, whis=1.5, showmeans=True, vert=False, meanprops=meanpointprops, flierprops=flierpointprops, medianprops=medianlineprops) plt.title('Box plot of an exponential distribution') plt.show(); ###Output _____no_output_____ ###Markdown This time the distribution is heavily non-symmetrical and the tail of exceeding values is clear. ###Code # The Zipf distribution ax = plt.subplot() ax.boxplot(z, whis=1.5, showmeans=True, vert=False, meanprops=meanpointprops, flierprops=flierpointprops, medianprops=medianlineprops) plt.title('Box plot of a Zipf distribution') plt.show(); ###Output _____no_output_____
data/Output-Python/852021_FDefaultCapsol.ipynb
###Markdown Tirmzi Analysisn=1000 m+=1000 nm-=120 istep= 4 min=150 max=700 ###Code import sys sys.path import matplotlib.pyplot as plt import numpy as np import os from scipy import signal ls import capsol.newanalyzecapsol as ac ac.get_gridparameters import glob folders = glob.glob("Fortran/*/") folders all_data= dict() for folder in folders: params = ac.get_gridparameters(folder + 'capsol.in') data = ac.np.loadtxt(folder + 'Z-U.dat') process_data = ac.process_data(params, data, smoothing=False, std=5*10**-9) all_data[folder]= (process_data) all_params= dict() for folder in folders: params=ac.get_gridparameters(folder + 'capsol.in') all_params[folder]= (params) all_data all_data.keys() for key in {key: params for key, params in all_params.items() if params['Thickness_sample'] == .5}: data=all_data[key] thickness =all_params[key]['Thickness_sample'] rtip= all_params[key]['Rtip'] er=all_params[key]['eps_r'] plt.plot(data['z'], data['c'], label= f'{rtip} nm, {er}, {thickness} nm') plt.title('C v. Z for 1nm thick sample') plt.ylabel("C(m)") plt.xlabel("Z(m)") plt.legend() plt.savefig("C' v. Z for 1nm thick sample 06-28-2021.png") ###Output _____no_output_____ ###Markdown cut off last experiment because capacitance was off the scale ###Code for key in {key: params for key, params in all_params.items() if params['Thickness_sample'] == .5}: data=all_data[key] thickness=all_params[key]['Thickness_sample'] rtip= all_params[key]['Rtip'] er=all_params[key]['eps_r'] s=slice(4,-3) plt.plot(data['z'][s], data['cz'][s], label=f'{rtip} nm, {er}, {thickness} nm' ) plt.title('Cz vs. Z for 1.0nm') plt.ylabel("Cz") plt.xlabel("Z(m)") plt.legend() plt.savefig("Cz v. Z for varying sample thickness, 06-28-2021.png") for key in {key: params for key, params in all_params.items() if params['Thickness_sample'] == .5}: data=all_data[key] thickness=all_params[key]['Thickness_sample'] rtip= all_params[key]['Rtip'] er=all_params[key]['eps_r'] s=slice(5,-5) plt.plot(data['z'][s], data['czz'][s], label=f'{rtip} nm, {er}, {thickness} nm' ) plt.title('Czz vs. Z for 1.0nm') plt.ylabel("Czz") plt.xlabel("Z(m)") plt.legend() plt.savefig("Czz v. Z for varying sample thickness, 06-28-2021.png") params for key in {key: params for key, params in all_params.items() if params['Thickness_sample'] == .5}: data=all_data[key] thickness=all_params[key]['Thickness_sample'] rtip= all_params[key]['Rtip'] er=all_params[key]['eps_r'] s=slice(8,-8) plt.plot(data['z'][s], data['alpha'][s], label=f'{rtip} nm, {er}, {thickness} nm' ) plt.title('alpha vs. Z for 1.0nm') plt.ylabel("$\\alpha$") plt.xlabel("Z(m)") plt.legend() plt.savefig("Alpha v. Z for varying sample thickness, 06-28-2021.png") data from scipy.optimize import curve_fit def Cz_model(z, a, n, b,): return(a*z**n + b) all_data.keys() data= all_data['capsol-calc\\0001-capsol\\'] z= data['z'][1:-1] cz= data['cz'][1:-1] popt, pcov= curve_fit(Cz_model, z, cz, p0=[cz[0]*z[0], -1, 0]) a=popt[0] n=popt[1] b=popt[2] std_devs= np.sqrt(pcov.diagonal()) sigma_a = std_devs[0] sigma_n = std_devs[1] model_output= Cz_model(z, a, n, b) rmse= np.sqrt(np.mean((cz - model_output)**2)) f"a= {a} ± {sigma_a}" f"n= {n}± {sigma_n}" model_output "Root Mean Square Error" rmse/np.mean(-cz) ###Output _____no_output_____
preprocessing_pipeline/eda.ipynb
###Markdown This notebook will focus on performing EDA on the sales data ###Code __author__ = "konwar.m" __copyright__ = "Copyright 2022, AI R&D" __credits__ = ["konwar.m"] __license__ = "Individual Ownership" __version__ = "1.0.1" __maintainer__ = "konwar.m" __email__ = "[email protected]" __status__ = "Development" ###Output _____no_output_____ ###Markdown The following steps would be covered so as to perform EDA on sales data 1. Data Sourcing2. Data Cleaning3. Univariate Analysis4. Bivariate Analysis5. Multivariate Analysis 1. Data Sourcing: This dataset is collected from a public data source platform known as Kaggle. Please follow this link to get this: https://www.kaggle.com/c/competitive-data-science-predict-future-sales/dataAlso find crucial information regarding this dataset:**File descriptions** sales_train.csv - the training set. Daily historical data from January 2013 to October 2015. test.csv - the test set. You need to forecast the sales for these shops and products for November 2015. sample_submission.csv - a sample submission file in the correct format. items.csv - supplemental information about the items/products. item_categories.csv - supplemental information about the items categories. shops.csv- supplemental information about the shops.**Data fields** ID - an Id that represents a (Shop, Item) tuple within the test set shop_id - unique identifier of a shop item_id - unique identifier of a product item_category_id - unique identifier of item category item_cnt_day - number of products sold. You are predicting a monthly amount of this measure item_price - current price of an item date - date in format dd/mm/yyyy date_block_num - a consecutive month number, used for convenience. January 2013 is 0, February 2013 is 1,..., October 2015 is 33 item_name - name of item shop_name - name of shop item_category_name - name of item category 2. Data CleaningIrregularities in a dataset are of different types. Please refer to details below Missing Values Duplicate ValuesIncorrect Format Incorrect Headers Anomalies/Outliers ###Code # Importing useful libraries. import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline os.chdir('..') os.getcwd() # Read the data set of "Marketing Analysis" in data. retail_data = pd.read_csv(os.path.join('datasets', 'sales_train.csv')) # Printing the data retail_data.head() ###Output _____no_output_____ ###Markdown Check for missing values There are mainly three types of missing values. **MCAR(Missing completely at random):** These values do not depend on any other features. **MAR(Missing at random):** These values may be dependent on some other features. **MNAR(Missing not at random):** These missing values have some reason for why they are missing. ###Code # Checking the missing values retail_data.isnull().sum() ###Output _____no_output_____ ###Markdown If there are lesser number of missing values in any of the column, they can be easily removed from the dataset but the best way to handle such situation is to replace those missing values with 'mean' or 'median' in case of numerical values or 'mode' in case of categorical column Check for duplicates records ###Code duplicate = retail_data.duplicated() print(duplicate.sum()) retail_data[duplicate] ###Output 6 ###Markdown Since, there are only 6 duplicates, we will remove them from the retail dataset and re-evaluate duplications again ###Code retail_data.drop_duplicates(inplace=True) duplicate = retail_data.duplicated() print(duplicate.sum()) ###Output 0 ###Markdown Handling outliersThere are two types of outliers: **1. Univariate outliers:** Univariate outliers are the data points whose values lie beyond the range of expected values based on one variable. **2. Multivariate outliers:** While plotting data, some values of one variable may not lie beyond the expected range, but when you plot the data with some other variable, these values may lie far from the expected value.![Outlier Types](../assets/outlier_types.jpg)Box plot is used normally to check for outliers ###Code retail_data.boxplot(column=['item_cnt_day']) ###Output _____no_output_____ ###Markdown 3. Univariate Analysis **Categorical Unordered Univariate Analysis:** Its applied on categorical columns once we identify which columns are object types from the dataset ###Code retail_data.dtypes # Let's calculate the percentage of unique date counts. retail_data.head(100).date.value_counts(normalize=True) #plot the bar graph of percentage dates plt.figure(figsize=(10,10)) retail_data.head(1000).date.value_counts(normalize=True).plot.barh() plt.show() ###Output _____no_output_____ ###Markdown 4.Bivariate Analysis: If we analyze data by taking two variables/columns into consideration from a dataset may be numerical columns one on one. a) Numeric Bivariate Analysis is done by using below techniques:1. Scatter Plot2. Pair Plot and3. Correlation Plot ###Code #plot the scatter plot of balance and salary variable in data plt.scatter(retail_data.item_price, retail_data.item_cnt_day) plt.show() #plot the pair plot of salary, balance and age in data dataframe. sns.pairplot(data = retail_data, vars=['item_price','item_cnt_day','shop_id', 'item_id']) plt.show() plt.figure(figsize=(8,8)) c= retail_data.corr() sns.heatmap(c, cmap='BrBG', annot=True) ###Output _____no_output_____ ###Markdown 5. Multivariate AnalysisItem Price, Item Count Per day, Item ID is used to pivot the results ###Code result = pd.pivot_table(data=retail_data.head(1000), index='shop_id', columns='item_id',values='item_cnt_day') print(result) plt.figure(figsize=(15,15)) #create heat map of education vs marital vs response_rate sns.heatmap(result, annot=True, cmap = 'RdYlGn', center=0.117) plt.show() ###Output item_id 785 791 804 810 829 832 839 944 965 \ shop_id 25 1.0 1.333333 1.0 1.0 1.0 1.0 1.0 1.0 1.0 59 NaN NaN NaN NaN NaN NaN NaN NaN NaN item_id 970 ... 5224 5256 5260 5261 5263 5272 5275 \ shop_id ... 25 1.0 ... 1.0 1.333333 1.0 1.2 1.0 1.428571 1.0 59 NaN ... NaN NaN NaN NaN NaN NaN NaN item_id 5313 5324 22154 shop_id 25 1.0 1.0 NaN 59 NaN NaN 1.0 [2 rows x 380 columns]
notebooks/5.Using of RGB strip/1.Light up a RGB light at any position/Light up a RGB light at any position.ipynb
###Markdown @Copyright (C): 2010-2019, Shenzhen Yahboom Tech @Author: Malloy.Yuan @Date: 2019-07-17 10:10:02 @LastEditors: Malloy.Yuan @LastEditTime: 2019-09-17 17:54:19 Import Yahboom officially packaged RGB driver libraryCreate and initialize a programmable RGB object ###Code from RGB_Lib import Programing_RGB RGB = Programing_RGB() ###Output _____no_output_____ ###Markdown Set the first RGB light to white., which is the left rear position RGB light of Jetbot The color parameter in the method is R G B ###Code RGB.Set_An_RGB(0, 0xFF, 0xFF, 0xFF) ###Output _____no_output_____ ###Markdown Set all RGB to red ###Code RGB.Set_All_RGB(0xFF, 0x00, 0x00) ###Output _____no_output_____ ###Markdown Set all RGB to green ###Code RGB.Set_All_RGB(0x00, 0xFF, 0x00) ###Output _____no_output_____ ###Markdown Set all RGB to blue ###Code RGB.Set_All_RGB(0x00, 0x00, 0xFF) ###Output _____no_output_____ ###Markdown Close all RGB ###Code RGB.OFF_ALL_RGB() ###Output _____no_output_____
_notebooks/2021-10-07-kagglestudy3.ipynb
###Markdown "[SSUDA] 택시 데이터 분석"- author: Seong Yeon Kim - categories: [SSUDA, jupyter, kaggle, datetime, scale, location, Regression] - image: images/211007.png 데이터 불러오기 ###Code !pip install kaggle from google.colab import files files.upload() !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !chmod 600 ~/.kaggle/kaggle.json !kaggle competitions download -c nyc-taxi-trip-duration !unzip train.zip !unzip test.zip !unzip sample_submission.zip ###Output Archive: train.zip replace train.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: Y inflating: train.csv Archive: test.zip replace test.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: Y inflating: test.csv Archive: sample_submission.zip replace sample_submission.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: Y inflating: sample_submission.csv ###Markdown 압축되어 있는 데이터라서 압축 풀어줍니다. ###Code %matplotlib inline import pandas as pd from datetime import datetime import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Ridge,BayesianRidge from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import mean_squared_error from math import radians, cos, sin, asin, sqrt import seaborn as sns import matplotlib import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [16, 10] train = pd.read_csv('./train.csv') test = pd.read_csv('./test.csv') ###Output _____no_output_____ ###Markdown 데이터 탐색 ###Code train.head() train.describe() train.info() test.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 625134 entries, 0 to 625133 Data columns (total 9 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 625134 non-null object 1 vendor_id 625134 non-null int64 2 pickup_datetime 625134 non-null object 3 passenger_count 625134 non-null int64 4 pickup_longitude 625134 non-null float64 5 pickup_latitude 625134 non-null float64 6 dropoff_longitude 625134 non-null float64 7 dropoff_latitude 625134 non-null float64 8 store_and_fwd_flag 625134 non-null object dtypes: float64(4), int64(2), object(3) memory usage: 42.9+ MB ###Markdown dropoff_datetime 변수가 test에는 없습니다. 도착 시간을 맞추는 예제이기 때문에 그렇습니다. 반응변수 관찰 ###Code plt.figure(figsize=(8,6)) plt.scatter(range(train.shape[0]), np.sort(train.trip_duration.values)) plt.xlabel('index', fontsize=12) plt.ylabel('trip duration', fontsize=12) plt.show() ###Output _____no_output_____ ###Markdown 반응변수의 이상치가 많아보입니다. 제거하겠습니다. ###Code m = np.mean(train['trip_duration']) s = np.std(train['trip_duration']) train = train[train['trip_duration'] <= m + 2*s] train = train[train['trip_duration'] >= m - 2*s] plt.figure(figsize=(8,6)) plt.scatter(range(train.shape[0]), np.sort(train.trip_duration.values)) plt.xlabel('index', fontsize=12) plt.ylabel('trip duration', fontsize=12) plt.show() ###Output _____no_output_____ ###Markdown 이상치는 대부분 제거된 것 같습니다. 다만 일부 데이터가 큰 값을 갖는거 같아요. ###Code plt.hist(train['trip_duration'].values, bins=100) plt.xlabel('trip_duration') plt.ylabel('number of train records') plt.show() ###Output _____no_output_____ ###Markdown 히스토그램으로 확인하니 그렇습니다. 우측 꼬리가 긴 모양으로 로그변환이 필요해보입니다. ###Code train['log_trip_duration'] = np.log(train['trip_duration'].values + 1) plt.hist(train['log_trip_duration'].values, bins=100) plt.xlabel('log(trip_duration)') plt.ylabel('number of train records') plt.show() sns.distplot(train["log_trip_duration"], bins =100) ###Output _____no_output_____ ###Markdown 확실히 그래프 모양이 괜찮아졌습니다. distplot 함수를 통해 그리기도 하였네요 데이터 전처리 ###Code train = train[train['pickup_longitude'] <= -73.75] train = train[train['pickup_longitude'] >= -74.03] train = train[train['pickup_latitude'] <= 40.85] train = train[train['pickup_latitude'] >= 40.63] train = train[train['dropoff_longitude'] <= -73.75] train = train[train['dropoff_longitude'] >= -74.03] train = train[train['dropoff_latitude'] <= 40.85] train = train[train['dropoff_latitude'] >= 40.63] ###Output _____no_output_____ ###Markdown 뉴욕의 위도는 (-74.03, -73.75) 경도는 (40.63, 40.85)사이 입니다. 이 값을 벗어나는 위도/경도 데이터를 제거하겠습니다. ###Code train['pickup_datetime'] = pd.to_datetime(train.pickup_datetime) test['pickup_datetime'] = pd.to_datetime(test.pickup_datetime) train.loc[:, 'pickup_date'] = train['pickup_datetime'].dt.date test.loc[:, 'pickup_date'] = test['pickup_datetime'].dt.date train['dropoff_datetime'] = pd.to_datetime(train.dropoff_datetime) #Not in Test ###Output _____no_output_____ ###Markdown to_datetime 함수로 datetime 변수로 바궈주었습니다. ###Code plt.plot(train.groupby('pickup_date').count()[['id']], 'o-', label='train') plt.plot(test.groupby('pickup_date').count()[['id']], 'o-', label='test') plt.title('Trips over Time.') plt.legend(loc=0) plt.ylabel('Trips') plt.show() ###Output _____no_output_____ ###Markdown 트레인과 테스트 데이터를 같이 그리니 유사한 측면을 발견하기가 쉬운것 같아요.1월 하순경 이동횟수가 급격하게 감소한것이 관찰됩니다. 또 5월 하순경 감소세가 또 관찰됩니다.계절적으로 추운것도 있겠지만 작성자는 다른 요인이 있지 않을까 생각하네요. ###Code import warnings warnings.filterwarnings("ignore") plot_vendor = train.groupby('vendor_id')['trip_duration'].mean() plt.subplots(1,1,figsize=(17,10)) plt.ylim(ymin=800) plt.ylim(ymax=840) sns.barplot(plot_vendor.index,plot_vendor.values) plt.title('Time per Vendor') plt.legend(loc=0) plt.ylabel('Time in Seconds') ###Output No handles with labels found to put in legend. ###Markdown 범위를 800~840으로 두어서 그렇지 두 vendor 간 큰 차이를 보이진 않습니다. ###Code snwflag = train.groupby('store_and_fwd_flag')['trip_duration'].mean() plt.subplots(1,1,figsize=(17,10)) plt.ylim(ymin=0) plt.ylim(ymax=1100) plt.title('Time per store_and_fwd_flag') plt.legend(loc=0) plt.ylabel('Time in Seconds') sns.barplot(snwflag.index,snwflag.values) ###Output No handles with labels found to put in legend. ###Markdown 공급업체에 보내기 전 기록이 잘 저장되었는지 나타내는 변수로 꽤 많이 차이가 납니다.작성자는 일부 직원이 이동시간을 정확히 기록하지 못해 발생하는 왜곡이라고 말합니다. ###Code pc = train.groupby('passenger_count')['trip_duration'].mean() plt.subplots(1,1,figsize=(17,10)) plt.ylim(ymin=0) plt.ylim(ymax=1100) plt.title('Time per store_and_fwd_flag') plt.legend(loc=0) plt.ylabel('Time in Seconds') sns.barplot(pc.index,pc.values) ###Output No handles with labels found to put in legend. ###Markdown 승객 수는 뚜렷한 여행을 주지 못합니다.승객을 아무도 태우지 않았는데 4분정도 이동한 것은 직원의 실수로 보입니다. ###Code train.groupby('passenger_count').size() ###Output _____no_output_____ ###Markdown 위치 데이터 ###Code city_long_border = (-74.03, -73.75) city_lat_border = (40.63, 40.85) fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True) ax[0].scatter(train['pickup_longitude'].values[:100000], train['pickup_latitude'].values[:100000], color='blue', s=1, label='train', alpha=0.1) ax[1].scatter(test['pickup_longitude'].values[:100000], test['pickup_latitude'].values[:100000], color='green', s=1, label='test', alpha=0.1) fig.suptitle('Train and test area complete overlap.') ax[0].legend(loc=0) ax[0].set_ylabel('latitude') ax[0].set_xlabel('longitude') ax[1].set_xlabel('longitude') ax[1].legend(loc=0) plt.ylim(city_lat_border) plt.xlim(city_long_border) plt.show() ###Output _____no_output_____ ###Markdown 자세한 코드 관찰은 위치 데이터 분석을 할때 다시 확인하겠습니다.train, test 간 위치 데이터가 매우 유사함을 알 수 있습니다. ###Code def haversine_array(lat1, lng1, lat2, lng2): lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2)) AVG_EARTH_RADIUS = 6371 # in km lat = lat2 - lat1 lng = lng2 - lng1 d = np.sin(lat * 0.5) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(lng * 0.5) ** 2 h = 2 * AVG_EARTH_RADIUS * np.arcsin(np.sqrt(d)) return h def dummy_manhattan_distance(lat1, lng1, lat2, lng2): a = haversine_array(lat1, lng1, lat1, lng2) b = haversine_array(lat1, lng1, lat2, lng1) return a + b def bearing_array(lat1, lng1, lat2, lng2): AVG_EARTH_RADIUS = 6371 # in km lng_delta_rad = np.radians(lng2 - lng1) lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2)) y = np.sin(lng_delta_rad) * np.cos(lat2) x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(lng_delta_rad) return np.degrees(np.arctan2(y, x)) train.loc[:, 'distance_haversine'] = haversine_array(train['pickup_latitude'].values, train['pickup_longitude'].values, train['dropoff_latitude'].values, train['dropoff_longitude'].values) test.loc[:, 'distance_haversine'] = haversine_array(test['pickup_latitude'].values, test['pickup_longitude'].values, test['dropoff_latitude'].values, test['dropoff_longitude'].values) train.loc[:, 'distance_dummy_manhattan'] = dummy_manhattan_distance(train['pickup_latitude'].values, train['pickup_longitude'].values, train['dropoff_latitude'].values, train['dropoff_longitude'].values) test.loc[:, 'distance_dummy_manhattan'] = dummy_manhattan_distance(test['pickup_latitude'].values, test['pickup_longitude'].values, test['dropoff_latitude'].values, test['dropoff_longitude'].values) train.loc[:, 'direction'] = bearing_array(train['pickup_latitude'].values, train['pickup_longitude'].values, train['dropoff_latitude'].values, train['dropoff_longitude'].values) test.loc[:, 'direction'] = bearing_array(test['pickup_latitude'].values, test['pickup_longitude'].values, test['dropoff_latitude'].values, test['dropoff_longitude'].values) ###Output _____no_output_____ ###Markdown 위도/경도를 활용하여 다양한 관측값을 나타내는 함수입니다.이해하기에 조금 벅차서 일단 다양한 변수를 추가해줄수 있구나 하고 넘어갔네요. ###Code coords = np.vstack((train[['pickup_latitude', 'pickup_longitude']].values, train[['dropoff_latitude', 'dropoff_longitude']].values)) sample_ind = np.random.permutation(len(coords))[:500000] kmeans = MiniBatchKMeans(n_clusters=100, batch_size=10000).fit(coords[sample_ind]) train.loc[:, 'pickup_cluster'] = kmeans.predict(train[['pickup_latitude', 'pickup_longitude']]) train.loc[:, 'dropoff_cluster'] = kmeans.predict(train[['dropoff_latitude', 'dropoff_longitude']]) test.loc[:, 'pickup_cluster'] = kmeans.predict(test[['pickup_latitude', 'pickup_longitude']]) test.loc[:, 'dropoff_cluster'] = kmeans.predict(test[['dropoff_latitude', 'dropoff_longitude']]) ###Output _____no_output_____ ###Markdown np.vstack는 데이터를 묶어주는 함수입니다.위도, 경도 데이터를 클러스트로 묶어주었습니다. ###Code fig, ax = plt.subplots(ncols=1, nrows=1) ax.scatter(train.pickup_longitude.values[:500000], train.pickup_latitude.values[:500000], s=10, lw=0, c=train.pickup_cluster[:500000].values, cmap='autumn', alpha=0.2) ax.set_xlim(city_long_border) ax.set_ylim(city_lat_border) ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') plt.show() ###Output _____no_output_____ ###Markdown 군집화가 잘된 것을 시각적으로 확인하였습니다. 날짜 데이터 ###Code train['Month'] = train['pickup_datetime'].dt.month test['Month'] = test['pickup_datetime'].dt.month train['DayofMonth'] = train['pickup_datetime'].dt.day test['DayofMonth'] = test['pickup_datetime'].dt.day train['Hour'] = train['pickup_datetime'].dt.hour test['Hour'] = test['pickup_datetime'].dt.hour train['dayofweek'] = train['pickup_datetime'].dt.dayofweek test['dayofweek'] = test['pickup_datetime'].dt.dayofweek ###Output _____no_output_____ ###Markdown 픽업된 시간으로 다양한 파생 날짜/시간 데이터를 생성한 모습입니다. datetime 변수이기에 가능한 모습입니다.여기서 dayofweek 변수는 요일변수로 0을 일요일로 생각하여 6을 토요일까지 쓰는 변수입니다. ###Code train.loc[:, 'avg_speed_h'] = 1000 * train['distance_haversine'] / train['trip_duration'] train.loc[:, 'avg_speed_m'] = 1000 * train['distance_dummy_manhattan'] / train['trip_duration'] fig, ax = plt.subplots(ncols=3, sharey=True) ax[0].plot(train.groupby('Hour').mean()['avg_speed_h'], 'bo-', lw=2, alpha=0.7) ax[1].plot(train.groupby('dayofweek').mean()['avg_speed_h'], 'go-', lw=2, alpha=0.7) ax[2].plot(train.groupby('Month').mean()['avg_speed_h'], 'ro-', lw=2, alpha=0.7) ax[0].set_xlabel('Hour of Day') ax[1].set_xlabel('Day of Week') ax[2].set_xlabel('Month of Year') ax[0].set_ylabel('Average Speed') fig.suptitle('Average Traffic Speed by Date-part') plt.show() ###Output _____no_output_____ ###Markdown 정확히 이해하진 못했지만 distance_haversine가 위치 변수를 보고 만든 거리 변수입니다.그렇기 때문에 거리 / 시간 = 평균속도 변수를 만들었습니다. 이 평균속도를 시각/요일/달 별로 얼마나 다른지 시각화했습니다.물론 분모인 시간이 반응변수 이기 때문에 분석에 사용할수는 없습니다.보통 오전 5시~9시, 오후 5시(17시) ~ 7시(19시) 사이가 가장 도로가 혼잡해 속도가 떨어집니다.예상과 어느정도 일치하면서도 출/퇴근 이외 근무시간도 속도가 출/퇴근 시간과 비슷하게 떨어집니다.또 금토일의 평균속도가 상대적으로 빠르며 달별로는 겨울의 평균속도가 빠릅니다. 원핫인코딩 ###Code vendor_train = pd.get_dummies(train['vendor_id'], prefix='vi', prefix_sep='_') vendor_test = pd.get_dummies(test['vendor_id'], prefix='vi', prefix_sep='_') passenger_count_train = pd.get_dummies(train['passenger_count'], prefix='pc', prefix_sep='_') passenger_count_test = pd.get_dummies(test['passenger_count'], prefix='pc', prefix_sep='_') store_and_fwd_flag_train = pd.get_dummies(train['store_and_fwd_flag'], prefix='sf', prefix_sep='_') store_and_fwd_flag_test = pd.get_dummies(test['store_and_fwd_flag'], prefix='sf', prefix_sep='_') cluster_pickup_train = pd.get_dummies(train['pickup_cluster'], prefix='p', prefix_sep='_') cluster_pickup_test = pd.get_dummies(test['pickup_cluster'], prefix='p', prefix_sep='_') cluster_dropoff_train = pd.get_dummies(train['dropoff_cluster'], prefix='d', prefix_sep='_') cluster_dropoff_test = pd.get_dummies(test['dropoff_cluster'], prefix='d', prefix_sep='_') month_train = pd.get_dummies(train['Month'], prefix='m', prefix_sep='_') month_test = pd.get_dummies(test['Month'], prefix='m', prefix_sep='_') dom_train = pd.get_dummies(train['DayofMonth'], prefix='dom', prefix_sep='_') dom_test = pd.get_dummies(test['DayofMonth'], prefix='dom', prefix_sep='_') hour_train = pd.get_dummies(train['Hour'], prefix='h', prefix_sep='_') hour_test = pd.get_dummies(test['Hour'], prefix='h', prefix_sep='_') dow_train = pd.get_dummies(train['dayofweek'], prefix='dow', prefix_sep='_') dow_test = pd.get_dummies(test['dayofweek'], prefix='dow', prefix_sep='_') ###Output _____no_output_____ ###Markdown 범주형 변수들을 전부 원핫인코딩을 했습니다.prefix 와 prefix_sep 으로 원핫인코딩 변수 이름도 설정할수 있네요. ###Code passenger_count_test = passenger_count_test.drop('pc_9', axis = 1) ###Output _____no_output_____ ###Markdown 다만 9명이 탑승한 2건은 표본이 너무 적어 과적합될수도 있고 직관적으로도 말이 안되서 열을 삭제합니다. ###Code train = train.drop(['id','vendor_id','passenger_count','store_and_fwd_flag','Month','DayofMonth','Hour','dayofweek','pickup_datetime', 'pickup_date','pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude'],axis = 1) Test_id = test['id'] test = test.drop(['id','vendor_id','passenger_count','store_and_fwd_flag','Month','DayofMonth','Hour','dayofweek', 'pickup_datetime', 'pickup_date', 'pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude'], axis = 1) train = train.drop(['dropoff_datetime','avg_speed_h','avg_speed_m','trip_duration'], axis = 1) ###Output _____no_output_____ ###Markdown 원핫인코딩 된 변수들, 시각화를 위해 만들었던 변수들, 변환한 변수들, id 등 필요없는 변수를 제거합니다. ###Code Train_Master = pd.concat([train, vendor_train, passenger_count_train, store_and_fwd_flag_train, cluster_pickup_train, cluster_dropoff_train, month_train, dom_train, hour_test, dow_train ], axis=1) Test_master = pd.concat([test, vendor_test, passenger_count_test, store_and_fwd_flag_test, cluster_pickup_test, cluster_dropoff_test, month_test, dom_test, hour_test, dow_test], axis=1) Train_Master.shape,Test_master.shape ###Output _____no_output_____ ###Markdown 원핫인코딩했던 변수들을 합쳐줍니다. 모델 적합 ###Code X_train = Train_Master.drop(['log_trip_duration'], axis=1) Y_train = Train_Master["log_trip_duration"] Y_train = Y_train.reset_index().drop('index',axis = 1) ###Output _____no_output_____ ###Markdown 이 코드 이후로 모델적합을 해야하는데 코랩에서 계속 램이 부족하다고 하네요.데이터도 크고, 열 개수도 원핫인코딩으로 늘려서 그런거 같습니다.XGB였다가 LGB로 바꾸고, 노말모델로 하고 어떻게 해도 계속 램이 부족해서 실행이 안되네요.코드를 리뷰하는 목적이고 요즘 시간이 넉넉하지 못해서 여기까지 하겠습니다. ###Code from lightgbm import LGBMRegressor model = LGBMRegressor() model.fit(X_train, Y_train) pred = model.predict(Test_master) pred = np.exp(pred) submission = pd.concat([Test_id, pd.DataFrame(pred)], axis=1) submission.columns = ['id','trip_duration'] submission['trip_duration'] = submission.apply(lambda x : 1 if (x['trip_duration'] <= 0) else x['trip_duration'], axis = 1) submission.to_csv("./submission.csv", index=False) !kaggle competitions submit -c nyc-taxi-trip-duration -f submission.csv -m "Message" ###Output _____no_output_____
notebooks/4.a- Convex_optimization_model_with_previous_influence_matrices.ipynb
###Markdown =========================================================== Solve the estimation problem with convex optimization model on the supervised dataset from the Jeopardy-like logs ===========================================================Goals:1. Split the data into test and train2. Formulate the convex optimization model3. Compute train and test error Last update: 03 Dec 2019 Imports ###Code from __future__ import division, print_function, absolute_import, unicode_literals import cvxpy as cp import scipy as sp import pandas as pd import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns from collections import defaultdict import sys from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split sys.path.insert(0, '../src/') %matplotlib inline import utils from mytimer import Timer import imp def reload(): imp.reload(utils) ###Output _____no_output_____ ###Markdown Parameters ###Code data_fpath = '/home/omid/Datasets/Jeopardy/supervised_data_with_only_first_influence.pk' # data_fpath = '/home/omid/Datasets/Jeopardy/supervised_data.pk' # lambdaa = 1 test_fraction = 0.2 runs = 30 ###Output _____no_output_____ ###Markdown Helper functions ###Code def compute_matrix_err(true_matrix: np.matrix, pred_matrix: np.matrix, type_str: str = 'corr') -> float: if type_str == 'frob_norm': frob_norm_of_difference = np.linalg.norm(true_matrix - pred_matrix) err = frob_norm_of_difference / np.linalg.norm(true_matrix) return err elif type_str == 'corr': # (r, p) = sp.stats.spearmanr(np.array(true_matrix.flatten())[0], np.array(pred_matrix.flatten())[0]) (r, p) = sp.stats.pearsonr(np.array(true_matrix.flatten())[0], np.array(pred_matrix.flatten())[0]) if p > 0.05: r = 0 return r else: raise ValueError('Wrong type_str was given.') ###Output _____no_output_____ ###Markdown Loading the data ###Code data = utils.load_it(data_fpath) print(len(data['X'])) mats = [] for i in range(len(data['y'])): mats.append(data['y'][i]['influence_matrix'] / 100) np.mean(mats, axis=0) np.std(mats, axis=0) ###Output _____no_output_____ ###Markdown Formulating the convex optimization problem With only average of previous influence matrices: ###Code lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) B = cp.Variable(4, 4) constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] A1 = element['average_of_previous_influence_matrices'] pred_influence_matrix = A1 * W1 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) constraints += [pred_influence_matrix >= 0] constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: A1 = element['average_of_previous_influence_matrices'] predicted_influence_matrix = A1 * W1.value + B.value model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sns.heatmap(W1.value); sns.heatmap(B.value); plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6257138866867928 +- 0.01604257548685887 uniform: 0.3371604198790437 +- 0.01908804176115327 model: 0.23749912395791864 +- 0.015044850361760172 ###Markdown Logistic function with only first influence matrix ###Code lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(2): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] A1 = element['first_influence_matrices'] # losses += cp.sum_entries( cp.logistic(-influence_matrix * (A1 * W1 + B)) ) pred_influence_matrix = A1 * W1 + B losses += cp.sum_entries( cp.kl_div(influence_matrix, pred_influence_matrix) ) # pred_influence_matrix = A1 * W1 + B # losses += cp.sum_squares(pred_influence_matrix - influence_matrix) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: A1 = element['first_influence_matrices'] predicted_influence_matrix = A1 * W1.value + B.value # predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sns.heatmap(W1.value) sns.heatmap(B.value) plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6174122674483592 +- 0.010745327398581805 uniform: 0.32959302075858365 +- 0.0013100443835122044 model: 0.3118306822846595 +- 0.014195220272253922 ###Markdown With only first influence matrix: ###Code lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] A1 = element['first_influence_matrices'] pred_influence_matrix = A1 * W1 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: A1 = element['first_influence_matrices'] predicted_influence_matrix = A1 * W1.value + B.value predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sns.heatmap(W1.value); sns.heatmap(B.value); plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); # Just the dataset itself: plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6212294304253135 +- 0.01706147914657565 uniform: 0.3308111043908909 +- 0.019409182902447326 model: 0.3044930561618803 +- 0.016874360467564523 ###Markdown With individual performance ###Code runs = 30 with Timer(): lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] # A1 = element['individual_performance'] p = element['individual_performance_hardness_weighted'] A1 = np.row_stack([p, p, p, p]) pred_influence_matrix = A1 * W1 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: # A1 = element['individual_performance'] p = element['individual_performance_hardness_weighted'] A1 = np.row_stack([p, p, p, p]) predicted_influence_matrix = A1 * W1.value + B.value predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sns.heatmap(W1.value); sns.heatmap(B.value); plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']) print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6216012908918773 +- 0.01642054499508854 uniform: 0.33076050491720327 +- 0.020687093389048193 model: 0.3277117626599369 +- 0.018084551142832275 ###Markdown With first influence matrix and individual performance (with correlation) ###Code with Timer(): # injaaaaaaaaaaaaaa lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) W2 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = np.matrix(utils.make_matrix_row_stochastic( y_train[index]['influence_matrix'])) A1 = element['first_influence_matrices'] p = element['individual_performance_hardness_weighted'] A2 = np.row_stack([p, p, p, p]) pred_influence_matrix = A1 * W1 + A2 * W2 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = np.matrix(utils.make_matrix_row_stochastic( y_test[index]['influence_matrix'])) # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: # A1 = element['individual_performance'] A1 = element['first_influence_matrices'] p = element['individual_performance_hardness_weighted'] A2 = np.row_stack([p, p, p, p]) predicted_influence_matrix = A1 * W1.value + A2 * W2.value + B.value predicted_influence_matrix = np.matrix(utils.make_matrix_row_stochastic(predicted_influence_matrix)) model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']) print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); corrz = [] for index in range(len(X_test)): element = X_test[index] influence_matrix = np.matrix(utils.make_matrix_row_stochastic( y_test[index]['influence_matrix'])) # Optimization model prediction: A1 = element['first_influence_matrices'] p = element['individual_performance_hardness_weighted'] A2 = np.row_stack([p, p, p, p]) predicted_influence_matrix = A1 * W1.value + A2 * W2.value + B.value predicted_influence_matrix = np.matrix(utils.make_matrix_row_stochastic(predicted_influence_matrix)) cr = compute_matrix_err( influence_matrix, predicted_influence_matrix) corrz.append(cr) corrz = np.array(corrz) plt.hist(corrz[corrz != 0]) ###Output _____no_output_____ ###Markdown With first influence matrix and individual performance (with frob norm) ###Code sns.heatmap(W1.value); sns.heatmap(W2.value); sns.heatmap(B.value); plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']) print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6273743596380378 +- 0.022857344339732598 uniform: 0.3325318587873968 +- 0.016509363259459668 model: 0.30392078030000086 +- 0.014614658704437995 ###Markdown With dataset itself (not replicating) ###Code with Timer(): lambdaa = 0.1 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) # X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( # X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) W2 = cp.Variable(4, 4) B = cp.Variable(4, 4) constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = utils.make_matrix_row_stochastic( y_train[index]['influence_matrix']) A1 = element['first_influence_matrices'] p = element['individual_performance_hardness_weighted'] A2 = np.row_stack([p, p, p, p]) pred_influence_matrix = A1 * W1 + A2 * W2 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) constraints += [pred_influence_matrix >= 0] constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = utils.make_matrix_row_stochastic( y_test[index]['influence_matrix']) # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: A1 = element['first_influence_matrices'] p = element['individual_performance_hardness_weighted'] A2 = np.row_stack([p, p, p, p]) predicted_influence_matrix = A1 * W1.value + A2 * W2.value + B.value predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sns.heatmap(W1.value); sns.heatmap(W2.value); sns.heatmap(B.value); # With dataset itself: plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']) print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.627369947142661 +- 0.016018037218512353 uniform: 0.33690498301216276 +- 0.020407942132259903 model: 0.30886834958388787 +- 0.012053484282264085 ###Markdown With previous influence matrices and all networks ###Code with Timer(): runs = 5 lambdaas = [0, 0.01, 0.05, 0.1, 0.2, 0.3, 0.5, 0.9, 1, 2, 5, 10, 100, 1000, 10000] model_errs = defaultdict(list) for lambdaa in lambdaas: print('Lambda: ', lambdaa, '...') for run in range(runs): X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) W2 = cp.Variable(4, 4) W3 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] # A1 = element['average_of_previous_influence_matrices'] A1 = element['first_influence_matrices'] A2 = element['reply_duration'] A3 = element['sentiment'] # A4 = element['emotion_arousal'] # A5 = element['emotion_dominance'] # A6 = element['emotion_valence'] pred_influence_matrix = A1 * W1 + A2 * W2 + A3 * W3 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(W2) + cp.norm1(W3) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Optimization model prediction: A1 = element['first_influence_matrices'] A2 = element['reply_duration'] A3 = element['sentiment'] predicted_influence_matrix = A1 * W1.value + A2 * W2.value + A3 * W3.value + B.value # predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) # << UNCOMMENT IT >> model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) model_errs[lambdaa].append(model_err) errz = [] for lambdaa in lambdaas: print(lambdaa, ': ', np.mean(model_errs[lambdaa]), '+-', np.std(model_errs[lambdaa])) errz.append(np.mean(model_errs[lambdaa])) ###Output 0 : 0.3011743802652413 +- 0.020063083113073005 0.01 : 0.2963133866176929 +- 0.015973161966079022 0.05 : 0.3062668795795276 +- 0.013874774618744515 0.1 : 0.3095999597617864 +- 0.017819090728314457 0.2 : 0.2941185878549716 +- 0.02006738367903435 0.3 : 0.30257457579288827 +- 0.013306889155314812 0.5 : 0.3078848763423549 +- 0.005515771787705399 0.9 : 0.29270645819532487 +- 0.01848981548039053 1 : 0.30146502732172176 +- 0.015082943084012262 2 : 0.30887201679195064 +- 0.020579339692010812 5 : 0.30389845778067637 +- 0.014803297392890165 10 : 0.3096589878225967 +- 0.01617236135673211 100 : 0.3108994226093108 +- 0.015821189229998523 1000 : 0.4881974650919253 +- 0.01133999614957398 10000 : 0.9999999956332914 +- 3.214929424423093e-10 ###Markdown Runs with tunned lambda ###Code lambdaa = 0.9 runs = 30 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) W2 = cp.Variable(4, 4) W3 = cp.Variable(4, 4) # W4 = cp.Variable(4, 4) # W5 = cp.Variable(4, 4) # W6 = cp.Variable(4, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] # A1 = element['average_of_previous_influence_matrices'] A1 = element['first_influence_matrices'] A2 = element['reply_duration'] A3 = element['sentiment'] # A4 = element['emotion_arousal'] # A5 = element['emotion_dominance'] # A6 = element['emotion_valence'] pred_influence_matrix = A1 * W1 + A2 * W2 + A3 * W3 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(W2) + cp.norm1(W3) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: # A1 = element['average_of_previous_influence_matrices'] A1 = element['first_influence_matrices'] A2 = element['reply_duration'] A3 = element['sentiment'] # A4 = element['emotion_arousal'] # A5 = element['emotion_dominance'] # A6 = element['emotion_valence'] predicted_influence_matrix = A1 * W1.value + A2 * W2.value + A3 * W3.value + B.value # predicted_influence_matrix = utils.make_matrix_row_stochastic(predicted_influence_matrix) # << UNCOMMENT IT >> model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) # err += frob_norm_of_difference model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) sum(np.array(uniform_errs) > np.array(model_errs)) / len(model_errs) plt.plot(np.array(uniform_errs) - np.array(model_errs), '*'); sns.heatmap(W1.value); sns.heatmap(W2.value); sns.heatmap(W3.value); sns.heatmap(B.value); plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); # With the data itself: plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); # plt.hist(model_errs) # # plt.hist(random_errs) # plt.hist(uniform_errs) # # plt.legend(['model', 'random', 'uniform']); # plt.legend(['model', 'uniform']) # print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) # print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) # print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6256036346292906 +- 0.02295350141450487 uniform: 0.33512193590092 +- 0.019971630246377763 model: 0.2452193368273235 +- 0.014147432504710407 ###Markdown With text embeddings and the first influence matrix: ###Code # with Timer(): # runs = 5 # lambdaas = [0, 0.01, 0.05, 0.1, 0.2, 0.3, 0.5, 0.9, 1, 2, 5, 10, 100, 1000, 10000] # model_errs = defaultdict(list) # for lambdaa in lambdaas: # print('Lambda: ', lambdaa, '...') # for run in range(runs): # X_train, X_test, y_train, y_test = train_test_split( # data['X'], data['y'], test_size=test_fraction) # X_train, y_train = replicate_train_dataset(X_train, y_train) # # Solving the optimization problem. # with Timer(): # W1 = cp.Variable(4, 4) # W2 = cp.Variable(768, 4) # B = cp.Variable(4, 4) # constraints = [] # losses = 0 # for index in range(len(X_train)): # element = X_train[index] # influence_matrix = y_train[index]['influence_matrix'] # A1 = element['first_influence_matrices'] # A2 = element['content_embedding_matrix'] # pred_influence_matrix = A1 * W1 + A2 * W2 + B # loss = pred_influence_matrix - influence_matrix # losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] # regluarization = cp.norm1(W1) + cp.norm1(W2) + cp.norm1(B) # objective = cp.Minimize(losses + lambdaa * regluarization) # prob = cp.Problem(objective, constraints) # result = prob.solve(solver=cp.MOSEK) # print('It was {} and result was {}'.format(prob.status, result)) # model_err = 0 # for index in range(len(X_test)): # element = X_test[index] # influence_matrix = y_test[index]['influence_matrix'] # # Optimization model prediction: # A1 = element['first_influence_matrices'] # A2 = element['content_embedding_matrix'] # predicted_influence_matrix = A1 * W1.value + A2 * W2.value + B.value # model_err += compute_matrix_err( # influence_matrix, predicted_influence_matrix) # model_err /= len(X_test) # model_errs[lambdaa].append(model_err) # errz = [] # for lambdaa in lambdaas: # print(lambdaa, ': ', np.mean(model_errs[lambdaa]), '+-', np.std(model_errs[lambdaa])) # errz.append(np.mean(model_errs[lambdaa])) ###Output _____no_output_____ ###Markdown Runs ###Code lambdaa = 0.01 runs = 30 model_errs = [] random_errs = [] uniform_errs = [] for run in range(runs): print('Run', run, '...') X_train, X_test, y_train, y_test = train_test_split( data['X'], data['y'], test_size=test_fraction) X_train, y_train = utils.replicate_networks_in_train_dataset_with_reordering( X_train, y_train) # Solving the optimization problem. with Timer(): W1 = cp.Variable(4, 4) W2 = cp.Variable(768, 4) B = cp.Variable(4, 4) # constraints = [] losses = 0 for index in range(len(X_train)): element = X_train[index] influence_matrix = y_train[index]['influence_matrix'] A1 = element['first_influence_matrices'] A2 = element['content_embedding_matrix'] pred_influence_matrix = A1 * W1 + A2 * W2 + B loss = pred_influence_matrix - influence_matrix losses += cp.sum_squares(loss) # constraints += [pred_influence_matrix >= 0] # constraints += [cp.sum_entries(pred_influence_matrix, axis=1) == 1] regluarization = cp.norm1(W1) + cp.norm1(W2) + cp.norm1(B) objective = cp.Minimize(losses + lambdaa * regluarization) prob = cp.Problem(objective) #, constraints) result = prob.solve(solver=cp.MOSEK) print('It was {} and result was {}'.format(prob.status, result)) model_err = 0 random_err = 0 uniform_err = 0 for index in range(len(X_test)): element = X_test[index] influence_matrix = y_test[index]['influence_matrix'] # Random model prediction: pred_random_influence_matrix = np.matrix(utils.make_matrix_row_stochastic( np.random.rand(4, 4))) random_err += compute_matrix_err( influence_matrix, pred_random_influence_matrix) # Uniform prediction: pred_uniform_influence_matrix = np.matrix(np.ones((4, 4)) * 0.25) uniform_err += compute_matrix_err( influence_matrix, pred_uniform_influence_matrix) # Optimization model prediction: A1 = element['first_influence_matrices'] A2 = element['content_embedding_matrix'] predicted_influence_matrix = A1 * W1.value + A2 * W2.value + B.value model_err += compute_matrix_err( influence_matrix, predicted_influence_matrix) model_err /= len(X_test) random_err /= len(X_test) uniform_err /= len(X_test) model_errs.append(model_err) random_errs.append(random_err) uniform_errs.append(uniform_err) plt.hist(model_errs) plt.hist(random_errs) plt.hist(uniform_errs) plt.legend(['model', 'random', 'uniform']); # plt.legend(['model', 'uniform']) print('random: {} +- {}'.format(np.mean(random_errs), np.std(random_errs))) print('uniform: {} +- {}'.format(np.mean(uniform_errs), np.std(uniform_errs))) print('model: {} +- {}'.format(np.mean(model_errs), np.std(model_errs))); ###Output random: 0.6269796734190237 +- 0.01995421860943538 uniform: 0.33240827017492997 +- 0.02336559677869273 model: 0.3027936262918508 +- 0.015856241631805136
RealDataPractice.ipynb
###Markdown Working with a real world data-set using SQL and Python IntroductionThis notebook shows how to work with a real world dataset using SQL and Python. In this lab you will:1. Understand the dataset for Chicago Public School level performance 1. Store the dataset in an Db2 database on IBM Cloud instance1. Retrieve metadata about tables and columns and query data from mixed case columns1. Solve example problems to practice your SQL skills including using built-in database functions Chicago Public Schools - Progress Report Cards (2011-2012) The city of Chicago released a dataset showing all school level performance data used to create School Report Cards for the 2011-2012 school year. The dataset is available from the Chicago Data Portal: https://data.cityofchicago.org/Education/Chicago-Public-Schools-Progress-Report-Cards-2011-/9xs2-f89tThis dataset includes a large number of metrics. Start by familiarizing yourself with the types of metrics in the database: https://data.cityofchicago.org/api/assets/AAD41A13-BE8A-4E67-B1F5-86E711E09D5F?download=true__NOTE__: Do not download the dataset directly from City of Chicago portal. Instead download a more database friendly version from the link below.Now download a static copy of this database and review some of its contents:https://ibm.box.com/shared/static/f9gjvj1gjmxxzycdhplzt01qtz0s7ew7.csv Store the dataset in a TableIn many cases the dataset to be analyzed is available as a .CSV (comma separated values) file, perhaps on the internet. To analyze the data using SQL, it first needs to be stored in the database.While it is easier to read the dataset into a Pandas dataframe and then PERSIST it into the database as we saw in the previous lab, it results in mapping to default datatypes which may not be optimal for SQL querying. For example a long textual field may map to a CLOB instead of a VARCHAR. Now open the Db2 console, open the LOAD tool, Select / Drag the .CSV file for the CHICAGO PUBLIC SCHOOLS dataset and load the dataset into a new table called __SCHOOLS__. Connect to the databaseLet us now load the ipython-sql extension and establish a connection with the database ###Code %load_ext sql # Enter the connection string for your Db2 on Cloud database instance below # %sql ibm_db_sa://my-username:my-password@my-hostname:my-port/my-db-name %sql ibm_db_sa://username:pwd@host:50000/BLUDB ###Output (ibm_db_dbi.ProgrammingError) ibm_db_dbi::ProgrammingError: [IBM][CLI Driver] SQL0438N Application raised error or warning with diagnostic text: "Exceeded maximum limit of 5 connections. Connection refused". SQLSTATE=42502\r SQLCODE=-438 (Background on this error at: http://sqlalche.me/e/f405) Connection info needed in SQLAlchemy format, example: postgresql://username:password@hostname/dbname or an existing connection: dict_keys([]) ###Markdown Query the database system catalog to retrieve table metadata You can verify that the table creation was successful by retrieving the list of all tables in your schema and checking whether the SCHOOLS table was created ###Code # type in your query to retrieve list of all tables in the database for your db2 schema (username) %sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES \ where TABSCHEMA not in ('SYSIBM', 'SYSCAT', 'SYSSTAT', 'SYSIBMADM', 'SYSTOOLS', 'SYSPUBLIC') ###Output Environment variable $DATABASE_URL not set, and no connect string given. Connection info needed in SQLAlchemy format, example: postgresql://username:password@hostname/dbname or an existing connection: dict_keys([]) ###Markdown Double-click __here__ for a hint<!--In Db2 the system catalog table called SYSCAT.TABLES contains the table metadata--> Double-click __here__ for the solution.<!-- Solution:%sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES where TABSCHEMA='YOUR-DB2-USERNAME'or, you can retrieve list of all tables where the schema name is not one of the system created ones:%sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES \ where TABSCHEMA not in ('SYSIBM', 'SYSCAT', 'SYSSTAT', 'SYSIBMADM', 'SYSTOOLS', 'SYSPUBLIC') or, just query for a specifc table that you want to verify exists in the database%sql select * from SYSCAT.TABLES where TABNAME = 'SCHOOLS'--> Query the database system catalog to retrieve column metadata The SCHOOLS table contains a large number of columns. How many columns does this table have? ###Code # type in your query to retrieve the number of columns in the SCHOOLS table %sql SELECT COUNT(*) FROM syscat.columns WHERE tabname = 'SCHOOLS' ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--In Db2 the system catalog table called SYSCAT.COLUMNS contains the column metadata--> Double-click __here__ for the solution.<!-- Solution:%sql select count(*) from SYSCAT.COLUMNS where TABNAME = 'SCHOOLS'--> Now retrieve the the list of columns in SCHOOLS table and their column type (datatype) and length. ###Code # type in your query to retrieve all column names in the SCHOOLS table along with their datatypes and length %sql select COLNAME, TYPENAME, LENGTH from SYSCAT.COLUMNS where TABNAME = 'SCHOOLS' ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for the solution.<!-- Solution:%sql select COLNAME, TYPENAME, LENGTH from SYSCAT.COLUMNS where TABNAME = 'SCHOOLS'or%sql select distinct(NAME), COLTYPE, LENGTH from SYSIBM.SYSCOLUMNS where TBNAME = 'SCHOOLS'--> Questions1. Is the column name for the "SCHOOL ID" attribute in upper or mixed case?1. What is the name of "Community Area Name" column in your table? Does it have spaces?1. Are there any columns in whose names the spaces and paranthesis (round brackets) have been replaced by the underscore character "_"? Problems Problem 1 How many Elementary Schools are in the dataset? ###Code %sql select count(*) from SCHOOLS where "Elementary, Middle, or High School" = 'ES' ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--Which column specifies the school type e.g. 'ES', 'MS', 'HS'?--> Double-click __here__ for another hint<!--Does the column name have mixed case, spaces or other special characters?If so, ensure you use double quotes around the "Name of the Column"--> Double-click __here__ for the solution.<!-- Solution:%sql select count(*) from SCHOOLS where "Elementary, Middle, or High School" = 'ES'Correct answer: 462--> Problem 2 What is the highest Safety Score? ###Code %sql select max(SAFETY_SCORE) from SCHOOLS ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--Use the MAX() function--> Double-click __here__ for the solution.<!-- Hint:%sql select MAX(Safety_Score) AS MAX_SAFETY_SCORE from SCHOOLSCorrect answer: 99--> Problem 3 Which schools have highest Safety Score? ###Code %sql select NAME_OF_SCHOOL, SAFETY_SCORE from SCHOOLS\ where SAFETY_SCORE = (select max(SAFETY_SCORE) from SCHOOLS) ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for the solution.<!-- Solution:In the previous problem we found out that the highest Safety Score is 99, so we can use that as an input in the where clause:%sql select Name_of_School, Safety_Score from SCHOOLS where Safety_Score = 99or, a better way:%sql select Name_of_School, Safety_Score from SCHOOLS where \ Safety_Score= (select MAX(Safety_Score) from SCHOOLS)Correct answer: several schools with with Safety Score of 99.--> Problem 4 What are the top 10 schools with the highest "Average Student Attendance"? ###Code %sql select NAME_OF_SCHOOL, AVERAGE_STUDENT_ATTENDANCE from SCHOOLS order by AVERAGE_STUDENT_ATTENDANCE desc nulls last limit 10; ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for the solution.<!-- Solution:%sql select Name_of_School, Average_Student_Attendance from SCHOOLS \ order by Average_Student_Attendance desc nulls last limit 10 --> Problem 5 Retrieve the list of 5 Schools with the lowest Average Student Attendance sorted in ascending order based on attendance ###Code %sql select NAME_OF_SCHOOL, AVERAGE_STUDENT_ATTENDANCE from SCHOOLS\ order by AVERAGE_STUDENT_ATTENDANCE limit 5; ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for the solution.<!-- Solution:%sql SELECT Name_of_School, Average_Student_Attendance \ from SCHOOLS \ order by Average_Student_Attendance \ fetch first 5 rows only--> Problem 6 Now remove the '%' sign from the above result set for Average Student Attendance column ###Code %sql select NAME_OF_SCHOOL, replace(AVERAGE_STUDENT_ATTENDANCE, '%', '')\ from SCHOOLS order by AVERAGE_STUDENT_ATTENDANCE fetch first 5 rows only ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--Use the REPLACE() function to replace '%' with ''See documentation for this function at:https://www.ibm.com/support/knowledgecenter/en/SSEPGG_10.5.0/com.ibm.db2.luw.sql.ref.doc/doc/r0000843.html--> Double-click __here__ for the solution.<!-- Hint:%sql SELECT Name_of_School, REPLACE(Average_Student_Attendance, '%', '') \ from SCHOOLS \ order by Average_Student_Attendance \ fetch first 5 rows only--> Problem 7 Which Schools have Average Student Attendance lower than 70%? ###Code %sql select NAME_OF_SCHOOL, AVERAGE_STUDENT_ATTENDANCE from SCHOOLS\ where decimal(replace(AVERAGE_STUDENT_ATTENDANCE, '%','')) <70 ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--The datatype of the "Average_Student_Attendance" column is varchar.So you cannot use it as is in the where clause for a numeric comparison.First use the CAST() function to cast it as a DECIMAL or DOUBLEe.g. CAST("Column_Name" as DOUBLE)or simply: DECIMAL("Column_Name")--> Double-click __here__ for another hint<!--Don't forget the '%' age sign needs to be removed before casting--> Double-click __here__ for the solution.<!-- Solution:%sql SELECT Name_of_School, Average_Student_Attendance \ from SCHOOLS \ where CAST ( REPLACE(Average_Student_Attendance, '%', '') AS DOUBLE ) < 70 \ order by Average_Student_Attendance or,%sql SELECT Name_of_School, Average_Student_Attendance \ from SCHOOLS \ where DECIMAL ( REPLACE(Average_Student_Attendance, '%', '') ) < 70 \ order by Average_Student_Attendance--> Problem 8 Get the total College Enrollment for each Community Area ###Code %sql select Community_Area_Name, sum(College_Enrollment) AS TOTAL_ENROLLMENT \ from SCHOOLS \ group by Community_Area_Name ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done. ###Markdown Double-click __here__ for a hint<!--Verify the exact name of the Enrollment column in the databaseUse the SUM() function to add up the Enrollments for each Community Area--> Double-click __here__ for another hint<!--Don't forget to group by the Community Area--> Double-click __here__ for the solution.<!-- Solution:%sql select Community_Area_Name, sum(College_Enrollment) AS TOTAL_ENROLLMENT \ from SCHOOLS \ group by Community_Area_Name --> Problem 9 Get the 5 Community Areas with the least total College Enrollment sorted in ascending order ###Code %sql select Community_Area_Name, sum(College_Enrollment) AS TOTAL_ENROLLMENT \ from SCHOOLS \ group by Community_Area_Name \ order by TOTAL_ENROLLMENT asc \ fetch first 5 rows only ###Output * ibm_db_sa://clk37870:***@dashdb-txn-sbox-yp-lon02-01.services.eu-gb.bluemix.net:50000/BLUDB Done.
exercise/chap_6/7_dt_moons.ipynb
###Markdown Important Points* Created using make_moons function in sklean a synthetic dataset* Applied GridSearchCV with params max_leaf_nodes and max_depth| Model | Training | Validation ||--------------|--------------|-------------|| Decison Tree | 86.28% | 85.68% | ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt np.random.seed(42) %matplotlib inline # Creating data and train-test split from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split x, y = make_moons(n_samples=10000, noise=0.4, random_state=True) x_train, x_valid, y_train, y_valid = train_test_split(x, y, random_state=42, test_size=0.25) print(x_train.shape, y_train.shape) print(x_valid.shape, y_valid.shape) # No of classes np.unique(y_train) from sklearn.metrics import accuracy_score def score(y, y_pred, train=False): if train: print("Training accuracy: ", accuracy_score(y, y_pred)) else: print("Validation accuracy: ", accuracy_score(y, y_pred)) from sklearn.tree import DecisionTreeClassifier dt = DecisionTreeClassifier() dt.fit(x_train, y_train) # The model overfits since no regularization had been applied score(y_valid, dt.predict(x_valid)) score(y_train, dt.predict(x_train), True) from sklearn.model_selection import GridSearchCV params = {"max_leaf_nodes": list(range(2, 50)), "max_depth": list(range(8, 12))} grid_search = GridSearchCV(DecisionTreeClassifier(random_state=42), verbose=1, param_grid=params, cv=3) %time grid_search.fit(x_train, y_train) grid_search.best_estimator_ # Since refit=True, model already trained on complete x_train score(y_train, grid_search.predict(x_train), True) # Validation score score(y_valid, grid_search.predict(x_valid)) ###Output Training accuracy: 0.8628 Validation accuracy: 0.8568
src/databricks/notebooks/traffic-camera-speeddetection.py.ipynb
###Markdown Load variables from key vault ###Code kv_scope = 'key-vault-secret' # Variables storage_account_name = dbutils.secrets.get(scope=kv_scope, key='traffic-storage-accountname') storage_account_access_key = dbutils.secrets.get(scope=kv_scope, key='traffic-storage-accountkey') eventgrid_accesskey = dbutils.secrets.get(scope=kv_scope, key='traffic-eventgrid-accesskey') eventgrid_topic = dbutils.secrets.get(scope=kv_scope, key='traffic-eventgrid-topicendpoint') ###Output _____no_output_____ ###Markdown Mounting the segment configuration json from blob- Using the mount functionality to load the blob file ###Code mount_name = 'traffic-config' to_be_mounted = True mounts = dbutils.fs.ls('/mnt/') for mnt in mounts: if mnt.name.startswith(mount_name): to_be_mounted = False if to_be_mounted: dbutils.fs.mount( source = 'wasbs://traffic-config@' + storage_account_name + '.blob.core.windows.net', mount_point = '/mnt/' + mount_name, extra_configs = {'fs.azure.account.key.' + storage_account_name + '.blob.core.windows.net':storage_account_access_key}) else: print('Traffic config already mounted') ###Output _____no_output_____ ###Markdown Parsing segment configuration- Reading the json file (`multiLine=True` !!)- Adding calculated field for maximum duration (`(distance / speedlimit) * 3.6`), where 3.6 is coming from meters/second- Only returning the relevant fields for the calculation query ###Code segment_config = spark.read.json('/mnt/' + mount_name, multiLine=True) \ .withColumn('TrajectId', col('segmentId')) \ .withColumn('MinDuration', ((col('cameraDistance') / col('speedLimit')) * 3.6)) \ .select('TrajectId', 'MinDuration', 'CameraDistance', 'SpeedLimit') \ display(segment_config) timestamp_from = datetime.utcnow() - timedelta(hours=0, minutes=20) delta_src_table_name = 'CameraTelemetry' + datetime.today().strftime('%Y%m%d') delta_dest_table_name = 'SpeedMeasurements' + datetime.today().strftime('%Y%m%d') cameraStream = spark.readStream.format('delta') \ .table(delta_src_table_name) \ .withWatermark('EventTime', '10 seconds') ###Output _____no_output_____ ###Markdown Query that measures time difference per licenseplate- Loading data from the delta table- Grouping by license plate and traject- Taking count, earliest timestamp and latest timestamp- Adding calculated field (max-min) for duration- Selecting relevant fields as output ###Code duration_calculation = cameraStream \ .groupBy('TrajectId', 'LicensePlate', 'Make', 'Country') \ .agg(count('*').alias('count'), min('EventTime').alias('firstevent'), max('EventTime').alias('lastevent')) \ .withColumn('duration', col('lastevent').cast(LongType())-col('firstevent').cast(LongType())) \ .where((col('duration') > 0) & (col('count') >= 2)) \ .select('TrajectId','LicensePlate', 'Make', 'Country', 'FirstEvent', 'LastEvent', 'Count', 'Duration') ###Output _____no_output_____ ###Markdown Join results with traject information and detect speeding cars- Join on TrajectId- Select cars with duration that is below the minimum duration of the traject- Add a calculated column for speed ###Code speed_measurements_df = duration_calculation.join(segment_config, 'TrajectId') \ .withColumn('speed', ((col('CameraDistance') / col('duration')) * 3.6)) \ .select('TrajectId', 'LicensePlate', 'Speed', 'Make', 'Country', 'LastEvent', 'SpeedLimit', 'Duration') \ .withWatermark('LastEvent', '5 seconds') \ .writeStream \ .format('delta') \ .outputMode('complete') \ .option('checkpointLocation', '/data/' + delta_dest_table_name + 'cp/_checkpoints/data_file') \ .table(delta_dest_table_name) speed_tickets_df = duration_calculation.join(segment_config, 'TrajectId') \ .withColumn('Subject', concat(col('TrajectId'), lit('/'), col('LicensePlate'))) \ .withColumn('speed', ((col('CameraDistance') / col('duration')) * 3.6)) \ .where(col('duration') < col('MinDuration')) \ .select('TrajectId', 'LicensePlate', 'Speed', 'Duration', 'Subject', 'SpeedLimit') \ .writeStream.foreach(eg.EventGridSinkWriter(eventgrid_topic, eventgrid_accesskey, 'SpeedingCarDetected')) \ .outputMode('update') \ .start() #dbutils.fs.unmount('/mnt/' + mount_name) ###Output _____no_output_____
CS224W_Colab1.ipynb
###Markdown **CS224W - Colab 1** In this Colab, we will write a full pipeline for **learning node embeddings**.We will go through the following 3 steps.To start, we will load a classic graph in network science, the [Karate Club Network](https://en.wikipedia.org/wiki/Zachary%27s_karate_club). We will explore multiple graph statistics for that graph.We will then work together to transform the graph structure into a PyTorch tensor, so that we can perform machine learning over the graph.Finally, we will finish the first learning algorithm on graphs: a node embedding model. For simplicity, our model here is simpler than DeepWalk / node2vec algorithms taught in the lecture. But it's still rewarding and challenging, as we will write it from scratch via PyTorch.Now let's get started!**Note**: Make sure to **sequentially run all the cells**, so that the intermediate variables / packages will carry over to the next cell 1 Graph BasicsTo start, we will load a classic graph in network science, the [Karate Club Network](https://en.wikipedia.org/wiki/Zachary%27s_karate_club). We will explore multiple graph statistics for that graph. SetupWe will heavily use NetworkX in this Colab. ###Code import networkx as nx ###Output _____no_output_____ ###Markdown Zachary's karate club networkThe [Karate Club Network](https://en.wikipedia.org/wiki/Zachary%27s_karate_club) is a graph describes a social network of 34 members of a karate club and documents links between members who interacted outside the club. ###Code G = nx.karate_club_graph() # G is an undirected graph type(G) # Visualize the graph nx.draw(G, with_labels = True) ###Output _____no_output_____ ###Markdown Question 1: What is the average degree of the karate club network? (5 Points) ###Code def average_degree(num_edges, num_nodes): # TODO: Implement this function that takes number of edges # and number of nodes, and returns the average node degree of # the graph. Round the result to nearest integer (for example # 3.3 will be rounded to 3 and 3.7 will be rounded to 4) avg_degree = 0 ############# Your code here ############ avg_degree = round(2 * num_edges / num_nodes) ######################################### return avg_degree num_edges = G.number_of_edges() num_nodes = G.number_of_nodes() avg_degree = average_degree(num_edges, num_nodes) print("Average degree of karate club network is {}".format(avg_degree)) ###Output Average degree of karate club network is 5 ###Markdown Question 2: What is the average clustering coefficient of the karate club network? (5 Points) ###Code def average_clustering_coefficient(G): # TODO: Implement this function that takes a nx.Graph # and returns the average clustering coefficient. Round # the result to 2 decimal places (for example 3.333 will # be rounded to 3.33 and 3.7571 will be rounded to 3.76) avg_cluster_coef = 0 ############# Your code here ############ ## Note: ## 1: Please use the appropriate NetworkX clustering function avg_cluster_coef = round(nx.average_clustering(G), 2) ######################################### return avg_cluster_coef avg_cluster_coef = average_clustering_coefficient(G) print("Average clustering coefficient of karate club network is {}".format(avg_cluster_coef)) ###Output Average clustering coefficient of karate club network is 0.57 ###Markdown Question 3: What is the PageRank value for node 0 (node with id 0) after one PageRank iteration? (5 Points)Please complete the code block by implementing the PageRank equation: $r_j = \sum_{i \rightarrow j} \beta \frac{r_i}{d_i} + (1 - \beta) \frac{1}{N}$ ###Code def one_iter_pagerank(G, beta, r0, node_id): # TODO: Implement this function that takes a nx.Graph, beta, r0 and node id. # The return value r1 is one interation PageRank value for the input node. # Please round r1 to 2 decimal places. r1 = 0 ############# Your code here ############ ## Note: ## 1: You should not use nx.pagerank for neighbor in G.neighbors(node_id): r1 += beta * r0 / G.degree[neighbor] r1 += (1 - beta) / G.number_of_nodes() r1 = round(r1, 2) ######################################### return r1 beta = 0.8 r0 = 1 / G.number_of_nodes() node = 0 r1 = one_iter_pagerank(G, beta, r0, node) print("The PageRank value for node 0 after one iteration is {}".format(r1)) ###Output The PageRank value for node 0 after one iteration is 0.13 ###Markdown Question 4: What is the (raw) closeness centrality for the karate club network node 5? (5 Points)The equation for closeness centrality is $c(v) = \frac{1}{\sum_{u \neq v}\text{shortest path length between } u \text{ and } v}$ ###Code def closeness_centrality(G, node=5): # TODO: Implement the function that calculates closeness centrality # for a node in karate club network. G is the input karate club # network and node is the node id in the graph. Please round the # closeness centrality result to 2 decimal places. closeness = 0 ## Note: ## 1: You can use networkx closeness centrality function. ## 2: Notice that networkx closeness centrality returns the normalized ## closeness directly, which is different from the raw (unnormalized) ## one that we learned in the lecture. normalized_closeness = nx.closeness_centrality(G, u=node) closeness = normalized_closeness / (len(nx.node_connected_component(G, node)) - 1) closeness = round(closeness, 2) ######################################### return closeness node = 5 closeness = closeness_centrality(G, node=node) print("The node 5 has closeness centrality {}".format(closeness)) ###Output The node 5 has closeness centrality 0.01 ###Markdown 2 Graph to TensorWe will then work together to transform the graph $G$ into a PyTorch tensor, so that we can perform machine learning over the graph. SetupCheck if PyTorch is properly installed ###Code import torch print(torch.__version__) ###Output 1.10.0+cu111 ###Markdown PyTorch tensor basicsWe can generate PyTorch tensor with all zeros, ones or random values. ###Code # Generate 3 x 4 tensor with all ones ones = torch.ones(3, 4) print(ones) # Generate 3 x 4 tensor with all zeros zeros = torch.zeros(3, 4) print(zeros) # Generate 3 x 4 tensor with random values on the interval [0, 1) random_tensor = torch.rand(3, 4) print(random_tensor) # Get the shape of the tensor print(ones.shape) ###Output tensor([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]) tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) tensor([[0.6379, 0.4626, 0.4569, 0.9950], [0.4649, 0.5162, 0.2455, 0.5794], [0.2019, 0.4957, 0.6122, 0.1658]]) torch.Size([3, 4]) ###Markdown PyTorch tensor contains elements for a single data type, the `dtype`. ###Code # Create a 3 x 4 tensor with all 32-bit floating point zeros zeros = torch.zeros(3, 4, dtype=torch.float32) print(zeros.dtype) # Change the tensor dtype to 64-bit integer zeros = zeros.type(torch.long) print(zeros.dtype) ###Output torch.float32 torch.int64 ###Markdown Question 5: Get the edge list of the karate club network and transform it into `torch.LongTensor`. What is the `torch.sum` value of `pos_edge_index` tensor? (10 Points) ###Code def graph_to_edge_list(G): # TODO: Implement the function that returns the edge list of # an nx.Graph. The returned edge_list should be a list of tuples # where each tuple is a tuple representing an edge connected # by two nodes. edge_list = [] ############# Your code here ############ edge_list = list(list(G.edges())) ######################################### return edge_list def edge_list_to_tensor(edge_list): # TODO: Implement the function that transforms the edge_list to # tensor. The input edge_list is a list of tuples and the resulting # tensor should have the shape [2 x len(edge_list)]. edge_index = torch.tensor([]) ############# Your code here ############ edge_index = torch.tensor(edge_list).T ######################################### return edge_index pos_edge_list = graph_to_edge_list(G) pos_edge_index = edge_list_to_tensor(pos_edge_list) print("The pos_edge_index tensor has shape {}".format(pos_edge_index.shape)) print("The pos_edge_index tensor has sum value {}".format(torch.sum(pos_edge_index))) ###Output The pos_edge_index tensor has shape torch.Size([2, 78]) The pos_edge_index tensor has sum value 2535 ###Markdown Question 6: Please implement following function that samples negative edges. Then answer which edges (edge_1 to edge_5) can be potential negative edges in the karate club network? (10 Points) ###Code import random def sample_negative_edges(G, num_neg_samples): # TODO: Implement the function that returns a list of negative edges. # The number of sampled negative edges is num_neg_samples. You do not # need to consider the corner case when the number of possible negative edges # is less than num_neg_samples. It should be ok as long as your implementation # works on the karate club network. In this implementation, self loops should # not be considered as either a positive or negative edge. Also, notice that # the karate club network is an undirected graph, if (0, 1) is a positive # edge, do you think (1, 0) can be a negative one? neg_edge_list = [] ############# Your code here ############ pos_set = set(G.edges()) visited_set = set() node_list = list(G.nodes()) random.shuffle(node_list) for n_i in node_list: for n_j in node_list: if n_i == n_j \ or (n_i,n_j) in pos_set or (n_j,n_i) in pos_set \ or (n_i,n_j) in visited_set or (n_j, n_i) is visited_set: continue neg_edge_list.append((n_i,n_j)) visited_set.add((n_i,n_j)) visited_set.add((n_j,n_i)) if len(neg_edge_list) == num_neg_samples: return neg_edge_list ######################################### return neg_edge_list # Sample 78 negative edges neg_edge_list = sample_negative_edges(G, len(pos_edge_list)) # Transform the negative edge list to tensor neg_edge_index = edge_list_to_tensor(neg_edge_list) print("The neg_edge_index tensor has shape {}".format(neg_edge_index.shape)) # Which of following edges can be negative ones? edge_1 = (7, 1) edge_2 = (1, 33) edge_3 = (33, 22) edge_4 = (0, 4) edge_5 = (4, 2) ############# Your code here ############ ## Note: ## 1: For each of the 5 edges, print whether it can be negative edge def is_neg_edge(edge): return not(edge in pos_edge_list or (edge[1], edge[0]) in pos_edge_list) print(is_neg_edge(edge_1)) print(is_neg_edge(edge_2)) print(is_neg_edge(edge_3)) print(is_neg_edge(edge_4)) print(is_neg_edge(edge_5)) ######################################### ###Output The neg_edge_index tensor has shape torch.Size([2, 78]) False True False False True ###Markdown 3 Node Emebedding LearningFinally, we will finish the first learning algorithm on graphs: a node embedding model. Setup ###Code import torch import torch.nn as nn import matplotlib.pyplot as plt from sklearn.decomposition import PCA print(torch.__version__) ###Output 1.10.0+cu111 ###Markdown To write our own node embedding learning methods, we'll heavily use the [`nn.Embedding`](https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html) module in PyTorch. Let's see how to use `nn.Embedding`: ###Code # Initialize an embedding layer # Suppose we want to have embedding for 4 items (e.g., nodes) # Each item is represented with 8 dimensional vector emb_sample = nn.Embedding(num_embeddings=4, embedding_dim=8) print('Sample embedding layer: {}'.format(emb_sample)) ###Output Sample embedding layer: Embedding(4, 8) ###Markdown We can select items from the embedding matrix, by using Tensor indices ###Code # Select an embedding in emb_sample id = torch.LongTensor([1]) print(emb_sample(id)) # Select multiple embeddings ids = torch.LongTensor([1, 3]) print(emb_sample(ids)) # Get the shape of the embedding weight matrix shape = emb_sample.weight.data.shape print(shape) # Overwrite the weight to tensor with all ones emb_sample.weight.data = torch.ones(shape) # Let's check if the emb is indeed initilized ids = torch.LongTensor([0, 3]) print(emb_sample(ids)) ###Output tensor([[ 0.6998, 0.2015, -0.2159, 0.3704, -0.0126, 2.8423, -0.4166, -0.2715]], grad_fn=<EmbeddingBackward0>) tensor([[ 0.6998, 0.2015, -0.2159, 0.3704, -0.0126, 2.8423, -0.4166, -0.2715], [-1.7620, 0.4619, -1.7589, -0.1419, -1.0391, 0.5771, 0.7422, -0.4567]], grad_fn=<EmbeddingBackward0>) torch.Size([4, 8]) tensor([[1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1.]], grad_fn=<EmbeddingBackward0>) ###Markdown Now, it's your time to create node embedding matrix for the graph we have!- We want to have **16 dimensional** vector for each node in the karate club network.- We want to initalize the matrix under **uniform distribution**, in the range of $[0, 1)$. We suggest you using [`torch.rand`](https://pytorch.org/docs/stable/generated/torch.rand.html). ###Code # Please do not change / reset the random seed torch.manual_seed(1) def create_node_emb(num_node=34, embedding_dim=16): # TODO: Implement this function that will create the node embedding matrix. # A torch.nn.Embedding layer will be returned. You do not need to change # the values of num_node and embedding_dim. The weight matrix of returned # layer should be initialized under uniform distribution. emb = None ############# Your code here ############ emb = nn.Embedding(num_nodes, embedding_dim) emb.weight.data = torch.rand(num_nodes, embedding_dim) ######################################### return emb emb = create_node_emb() ids = torch.LongTensor([0, 3]) # Print the embedding layer print("Embedding: {}".format(emb)) # An example that gets the embeddings for node 0 and 3 print(emb(ids)) ###Output Embedding: Embedding(34, 16) tensor([[0.2114, 0.7335, 0.1433, 0.9647, 0.2933, 0.7951, 0.5170, 0.2801, 0.8339, 0.1185, 0.2355, 0.5599, 0.8966, 0.2858, 0.1955, 0.1808], [0.7486, 0.6546, 0.3843, 0.9820, 0.6012, 0.3710, 0.4929, 0.9915, 0.8358, 0.4629, 0.9902, 0.7196, 0.2338, 0.0450, 0.7906, 0.9689]], grad_fn=<EmbeddingBackward0>) ###Markdown Visualize the initial node embeddingsOne good way to understand an embedding matrix, is to visualize it in a 2D space.Here, we have implemented an embedding visualization function for you.We first do PCA to reduce the dimensionality of embeddings to a 2D space.Then we visualize each point, colored by the community it belongs to. ###Code def visualize_emb(emb): X = emb.weight.data.numpy() pca = PCA(n_components=2) components = pca.fit_transform(X) plt.figure(figsize=(6, 6)) club1_x = [] club1_y = [] club2_x = [] club2_y = [] for node in G.nodes(data=True): if node[1]['club'] == 'Mr. Hi': club1_x.append(components[node[0]][0]) club1_y.append(components[node[0]][1]) else: club2_x.append(components[node[0]][0]) club2_y.append(components[node[0]][1]) plt.scatter(club1_x, club1_y, color="red", label="Mr. Hi") plt.scatter(club2_x, club2_y, color="blue", label="Officer") plt.legend() plt.show() # Visualize the initial random embeddding visualize_emb(emb) ###Output _____no_output_____ ###Markdown Question 7: Training the embedding! What is the best performance you can get? Please report both the best loss and accuracy on Gradescope. (20 Points)We want to optimize our embeddings for the task of classifying edges as positive or negative. Given an edge and the embeddings for each node, the dot product of the embeddings, followed by a sigmoid, should give us the likelihood of that edge being either positive (output of sigmoid > 0.5) or negative (output of sigmoid < 0.5).Note that we're using the functions you wrote in the previous questions, _as well as the variables initialized in previous cells_. If you're running into issues, make sure your answers to questions 1-6 are correct. ###Code from torch.optim import SGD import torch.nn as nn import numpy as np def accuracy(pred, label): # TODO: Implement the accuracy function. This function takes the # pred tensor (the resulting tensor after sigmoid) and the label # tensor (torch.LongTensor). Predicted value greater than 0.5 will # be classified as label 1. Else it will be classified as label 0. # The returned accuracy should be rounded to 4 decimal places. # For example, accuracy 0.82956 will be rounded to 0.8296. accu = 0.0 ############# Your code here ############ pred = [1 if item>0.5 else 0 for item in pred] num_match = (np.array(pred) == np.array(train_label)).sum() accu = num_match / len(train_label) accu = round(accu, 4) ######################################### return accu def train(emb, loss_fn, sigmoid, train_label, train_edge): # TODO: Train the embedding layer here. You can also change epochs and # learning rate. In general, you need to implement: # (1) Get the embeddings of the nodes in train_edge # (2) Dot product the embeddings between each node pair # (3) Feed the dot product result into sigmoid # (4) Feed the sigmoid output into the loss_fn # (5) Print both loss and accuracy of each epoch # (6) Update the embeddings using the loss and optimizer # (as a sanity check, the loss should decrease during training) epochs = 500 learning_rate = 0.1 optimizer = SGD(emb.parameters(), lr=learning_rate, momentum=0.9) for i in range(epochs): ############# Your code here ############ optimizer.zero_grad() # (1) Get the embeddings of the nodes in train_edge emb_set_u = emb(train_edge[0]) emb_set_v = emb(train_edge[1]) # (2) Dot product the embeddings between each node pair dot_prod = torch.sum(emb_set_u * emb_set_v, dim=-1) # (3) Feed the dot product result into sigmoid sig = sigmoid(dot_prod) # (4) Feed the sigmoid output into the loss_fn loss = loss_fn(sig, train_label) loss.backward() # Derive gradients. optimizer.step() # Update parameters based on gradients. print(f"Loss for Epoch {i}: {loss}") print(f"Accuracy for is Epoch {i}: {accuracy(sig, train_label)}") print() ######################################### loss_fn = nn.BCELoss() sigmoid = nn.Sigmoid() print(pos_edge_index.shape) # Generate the positive and negative labels pos_label = torch.ones(pos_edge_index.shape[1], ) neg_label = torch.zeros(neg_edge_index.shape[1], ) # Concat positive and negative labels into one tensor train_label = torch.cat([pos_label, neg_label], dim=0) # Concat positive and negative edges into one tensor # Since the network is very small, we do not split the edges into val/test sets train_edge = torch.cat([pos_edge_index, neg_edge_index], dim=1) print(train_edge.shape) train(emb, loss_fn, sigmoid, train_label, train_edge) ###Output torch.Size([2, 78]) torch.Size([2, 156]) Loss for Epoch 0: 2.25661301612854 Accuracy for is Epoch 0: 0.5 Loss for Epoch 1: 2.2170355319976807 Accuracy for is Epoch 1: 0.5 Loss for Epoch 2: 2.1426429748535156 Accuracy for is Epoch 2: 0.5 Loss for Epoch 3: 2.038400411605835 Accuracy for is Epoch 3: 0.5 Loss for Epoch 4: 1.9093924760818481 Accuracy for is Epoch 4: 0.5 Loss for Epoch 5: 1.7607818841934204 Accuracy for is Epoch 5: 0.5 Loss for Epoch 6: 1.5978357791900635 Accuracy for is Epoch 6: 0.5 Loss for Epoch 7: 1.4259817600250244 Accuracy for is Epoch 7: 0.5 Loss for Epoch 8: 1.2508485317230225 Accuracy for is Epoch 8: 0.5 Loss for Epoch 9: 1.0782299041748047 Accuracy for is Epoch 9: 0.5 Loss for Epoch 10: 0.9139243960380554 Accuracy for is Epoch 10: 0.5 Loss for Epoch 11: 0.763421893119812 Accuracy for is Epoch 11: 0.5192 Loss for Epoch 12: 0.631392776966095 Accuracy for is Epoch 12: 0.5705 Loss for Epoch 13: 0.521044909954071 Accuracy for is Epoch 13: 0.6474 Loss for Epoch 14: 0.4336003065109253 Accuracy for is Epoch 14: 0.6987 Loss for Epoch 15: 0.36819779872894287 Accuracy for is Epoch 15: 0.8077 Loss for Epoch 16: 0.32231464982032776 Accuracy for is Epoch 16: 0.8654 Loss for Epoch 17: 0.2925078570842743 Accuracy for is Epoch 17: 0.9167 Loss for Epoch 18: 0.27514827251434326 Accuracy for is Epoch 18: 0.9103 Loss for Epoch 19: 0.26692166924476624 Accuracy for is Epoch 19: 0.9103 Loss for Epoch 20: 0.2650585174560547 Accuracy for is Epoch 20: 0.9038 Loss for Epoch 21: 0.26737043261528015 Accuracy for is Epoch 21: 0.8974 Loss for Epoch 22: 0.2721913754940033 Accuracy for is Epoch 22: 0.8974 Loss for Epoch 23: 0.27828744053840637 Accuracy for is Epoch 23: 0.8974 Loss for Epoch 24: 0.28476765751838684 Accuracy for is Epoch 24: 0.8974 Loss for Epoch 25: 0.29100707173347473 Accuracy for is Epoch 25: 0.8974 Loss for Epoch 26: 0.2965843379497528 Accuracy for is Epoch 26: 0.8974 Loss for Epoch 27: 0.3012319803237915 Accuracy for is Epoch 27: 0.8974 Loss for Epoch 28: 0.30479806661605835 Accuracy for is Epoch 28: 0.8974 Loss for Epoch 29: 0.3072158992290497 Accuracy for is Epoch 29: 0.8974 Loss for Epoch 30: 0.30848127603530884 Accuracy for is Epoch 30: 0.8974 Loss for Epoch 31: 0.308634877204895 Accuracy for is Epoch 31: 0.8974 Loss for Epoch 32: 0.3077490031719208 Accuracy for is Epoch 32: 0.8974 Loss for Epoch 33: 0.30591732263565063 Accuracy for is Epoch 33: 0.8974 Loss for Epoch 34: 0.3032471537590027 Accuracy for is Epoch 34: 0.8974 Loss for Epoch 35: 0.29985353350639343 Accuracy for is Epoch 35: 0.8974 Loss for Epoch 36: 0.2958546280860901 Accuracy for is Epoch 36: 0.8974 Loss for Epoch 37: 0.2913680970668793 Accuracy for is Epoch 37: 0.8974 Loss for Epoch 38: 0.28650835156440735 Accuracy for is Epoch 38: 0.8974 Loss for Epoch 39: 0.28138408064842224 Accuracy for is Epoch 39: 0.8974 Loss for Epoch 40: 0.2760966718196869 Accuracy for is Epoch 40: 0.8974 Loss for Epoch 41: 0.2707386910915375 Accuracy for is Epoch 41: 0.8974 Loss for Epoch 42: 0.265392929315567 Accuracy for is Epoch 42: 0.8974 Loss for Epoch 43: 0.26013126969337463 Accuracy for is Epoch 43: 0.8974 Loss for Epoch 44: 0.25501468777656555 Accuracy for is Epoch 44: 0.8974 Loss for Epoch 45: 0.2500925362110138 Accuracy for is Epoch 45: 0.8974 Loss for Epoch 46: 0.24540305137634277 Accuracy for is Epoch 46: 0.8974 Loss for Epoch 47: 0.24097339808940887 Accuracy for is Epoch 47: 0.8974 Loss for Epoch 48: 0.23682045936584473 Accuracy for is Epoch 48: 0.9038 Loss for Epoch 49: 0.23295140266418457 Accuracy for is Epoch 49: 0.9103 Loss for Epoch 50: 0.22936496138572693 Accuracy for is Epoch 50: 0.9103 Loss for Epoch 51: 0.226052388548851 Accuracy for is Epoch 51: 0.9103 Loss for Epoch 52: 0.22299876809120178 Accuracy for is Epoch 52: 0.9103 Loss for Epoch 53: 0.22018428146839142 Accuracy for is Epoch 53: 0.9103 Loss for Epoch 54: 0.2175855189561844 Accuracy for is Epoch 54: 0.9231 Loss for Epoch 55: 0.21517665684223175 Accuracy for is Epoch 55: 0.9231 Loss for Epoch 56: 0.212930828332901 Accuracy for is Epoch 56: 0.9231 Loss for Epoch 57: 0.21082088351249695 Accuracy for is Epoch 57: 0.9295 Loss for Epoch 58: 0.20882073044776917 Accuracy for is Epoch 58: 0.9295 Loss for Epoch 59: 0.20690567791461945 Accuracy for is Epoch 59: 0.9359 Loss for Epoch 60: 0.2050534039735794 Accuracy for is Epoch 60: 0.9359 Loss for Epoch 61: 0.2032441347837448 Accuracy for is Epoch 61: 0.9359 Loss for Epoch 62: 0.201461061835289 Accuracy for is Epoch 62: 0.9359 Loss for Epoch 63: 0.19969037175178528 Accuracy for is Epoch 63: 0.9359 Loss for Epoch 64: 0.19792133569717407 Accuracy for is Epoch 64: 0.9359 Loss for Epoch 65: 0.19614599645137787 Accuracy for is Epoch 65: 0.9359 Loss for Epoch 66: 0.19435913860797882 Accuracy for is Epoch 66: 0.9359 Loss for Epoch 67: 0.19255773723125458 Accuracy for is Epoch 67: 0.9359 Loss for Epoch 68: 0.1907408982515335 Accuracy for is Epoch 68: 0.9359 Loss for Epoch 69: 0.18890917301177979 Accuracy for is Epoch 69: 0.9359 Loss for Epoch 70: 0.18706448376178741 Accuracy for is Epoch 70: 0.9359 Loss for Epoch 71: 0.18520960211753845 Accuracy for is Epoch 71: 0.9359 Loss for Epoch 72: 0.18334777653217316 Accuracy for is Epoch 72: 0.9359 Loss for Epoch 73: 0.18148262798786163 Accuracy for is Epoch 73: 0.9359 Loss for Epoch 74: 0.17961779236793518 Accuracy for is Epoch 74: 0.9423 Loss for Epoch 75: 0.1777566820383072 Accuracy for is Epoch 75: 0.9423 Loss for Epoch 76: 0.17590248584747314 Accuracy for is Epoch 76: 0.9423 Loss for Epoch 77: 0.17405793070793152 Accuracy for is Epoch 77: 0.9423 Loss for Epoch 78: 0.17222529649734497 Accuracy for is Epoch 78: 0.9423 Loss for Epoch 79: 0.17040641605854034 Accuracy for is Epoch 79: 0.9423 Loss for Epoch 80: 0.1686026006937027 Accuracy for is Epoch 80: 0.9423 Loss for Epoch 81: 0.16681469976902008 Accuracy for is Epoch 81: 0.9423 Loss for Epoch 82: 0.1650431901216507 Accuracy for is Epoch 82: 0.9423 Loss for Epoch 83: 0.1632881611585617 Accuracy for is Epoch 83: 0.9423 Loss for Epoch 84: 0.16154944896697998 Accuracy for is Epoch 84: 0.9423 Loss for Epoch 85: 0.1598266065120697 Accuracy for is Epoch 85: 0.9423 Loss for Epoch 86: 0.1581190675497055 Accuracy for is Epoch 86: 0.9423 Loss for Epoch 87: 0.15642611682415009 Accuracy for is Epoch 87: 0.9423 Loss for Epoch 88: 0.15474699437618256 Accuracy for is Epoch 88: 0.9423 Loss for Epoch 89: 0.15308091044425964 Accuracy for is Epoch 89: 0.9423 Loss for Epoch 90: 0.15142713487148285 Accuracy for is Epoch 90: 0.9423 Loss for Epoch 91: 0.1497848927974701 Accuracy for is Epoch 91: 0.9487 Loss for Epoch 92: 0.14815357327461243 Accuracy for is Epoch 92: 0.9487 Loss for Epoch 93: 0.14653262495994568 Accuracy for is Epoch 93: 0.9487 Loss for Epoch 94: 0.14492157101631165 Accuracy for is Epoch 94: 0.9487 Loss for Epoch 95: 0.1433200240135193 Accuracy for is Epoch 95: 0.9487 Loss for Epoch 96: 0.1417277455329895 Accuracy for is Epoch 96: 0.9487 Loss for Epoch 97: 0.14014455676078796 Accuracy for is Epoch 97: 0.9679 Loss for Epoch 98: 0.13857032358646393 Accuracy for is Epoch 98: 0.9679 Loss for Epoch 99: 0.13700509071350098 Accuracy for is Epoch 99: 0.9679 Loss for Epoch 100: 0.13544891774654388 Accuracy for is Epoch 100: 0.9679 Loss for Epoch 101: 0.13390189409255981 Accuracy for is Epoch 101: 0.9679 Loss for Epoch 102: 0.1323641836643219 Accuracy for is Epoch 102: 0.9679 Loss for Epoch 103: 0.13083599507808685 Accuracy for is Epoch 103: 0.9679 Loss for Epoch 104: 0.12931756675243378 Accuracy for is Epoch 104: 0.9679 Loss for Epoch 105: 0.12780915200710297 Accuracy for is Epoch 105: 0.9808 Loss for Epoch 106: 0.12631098926067352 Accuracy for is Epoch 106: 0.9808 Loss for Epoch 107: 0.12482333928346634 Accuracy for is Epoch 107: 0.9808 Loss for Epoch 108: 0.12334650009870529 Accuracy for is Epoch 108: 0.9808 Loss for Epoch 109: 0.12188071757555008 Accuracy for is Epoch 109: 0.9808 Loss for Epoch 110: 0.1204262375831604 Accuracy for is Epoch 110: 0.9808 Loss for Epoch 111: 0.11898329108953476 Accuracy for is Epoch 111: 0.9808 Loss for Epoch 112: 0.11755212396383286 Accuracy for is Epoch 112: 0.9808 Loss for Epoch 113: 0.11613290756940842 Accuracy for is Epoch 113: 0.9808 Loss for Epoch 114: 0.11472588032484055 Accuracy for is Epoch 114: 0.9808 Loss for Epoch 115: 0.11333119869232178 Accuracy for is Epoch 115: 0.9808 Loss for Epoch 116: 0.11194900423288345 Accuracy for is Epoch 116: 0.9808 Loss for Epoch 117: 0.1105794906616211 Accuracy for is Epoch 117: 0.9808 Loss for Epoch 118: 0.10922273993492126 Accuracy for is Epoch 118: 0.9808 Loss for Epoch 119: 0.1078789085149765 Accuracy for is Epoch 119: 0.9808 Loss for Epoch 120: 0.10654806345701218 Accuracy for is Epoch 120: 0.9808 Loss for Epoch 121: 0.10523035377264023 Accuracy for is Epoch 121: 0.9808 Loss for Epoch 122: 0.10392585396766663 Accuracy for is Epoch 122: 0.9808 Loss for Epoch 123: 0.10263462364673615 Accuracy for is Epoch 123: 0.9808 Loss for Epoch 124: 0.10135678201913834 Accuracy for is Epoch 124: 0.9808 Loss for Epoch 125: 0.1000923365354538 Accuracy for is Epoch 125: 0.9808 Loss for Epoch 126: 0.09884139895439148 Accuracy for is Epoch 126: 0.9808 Loss for Epoch 127: 0.09760398417711258 Accuracy for is Epoch 127: 0.9808 Loss for Epoch 128: 0.09638015925884247 Accuracy for is Epoch 128: 0.9808 Loss for Epoch 129: 0.09516997635364532 Accuracy for is Epoch 129: 0.9808 Loss for Epoch 130: 0.09397348016500473 Accuracy for is Epoch 130: 0.9808 Loss for Epoch 131: 0.09279068559408188 Accuracy for is Epoch 131: 0.9808 Loss for Epoch 132: 0.09162164479494095 Accuracy for is Epoch 132: 0.9808 Loss for Epoch 133: 0.09046636521816254 Accuracy for is Epoch 133: 0.9808 Loss for Epoch 134: 0.08932486921548843 Accuracy for is Epoch 134: 0.9808 Loss for Epoch 135: 0.08819719403982162 Accuracy for is Epoch 135: 0.9808 Loss for Epoch 136: 0.0870833545923233 Accuracy for is Epoch 136: 0.9808 Loss for Epoch 137: 0.08598333597183228 Accuracy for is Epoch 137: 0.9808 Loss for Epoch 138: 0.08489716053009033 Accuracy for is Epoch 138: 0.9808 Loss for Epoch 139: 0.08382480591535568 Accuracy for is Epoch 139: 0.9808 Loss for Epoch 140: 0.08276629447937012 Accuracy for is Epoch 140: 0.9808 Loss for Epoch 141: 0.08172160387039185 Accuracy for is Epoch 141: 0.9808 Loss for Epoch 142: 0.08069069683551788 Accuracy for is Epoch 142: 0.9808 Loss for Epoch 143: 0.07967356592416763 Accuracy for is Epoch 143: 0.9808 Loss for Epoch 144: 0.07867017388343811 Accuracy for is Epoch 144: 0.9808 Loss for Epoch 145: 0.07768049836158752 Accuracy for is Epoch 145: 0.9808 Loss for Epoch 146: 0.0767044872045517 Accuracy for is Epoch 146: 0.9808 Loss for Epoch 147: 0.07574208825826645 Accuracy for is Epoch 147: 0.9872 Loss for Epoch 148: 0.0747932642698288 Accuracy for is Epoch 148: 0.9872 Loss for Epoch 149: 0.07385794073343277 Accuracy for is Epoch 149: 0.9872 Loss for Epoch 150: 0.07293606549501419 Accuracy for is Epoch 150: 0.9872 Loss for Epoch 151: 0.07202755659818649 Accuracy for is Epoch 151: 0.9872 Loss for Epoch 152: 0.07113233953714371 Accuracy for is Epoch 152: 0.9872 Loss for Epoch 153: 0.07025035470724106 Accuracy for is Epoch 153: 0.9872 Loss for Epoch 154: 0.069381482899189 Accuracy for is Epoch 154: 0.9936 Loss for Epoch 155: 0.06852562725543976 Accuracy for is Epoch 155: 0.9936 Loss for Epoch 156: 0.06768272072076797 Accuracy for is Epoch 156: 0.9936 Loss for Epoch 157: 0.0668526440858841 Accuracy for is Epoch 157: 0.9936 Loss for Epoch 158: 0.06603528559207916 Accuracy for is Epoch 158: 0.9936 Loss for Epoch 159: 0.06523054838180542 Accuracy for is Epoch 159: 0.9936 Loss for Epoch 160: 0.06443829834461212 Accuracy for is Epoch 160: 0.9936 Loss for Epoch 161: 0.06365841627120972 Accuracy for is Epoch 161: 0.9936 Loss for Epoch 162: 0.06289078295230865 Accuracy for is Epoch 162: 0.9936 Loss for Epoch 163: 0.06213526800274849 Accuracy for is Epoch 163: 0.9936 Loss for Epoch 164: 0.06139172613620758 Accuracy for is Epoch 164: 1.0 Loss for Epoch 165: 0.060660045593976974 Accuracy for is Epoch 165: 1.0 Loss for Epoch 166: 0.05994005128741264 Accuracy for is Epoch 166: 1.0 Loss for Epoch 167: 0.05923163518309593 Accuracy for is Epoch 167: 1.0 Loss for Epoch 168: 0.058534640818834305 Accuracy for is Epoch 168: 1.0 Loss for Epoch 169: 0.05784890428185463 Accuracy for is Epoch 169: 1.0 Loss for Epoch 170: 0.05717430263757706 Accuracy for is Epoch 170: 1.0 Loss for Epoch 171: 0.05651067569851875 Accuracy for is Epoch 171: 1.0 Loss for Epoch 172: 0.05585784092545509 Accuracy for is Epoch 172: 1.0 Loss for Epoch 173: 0.05521570146083832 Accuracy for is Epoch 173: 1.0 Loss for Epoch 174: 0.05458405241370201 Accuracy for is Epoch 174: 1.0 Loss for Epoch 175: 0.05396275594830513 Accuracy for is Epoch 175: 1.0 Loss for Epoch 176: 0.05335165932774544 Accuracy for is Epoch 176: 1.0 Loss for Epoch 177: 0.0527505949139595 Accuracy for is Epoch 177: 1.0 Loss for Epoch 178: 0.05215940624475479 Accuracy for is Epoch 178: 1.0 Loss for Epoch 179: 0.051577940583229065 Accuracy for is Epoch 179: 1.0 Loss for Epoch 180: 0.05100603401660919 Accuracy for is Epoch 180: 1.0 Loss for Epoch 181: 0.050443537533283234 Accuracy for is Epoch 181: 1.0 Loss for Epoch 182: 0.04989028349518776 Accuracy for is Epoch 182: 1.0 Loss for Epoch 183: 0.049346115440130234 Accuracy for is Epoch 183: 1.0 Loss for Epoch 184: 0.04881088435649872 Accuracy for is Epoch 184: 1.0 Loss for Epoch 185: 0.048284441232681274 Accuracy for is Epoch 185: 1.0 Loss for Epoch 186: 0.04776662588119507 Accuracy for is Epoch 186: 1.0 Loss for Epoch 187: 0.04725727438926697 Accuracy for is Epoch 187: 1.0 Loss for Epoch 188: 0.046756256371736526 Accuracy for is Epoch 188: 1.0 Loss for Epoch 189: 0.04626340791583061 Accuracy for is Epoch 189: 1.0 Loss for Epoch 190: 0.045778583735227585 Accuracy for is Epoch 190: 1.0 Loss for Epoch 191: 0.0453016422688961 Accuracy for is Epoch 191: 1.0 Loss for Epoch 192: 0.044832438230514526 Accuracy for is Epoch 192: 1.0 Loss for Epoch 193: 0.04437081888318062 Accuracy for is Epoch 193: 1.0 Loss for Epoch 194: 0.04391665384173393 Accuracy for is Epoch 194: 1.0 Loss for Epoch 195: 0.04346981272101402 Accuracy for is Epoch 195: 1.0 Loss for Epoch 196: 0.04303012788295746 Accuracy for is Epoch 196: 1.0 Loss for Epoch 197: 0.04259749501943588 Accuracy for is Epoch 197: 1.0 Loss for Epoch 198: 0.04217176139354706 Accuracy for is Epoch 198: 1.0 Loss for Epoch 199: 0.041752807796001434 Accuracy for is Epoch 199: 1.0 Loss for Epoch 200: 0.04134050011634827 Accuracy for is Epoch 200: 1.0 Loss for Epoch 201: 0.040934719145298004 Accuracy for is Epoch 201: 1.0 Loss for Epoch 202: 0.040535323321819305 Accuracy for is Epoch 202: 1.0 Loss for Epoch 203: 0.040142204612493515 Accuracy for is Epoch 203: 1.0 Loss for Epoch 204: 0.03975524380803108 Accuracy for is Epoch 204: 1.0 Loss for Epoch 205: 0.03937431424856186 Accuracy for is Epoch 205: 1.0 Loss for Epoch 206: 0.038999300450086594 Accuracy for is Epoch 206: 1.0 Loss for Epoch 207: 0.03863010182976723 Accuracy for is Epoch 207: 1.0 Loss for Epoch 208: 0.03826659172773361 Accuracy for is Epoch 208: 1.0 Loss for Epoch 209: 0.037908658385276794 Accuracy for is Epoch 209: 1.0 Loss for Epoch 210: 0.03755621239542961 Accuracy for is Epoch 210: 1.0 Loss for Epoch 211: 0.03720913827419281 Accuracy for is Epoch 211: 1.0 Loss for Epoch 212: 0.036867327988147736 Accuracy for is Epoch 212: 1.0 Loss for Epoch 213: 0.036530692130327225 Accuracy for is Epoch 213: 1.0 Loss for Epoch 214: 0.03619911149144173 Accuracy for is Epoch 214: 1.0 Loss for Epoch 215: 0.03587250038981438 Accuracy for is Epoch 215: 1.0 Loss for Epoch 216: 0.03555077686905861 Accuracy for is Epoch 216: 1.0 Loss for Epoch 217: 0.03523382544517517 Accuracy for is Epoch 217: 1.0 Loss for Epoch 218: 0.03492157161235809 Accuracy for is Epoch 218: 1.0 Loss for Epoch 219: 0.03461391478776932 Accuracy for is Epoch 219: 1.0 Loss for Epoch 220: 0.034310776740312576 Accuracy for is Epoch 220: 1.0 Loss for Epoch 221: 0.03401205316185951 Accuracy for is Epoch 221: 1.0 Loss for Epoch 222: 0.03371768817305565 Accuracy for is Epoch 222: 1.0 Loss for Epoch 223: 0.03342757374048233 Accuracy for is Epoch 223: 1.0 Loss for Epoch 224: 0.033141642808914185 Accuracy for is Epoch 224: 1.0 Loss for Epoch 225: 0.03285980969667435 Accuracy for is Epoch 225: 1.0 Loss for Epoch 226: 0.032582007348537445 Accuracy for is Epoch 226: 1.0 Loss for Epoch 227: 0.03230816125869751 Accuracy for is Epoch 227: 1.0 Loss for Epoch 228: 0.032038185745477676 Accuracy for is Epoch 228: 1.0 Loss for Epoch 229: 0.031772010028362274 Accuracy for is Epoch 229: 1.0 Loss for Epoch 230: 0.03150956332683563 Accuracy for is Epoch 230: 1.0 Loss for Epoch 231: 0.03125078231096268 Accuracy for is Epoch 231: 1.0 Loss for Epoch 232: 0.030995601788163185 Accuracy for is Epoch 232: 1.0 Loss for Epoch 233: 0.030743947252631187 Accuracy for is Epoch 233: 1.0 Loss for Epoch 234: 0.030495749786496162 Accuracy for is Epoch 234: 1.0 Loss for Epoch 235: 0.030250955373048782 Accuracy for is Epoch 235: 1.0 Loss for Epoch 236: 0.030009504407644272 Accuracy for is Epoch 236: 1.0 Loss for Epoch 237: 0.02977132797241211 Accuracy for is Epoch 237: 1.0 Loss for Epoch 238: 0.029536370187997818 Accuracy for is Epoch 238: 1.0 Loss for Epoch 239: 0.02930457517504692 Accuracy for is Epoch 239: 1.0 Loss for Epoch 240: 0.029075879603624344 Accuracy for is Epoch 240: 1.0 Loss for Epoch 241: 0.02885022573173046 Accuracy for is Epoch 241: 1.0 Loss for Epoch 242: 0.02862757071852684 Accuracy for is Epoch 242: 1.0 Loss for Epoch 243: 0.028407849371433258 Accuracy for is Epoch 243: 1.0 Loss for Epoch 244: 0.028191013261675835 Accuracy for is Epoch 244: 1.0 Loss for Epoch 245: 0.02797701768577099 Accuracy for is Epoch 245: 1.0 Loss for Epoch 246: 0.027765803039073944 Accuracy for is Epoch 246: 1.0 Loss for Epoch 247: 0.027557330206036568 Accuracy for is Epoch 247: 1.0 Loss for Epoch 248: 0.027351537719368935 Accuracy for is Epoch 248: 1.0 Loss for Epoch 249: 0.027148384600877762 Accuracy for is Epoch 249: 1.0 Loss for Epoch 250: 0.026947828009724617 Accuracy for is Epoch 250: 1.0 Loss for Epoch 251: 0.026749828830361366 Accuracy for is Epoch 251: 1.0 Loss for Epoch 252: 0.026554325595498085 Accuracy for is Epoch 252: 1.0 Loss for Epoch 253: 0.026361290365457535 Accuracy for is Epoch 253: 1.0 Loss for Epoch 254: 0.026170672848820686 Accuracy for is Epoch 254: 1.0 Loss for Epoch 255: 0.025982435792684555 Accuracy for is Epoch 255: 1.0 Loss for Epoch 256: 0.025796538218855858 Accuracy for is Epoch 256: 1.0 Loss for Epoch 257: 0.025612935423851013 Accuracy for is Epoch 257: 1.0 Loss for Epoch 258: 0.025431593880057335 Accuracy for is Epoch 258: 1.0 Loss for Epoch 259: 0.02525247447192669 Accuracy for is Epoch 259: 1.0 Loss for Epoch 260: 0.025075532495975494 Accuracy for is Epoch 260: 1.0 Loss for Epoch 261: 0.02490074560046196 Accuracy for is Epoch 261: 1.0 Loss for Epoch 262: 0.024728069081902504 Accuracy for is Epoch 262: 1.0 Loss for Epoch 263: 0.024557465687394142 Accuracy for is Epoch 263: 1.0 Loss for Epoch 264: 0.024388913065195084 Accuracy for is Epoch 264: 1.0 Loss for Epoch 265: 0.024222364649176598 Accuracy for is Epoch 265: 1.0 Loss for Epoch 266: 0.024057796224951744 Accuracy for is Epoch 266: 1.0 Loss for Epoch 267: 0.023895159363746643 Accuracy for is Epoch 267: 1.0 Loss for Epoch 268: 0.0237344391644001 Accuracy for is Epoch 268: 1.0 Loss for Epoch 269: 0.023575609549880028 Accuracy for is Epoch 269: 1.0 Loss for Epoch 270: 0.023418625816702843 Accuracy for is Epoch 270: 1.0 Loss for Epoch 271: 0.023263458162546158 Accuracy for is Epoch 271: 1.0 Loss for Epoch 272: 0.023110080510377884 Accuracy for is Epoch 272: 1.0 Loss for Epoch 273: 0.02295847237110138 Accuracy for is Epoch 273: 1.0 Loss for Epoch 274: 0.022808605805039406 Accuracy for is Epoch 274: 1.0 Loss for Epoch 275: 0.022660430520772934 Accuracy for is Epoch 275: 1.0 Loss for Epoch 276: 0.022513946518301964 Accuracy for is Epoch 276: 1.0 Loss for Epoch 277: 0.02236912027001381 Accuracy for is Epoch 277: 1.0 Loss for Epoch 278: 0.022225912660360336 Accuracy for is Epoch 278: 1.0 Loss for Epoch 279: 0.022084318101406097 Accuracy for is Epoch 279: 1.0 Loss for Epoch 280: 0.021944290027022362 Accuracy for is Epoch 280: 1.0 Loss for Epoch 281: 0.02180582284927368 Accuracy for is Epoch 281: 1.0 Loss for Epoch 282: 0.02166888304054737 Accuracy for is Epoch 282: 1.0 Loss for Epoch 283: 0.021533453837037086 Accuracy for is Epoch 283: 1.0 Loss for Epoch 284: 0.021399501711130142 Accuracy for is Epoch 284: 1.0 Loss for Epoch 285: 0.021267011761665344 Accuracy for is Epoch 285: 1.0 Loss for Epoch 286: 0.021135959774255753 Accuracy for is Epoch 286: 1.0 Loss for Epoch 287: 0.021006332710385323 Accuracy for is Epoch 287: 1.0 Loss for Epoch 288: 0.02087809145450592 Accuracy for is Epoch 288: 1.0 Loss for Epoch 289: 0.0207512266933918 Accuracy for is Epoch 289: 1.0 Loss for Epoch 290: 0.02062571607530117 Accuracy for is Epoch 290: 1.0 Loss for Epoch 291: 0.02050154097378254 Accuracy for is Epoch 291: 1.0 Loss for Epoch 292: 0.020378679037094116 Accuracy for is Epoch 292: 1.0 Loss for Epoch 293: 0.020257113501429558 Accuracy for is Epoch 293: 1.0 Loss for Epoch 294: 0.02013682946562767 Accuracy for is Epoch 294: 1.0 Loss for Epoch 295: 0.02001778967678547 Accuracy for is Epoch 295: 1.0 Loss for Epoch 296: 0.019899997860193253 Accuracy for is Epoch 296: 1.0 Loss for Epoch 297: 0.019783422350883484 Accuracy for is Epoch 297: 1.0 Loss for Epoch 298: 0.019668051972985268 Accuracy for is Epoch 298: 1.0 Loss for Epoch 299: 0.019553856924176216 Accuracy for is Epoch 299: 1.0 Loss for Epoch 300: 0.01944083720445633 Accuracy for is Epoch 300: 1.0 Loss for Epoch 301: 0.019328976050019264 Accuracy for is Epoch 301: 1.0 Loss for Epoch 302: 0.01921824924647808 Accuracy for is Epoch 302: 1.0 Loss for Epoch 303: 0.019108640030026436 Accuracy for is Epoch 303: 1.0 Loss for Epoch 304: 0.01900012418627739 Accuracy for is Epoch 304: 1.0 Loss for Epoch 305: 0.01889270916581154 Accuracy for is Epoch 305: 1.0 Loss for Epoch 306: 0.018786363303661346 Accuracy for is Epoch 306: 1.0 Loss for Epoch 307: 0.018681077286601067 Accuracy for is Epoch 307: 1.0 Loss for Epoch 308: 0.01857682131230831 Accuracy for is Epoch 308: 1.0 Loss for Epoch 309: 0.01847360096871853 Accuracy for is Epoch 309: 1.0 Loss for Epoch 310: 0.018371401354670525 Accuracy for is Epoch 310: 1.0 Loss for Epoch 311: 0.01827019825577736 Accuracy for is Epoch 311: 1.0 Loss for Epoch 312: 0.018169982358813286 Accuracy for is Epoch 312: 1.0 Loss for Epoch 313: 0.018070736899971962 Accuracy for is Epoch 313: 1.0 Loss for Epoch 314: 0.017972448840737343 Accuracy for is Epoch 314: 1.0 Loss for Epoch 315: 0.017875107005238533 Accuracy for is Epoch 315: 1.0 Loss for Epoch 316: 0.017778705805540085 Accuracy for is Epoch 316: 1.0 Loss for Epoch 317: 0.01768322102725506 Accuracy for is Epoch 317: 1.0 Loss for Epoch 318: 0.017588647082448006 Accuracy for is Epoch 318: 1.0 Loss for Epoch 319: 0.01749497279524803 Accuracy for is Epoch 319: 1.0 Loss for Epoch 320: 0.017402177676558495 Accuracy for is Epoch 320: 1.0 Loss for Epoch 321: 0.017310254275798798 Accuracy for is Epoch 321: 1.0 Loss for Epoch 322: 0.017219197005033493 Accuracy for is Epoch 322: 1.0 Loss for Epoch 323: 0.01712898537516594 Accuracy for is Epoch 323: 1.0 Loss for Epoch 324: 0.017039615660905838 Accuracy for is Epoch 324: 1.0 Loss for Epoch 325: 0.016951076686382294 Accuracy for is Epoch 325: 1.0 Loss for Epoch 326: 0.016863351687788963 Accuracy for is Epoch 326: 1.0 Loss for Epoch 327: 0.0167764313519001 Accuracy for is Epoch 327: 1.0 Loss for Epoch 328: 0.016690311953425407 Accuracy for is Epoch 328: 1.0 Loss for Epoch 329: 0.01660497486591339 Accuracy for is Epoch 329: 1.0 Loss for Epoch 330: 0.016520414501428604 Accuracy for is Epoch 330: 1.0 Loss for Epoch 331: 0.016436615958809853 Accuracy for is Epoch 331: 1.0 Loss for Epoch 332: 0.016353577375411987 Accuracy for is Epoch 332: 1.0 Loss for Epoch 333: 0.016271281987428665 Accuracy for is Epoch 333: 1.0 Loss for Epoch 334: 0.016189727932214737 Accuracy for is Epoch 334: 1.0 Loss for Epoch 335: 0.01610890030860901 Accuracy for is Epoch 335: 1.0 Loss for Epoch 336: 0.016028789803385735 Accuracy for is Epoch 336: 1.0 Loss for Epoch 337: 0.015949388965964317 Accuracy for is Epoch 337: 1.0 Loss for Epoch 338: 0.01587069034576416 Accuracy for is Epoch 338: 1.0 Loss for Epoch 339: 0.015792682766914368 Accuracy for is Epoch 339: 1.0 Loss for Epoch 340: 0.015715356916189194 Accuracy for is Epoch 340: 1.0 Loss for Epoch 341: 0.01563870720565319 Accuracy for is Epoch 341: 1.0 Loss for Epoch 342: 0.01556272804737091 Accuracy for is Epoch 342: 1.0 Loss for Epoch 343: 0.01548740454018116 Accuracy for is Epoch 343: 1.0 Loss for Epoch 344: 0.015412723645567894 Accuracy for is Epoch 344: 1.0 Loss for Epoch 345: 0.01533869095146656 Accuracy for is Epoch 345: 1.0 Loss for Epoch 346: 0.015265293419361115 Accuracy for is Epoch 346: 1.0 Loss for Epoch 347: 0.015192518010735512 Accuracy for is Epoch 347: 1.0 Loss for Epoch 348: 0.015120365656912327 Accuracy for is Epoch 348: 1.0 Loss for Epoch 349: 0.015048825182020664 Accuracy for is Epoch 349: 1.0 Loss for Epoch 350: 0.014977889135479927 Accuracy for is Epoch 350: 1.0 Loss for Epoch 351: 0.014907552860677242 Accuracy for is Epoch 351: 1.0 Loss for Epoch 352: 0.014837798662483692 Accuracy for is Epoch 352: 1.0 Loss for Epoch 353: 0.014768628403544426 Accuracy for is Epoch 353: 1.0 Loss for Epoch 354: 0.014700040221214294 Accuracy for is Epoch 354: 1.0 Loss for Epoch 355: 0.014632027596235275 Accuracy for is Epoch 355: 1.0 Loss for Epoch 356: 0.014564563520252705 Accuracy for is Epoch 356: 1.0 Loss for Epoch 357: 0.014497663825750351 Accuracy for is Epoch 357: 1.0 Loss for Epoch 358: 0.014431305229663849 Accuracy for is Epoch 358: 1.0 Loss for Epoch 359: 0.014365500770509243 Accuracy for is Epoch 359: 1.0 Loss for Epoch 360: 0.014300225302577019 Accuracy for is Epoch 360: 1.0 Loss for Epoch 361: 0.01423549372702837 Accuracy for is Epoch 361: 1.0 Loss for Epoch 362: 0.014171268790960312 Accuracy for is Epoch 362: 1.0 Loss for Epoch 363: 0.014107570052146912 Accuracy for is Epoch 363: 1.0 Loss for Epoch 364: 0.014044385403394699 Accuracy for is Epoch 364: 1.0 Loss for Epoch 365: 0.013981706462800503 Accuracy for is Epoch 365: 1.0 Loss for Epoch 366: 0.013919529505074024 Accuracy for is Epoch 366: 1.0 Loss for Epoch 367: 0.013857843354344368 Accuracy for is Epoch 367: 1.0 Loss for Epoch 368: 0.013796651735901833 Accuracy for is Epoch 368: 1.0 Loss for Epoch 369: 0.013735939748585224 Accuracy for is Epoch 369: 1.0 Loss for Epoch 370: 0.013675708323717117 Accuracy for is Epoch 370: 1.0 Loss for Epoch 371: 0.013615953736007214 Accuracy for is Epoch 371: 1.0 Loss for Epoch 372: 0.013556666672229767 Accuracy for is Epoch 372: 1.0 Loss for Epoch 373: 0.013497831299901009 Accuracy for is Epoch 373: 1.0 Loss for Epoch 374: 0.01343946997076273 Accuracy for is Epoch 374: 1.0 Loss for Epoch 375: 0.013381557539105415 Accuracy for is Epoch 375: 1.0 Loss for Epoch 376: 0.013324081897735596 Accuracy for is Epoch 376: 1.0 Loss for Epoch 377: 0.013267059810459614 Accuracy for is Epoch 377: 1.0 Loss for Epoch 378: 0.013210475444793701 Accuracy for is Epoch 378: 1.0 Loss for Epoch 379: 0.013154320418834686 Accuracy for is Epoch 379: 1.0 Loss for Epoch 380: 0.01309859286993742 Accuracy for is Epoch 380: 1.0 Loss for Epoch 381: 0.013043294660747051 Accuracy for is Epoch 381: 1.0 Loss for Epoch 382: 0.012988414615392685 Accuracy for is Epoch 382: 1.0 Loss for Epoch 383: 0.012933946214616299 Accuracy for is Epoch 383: 1.0 Loss for Epoch 384: 0.012879888527095318 Accuracy for is Epoch 384: 1.0 Loss for Epoch 385: 0.012826235964894295 Accuracy for is Epoch 385: 1.0 Loss for Epoch 386: 0.012772982008755207 Accuracy for is Epoch 386: 1.0 Loss for Epoch 387: 0.012720133177936077 Accuracy for is Epoch 387: 1.0 Loss for Epoch 388: 0.012667671777307987 Accuracy for is Epoch 388: 1.0 Loss for Epoch 389: 0.01261560432612896 Accuracy for is Epoch 389: 1.0 Loss for Epoch 390: 0.0125639159232378 Accuracy for is Epoch 390: 1.0 Loss for Epoch 391: 0.012512610293924809 Accuracy for is Epoch 391: 1.0 Loss for Epoch 392: 0.012461683712899685 Accuracy for is Epoch 392: 1.0 Loss for Epoch 393: 0.012411129660904408 Accuracy for is Epoch 393: 1.0 Loss for Epoch 394: 0.012360942550003529 Accuracy for is Epoch 394: 1.0 Loss for Epoch 395: 0.012311122380197048 Accuracy for is Epoch 395: 1.0 Loss for Epoch 396: 0.012261662632226944 Accuracy for is Epoch 396: 1.0 Loss for Epoch 397: 0.012212551198899746 Accuracy for is Epoch 397: 1.0 Loss for Epoch 398: 0.012163807637989521 Accuracy for is Epoch 398: 1.0 Loss for Epoch 399: 0.012115409597754478 Accuracy for is Epoch 399: 1.0 Loss for Epoch 400: 0.012067358940839767 Accuracy for is Epoch 400: 1.0 Loss for Epoch 401: 0.012019647285342216 Accuracy for is Epoch 401: 1.0 Loss for Epoch 402: 0.011972276493906975 Accuracy for is Epoch 402: 1.0 Loss for Epoch 403: 0.011925249360501766 Accuracy for is Epoch 403: 1.0 Loss for Epoch 404: 0.011878546327352524 Accuracy for is Epoch 404: 1.0 Loss for Epoch 405: 0.011832175776362419 Accuracy for is Epoch 405: 1.0 Loss for Epoch 406: 0.011786133982241154 Accuracy for is Epoch 406: 1.0 Loss for Epoch 407: 0.011740412563085556 Accuracy for is Epoch 407: 1.0 Loss for Epoch 408: 0.011695006862282753 Accuracy for is Epoch 408: 1.0 Loss for Epoch 409: 0.011649922467768192 Accuracy for is Epoch 409: 1.0 Loss for Epoch 410: 0.011605150066316128 Accuracy for is Epoch 410: 1.0 Loss for Epoch 411: 0.011560685001313686 Accuracy for is Epoch 411: 1.0 Loss for Epoch 412: 0.011516541242599487 Accuracy for is Epoch 412: 1.0 Loss for Epoch 413: 0.01147268433123827 Accuracy for is Epoch 413: 1.0 Loss for Epoch 414: 0.0114291375502944 Accuracy for is Epoch 414: 1.0 Loss for Epoch 415: 0.011385884135961533 Accuracy for is Epoch 415: 1.0 Loss for Epoch 416: 0.011342927813529968 Accuracy for is Epoch 416: 1.0 Loss for Epoch 417: 0.011300265789031982 Accuracy for is Epoch 417: 1.0 Loss for Epoch 418: 0.011257889680564404 Accuracy for is Epoch 418: 1.0 Loss for Epoch 419: 0.011215806007385254 Accuracy for is Epoch 419: 1.0 Loss for Epoch 420: 0.011174005456268787 Accuracy for is Epoch 420: 1.0 Loss for Epoch 421: 0.011132482439279556 Accuracy for is Epoch 421: 1.0 Loss for Epoch 422: 0.01109123695641756 Accuracy for is Epoch 422: 1.0 Loss for Epoch 423: 0.01105027087032795 Accuracy for is Epoch 423: 1.0 Loss for Epoch 424: 0.011009575799107552 Accuracy for is Epoch 424: 1.0 Loss for Epoch 425: 0.010969155468046665 Accuracy for is Epoch 425: 1.0 Loss for Epoch 426: 0.010928994044661522 Accuracy for is Epoch 426: 1.0 Loss for Epoch 427: 0.010889106430113316 Accuracy for is Epoch 427: 1.0 Loss for Epoch 428: 0.010849477723240852 Accuracy for is Epoch 428: 1.0 Loss for Epoch 429: 0.010810110718011856 Accuracy for is Epoch 429: 1.0 Loss for Epoch 430: 0.010771005414426327 Accuracy for is Epoch 430: 1.0 Loss for Epoch 431: 0.010732153430581093 Accuracy for is Epoch 431: 1.0 Loss for Epoch 432: 0.01069355383515358 Accuracy for is Epoch 432: 1.0 Loss for Epoch 433: 0.010655202902853489 Accuracy for is Epoch 433: 1.0 Loss for Epoch 434: 0.010617105290293694 Accuracy for is Epoch 434: 1.0 Loss for Epoch 435: 0.010579249821603298 Accuracy for is Epoch 435: 1.0 Loss for Epoch 436: 0.010541647672653198 Accuracy for is Epoch 436: 1.0 Loss for Epoch 437: 0.010504275560379028 Accuracy for is Epoch 437: 1.0 Loss for Epoch 438: 0.010467151179909706 Accuracy for is Epoch 438: 1.0 Loss for Epoch 439: 0.01043025404214859 Accuracy for is Epoch 439: 1.0 Loss for Epoch 440: 0.010393607430160046 Accuracy for is Epoch 440: 1.0 Loss for Epoch 441: 0.010357179678976536 Accuracy for is Epoch 441: 1.0 Loss for Epoch 442: 0.010320993140339851 Accuracy for is Epoch 442: 1.0 Loss for Epoch 443: 0.010285023599863052 Accuracy for is Epoch 443: 1.0 Loss for Epoch 444: 0.010249285958707333 Accuracy for is Epoch 444: 1.0 Loss for Epoch 445: 0.010213782079517841 Accuracy for is Epoch 445: 1.0 Loss for Epoch 446: 0.010178486816585064 Accuracy for is Epoch 446: 1.0 Loss for Epoch 447: 0.01014342624694109 Accuracy for is Epoch 447: 1.0 Loss for Epoch 448: 0.010108571499586105 Accuracy for is Epoch 448: 1.0 Loss for Epoch 449: 0.010073940269649029 Accuracy for is Epoch 449: 1.0 Loss for Epoch 450: 0.010039526969194412 Accuracy for is Epoch 450: 1.0 Loss for Epoch 451: 0.010005323216319084 Accuracy for is Epoch 451: 1.0 Loss for Epoch 452: 0.00997132807970047 Accuracy for is Epoch 452: 1.0 Loss for Epoch 453: 0.009937545284628868 Accuracy for is Epoch 453: 1.0 Loss for Epoch 454: 0.009903961792588234 Accuracy for is Epoch 454: 1.0 Loss for Epoch 455: 0.009870597161352634 Accuracy for is Epoch 455: 1.0 Loss for Epoch 456: 0.009837429039180279 Accuracy for is Epoch 456: 1.0 Loss for Epoch 457: 0.00980446208268404 Accuracy for is Epoch 457: 1.0 Loss for Epoch 458: 0.009771698154509068 Accuracy for is Epoch 458: 1.0 Loss for Epoch 459: 0.009739132598042488 Accuracy for is Epoch 459: 1.0 Loss for Epoch 460: 0.009706763550639153 Accuracy for is Epoch 460: 1.0 Loss for Epoch 461: 0.009674584493041039 Accuracy for is Epoch 461: 1.0 Loss for Epoch 462: 0.009642601013183594 Accuracy for is Epoch 462: 1.0 Loss for Epoch 463: 0.009610812179744244 Accuracy for is Epoch 463: 1.0 Loss for Epoch 464: 0.009579211473464966 Accuracy for is Epoch 464: 1.0 Loss for Epoch 465: 0.009547803550958633 Accuracy for is Epoch 465: 1.0 Loss for Epoch 466: 0.009516575373709202 Accuracy for is Epoch 466: 1.0 Loss for Epoch 467: 0.009485539048910141 Accuracy for is Epoch 467: 1.0 Loss for Epoch 468: 0.009454679675400257 Accuracy for is Epoch 468: 1.0 Loss for Epoch 469: 0.009424007497727871 Accuracy for is Epoch 469: 1.0 Loss for Epoch 470: 0.009393512271344662 Accuracy for is Epoch 470: 1.0 Loss for Epoch 471: 0.009363200515508652 Accuracy for is Epoch 471: 1.0 Loss for Epoch 472: 0.009333064779639244 Accuracy for is Epoch 472: 1.0 Loss for Epoch 473: 0.009303102269768715 Accuracy for is Epoch 473: 1.0 Loss for Epoch 474: 0.009273318573832512 Accuracy for is Epoch 474: 1.0 Loss for Epoch 475: 0.009243707172572613 Accuracy for is Epoch 475: 1.0 Loss for Epoch 476: 0.009214267134666443 Accuracy for is Epoch 476: 1.0 Loss for Epoch 477: 0.009184992872178555 Accuracy for is Epoch 477: 1.0 Loss for Epoch 478: 0.00915589090436697 Accuracy for is Epoch 478: 1.0 Loss for Epoch 479: 0.009126957505941391 Accuracy for is Epoch 479: 1.0 Loss for Epoch 480: 0.009098188020288944 Accuracy for is Epoch 480: 1.0 Loss for Epoch 481: 0.009069581516087055 Accuracy for is Epoch 481: 1.0 Loss for Epoch 482: 0.009041142649948597 Accuracy for is Epoch 482: 1.0 Loss for Epoch 483: 0.009012863039970398 Accuracy for is Epoch 483: 1.0 Loss for Epoch 484: 0.008984743617475033 Accuracy for is Epoch 484: 1.0 Loss for Epoch 485: 0.008956785313785076 Accuracy for is Epoch 485: 1.0 Loss for Epoch 486: 0.008928988128900528 Accuracy for is Epoch 486: 1.0 Loss for Epoch 487: 0.008901339955627918 Accuracy for is Epoch 487: 1.0 Loss for Epoch 488: 0.008873851969838142 Accuracy for is Epoch 488: 1.0 Loss for Epoch 489: 0.008846525102853775 Accuracy for is Epoch 489: 1.0 Loss for Epoch 490: 0.00881933979690075 Accuracy for is Epoch 490: 1.0 Loss for Epoch 491: 0.008792308159172535 Accuracy for is Epoch 491: 1.0 Loss for Epoch 492: 0.008765429258346558 Accuracy for is Epoch 492: 1.0 Loss for Epoch 493: 0.008738703094422817 Accuracy for is Epoch 493: 1.0 Loss for Epoch 494: 0.008712121285498142 Accuracy for is Epoch 494: 1.0 Loss for Epoch 495: 0.008685688488185406 Accuracy for is Epoch 495: 1.0 Loss for Epoch 496: 0.00865940097719431 Accuracy for is Epoch 496: 1.0 Loss for Epoch 497: 0.008633255027234554 Accuracy for is Epoch 497: 1.0 Loss for Epoch 498: 0.008607256226241589 Accuracy for is Epoch 498: 1.0 Loss for Epoch 499: 0.00858139805495739 Accuracy for is Epoch 499: 1.0 ###Markdown Visualize the final node embeddingsVisualize your final embedding here! You can visually compare the figure with the previous embedding figure. After training, you should oberserve that the two classes are more evidently separated. This is a great sanitity check for your implementation as well. ###Code # Visualize the final learned embedding visualize_emb(emb) ###Output _____no_output_____
bumphunter/Python_notebook_stepping_through_bumphunter/py_bumphunter.ipynb
###Markdown Python-equivalent commands for bumphunting ###Code #import csv ##module required so far just to read CSV data files output by minfi processing in R import pandas as pd import numpy as np import statsmodels.api as sm ##Read in the minfi processed output matrices needed to run bumphunter code betaVals = pd.read_csv("Sample_Beta_value_matrix_quantilePreprocessed.csv",index_col=0) phenoDesign = pd.read_csv("Sample_phenotype_design_matrix.csv") probePositions = pd.read_csv("Sample_probe_genomic_positions.csv",index_col=0) probePositions.head() betaVals.head() betaVals.shape ###Output _____no_output_____ ###Markdown The first set of commands within the bumphunterEngine check which arguments were specified when the bumphunter function was called, check if they're in the correct format, and produce informative warnings if any input is incorrect.Then the bumphunterEngine calls several functions from R's foreach package to see if multiple cores were registered before bumphunter was called. This sets up the makes it possible for the more time-consuming bumphunterEngine functions to process in parallel as coded.Parallel processing has NOT been addressed yet in this python implementationThe first backend function bumphunterEngine calls is clusterMaker, which assigns genomic locations to sets of clusters if they are within maxGap of one another (if clusters were not already pre-assigned in one of the function arguments). ###Code ##if (is.null(cluster)) ##cluster <- clusterMaker(chr, pos, maxGap = maxGap) ###Output _____no_output_____ ###Markdown clusterMaker() commands ###Code ##clusterMaker function args (lists a different default maxGap than bumphunter()) ##clusterMaker <- function(chr, pos, assumeSorted = FALSE, maxGap=300) #nonaIndex <- which(!is.na(chr) & !is.na(pos)) ##integer vector of probe indices from 1-485512 #Indexes <- split(nonaIndex, chr[nonaIndex]) ##24 integer vectors (one for each chromosome) #clusterIDs <- rep(NA, length(chr)) #LAST <- 0 ##Set maximum distance in bp allowed between probes in the same cluster maxGap = 300 assumeSorted = False ##don't assume the genomic positions are listed in order of chromosomal location ##Drop NA values from the dataframe of chromosome IDs and genomic locations for each probe if probePositions.isnull().values.any(): probePositions.dropna() ##set "last" counter to zero (keeps count of how many clusters were assigned on previous chromosomes in following loop) last = 0 ##Create list of all chromosome IDs present in dataset probeChr = set(probePositions["Chromosome"]) probeChr = list(probeChr) probeChr[:5] ##list to hold cluster ID number for each genomic position clusterIDs = [] ###Output _____no_output_____ ###Markdown R code (commented out above Python commands) splits the probe positions by chromosome into a list of vectors, but is that really necessary? I'm going to keep the pandas dataframe together and select by chromosome when it comes to it. Might change this if that's unwieldy or slow. ###Code #assumeSorted = FALSE #for(i in seq(along = Indexes)){ ##loops 24 times, once for each chromosome #Index <- Indexes[[i]] #x <- pos[Index] ##select probe positions for that chromosome #if(!assumeSorted){ ##make sure probe genomic locations are in order #Index <- Index[order(x)] #x <- pos[Index] #} ##diff(x) to calculate distance between each sequential position #y <- as.numeric(diff(x) > maxGap) ##binary vector where 0 = distance < maxGap and 1 = distance < maxGap #z <- cumsum(c(1, y)) ##cumulative sum of this binary vector #clusterIDs[Index] <- z + LAST ##turn this cumulative sum vector into the cluster ID numbers #LAST <- max(z) + LAST ##record the last clusterID to start at the next number for the following chromosome #} #head(clusterIDs) ##Loop 24 times (once for each chromosome since clusters can't span across chromosomes) for i in probeChr: ##Select just the rows of the dataframe corresponding to that chromosome chr_rows = probePositions[probePositions.Chromosome==i] ##Create a series of the numeric genomic locations for each probe on that chromosome x = chr_rows.Position ##Make sure they're sorted in ascending order if not assumeSorted: x = x.sort_values() ##Calculate the difference between each successive position diff_x = np.diff(x) ##Create a list of 0s (difference is <maxGap) and 1s (difference is >maxGap) y = (diff_x > maxGap)*1 ##diff is always one item shorter than the series from which it was calculated, so add one 1 to the start of y #y.insert(0,1) y_all = np.insert(y,0,1) ##Take the cumulative sum of these zeroes and ones to assign cluster ID numbers ##that start a new cluster each time the probes are >maxGap apart z = np.cumsum(y_all) ##Add the final cluster number from the previous chromosome to z so that this chromosome starts at the next ID # #z_plus = [1+i for i in z] z_plus = z+last ##Concatenate this chromosome's list of cluster IDs with the running list of cluster ID numbers clusterIDs = np.append(clusterIDs,z_plus) ##Adjust the "last" counter to the final cluster ID number for this chromosome last = max(z_plus) len(clusterIDs) clusterIDs[-10:] ###Output _____no_output_____ ###Markdown After designating cluster ID numbers, bumphunterEngine makes decisions about smoothing and weighting the data depending on the inputs the user provided for the function. Whether the data is eventually weighted or not, it is first processed through the .getEstimate method. ###Code ##if (useWeights & smooth) { ##tmp <- .getEstimate(mat = mat, design = design, ##coef = coef, full = TRUE) ##rawBeta <- tmp$coef ##weights <- 1/tmp$sigma ##rm(tmp) ##} else { ##rawBeta <- .getEstimate(mat = mat, design = design, coef = coef, ##full = FALSE) ##weights <- NULL ##} ###Output _____no_output_____ ###Markdown .getEstimate() commandsCurrently doesn't handle a user input matrix for the permutations argument (assumes argument has been left blank and defaults to None).Found issues when trying to find corresponding numpy functions for the R matrix operations used in solving the linear regression. The following is a cheatsheet I came up with after experimenting with simple test matrices to see what commands produced the same output in both languages:R | Python --- | --- A %*% B | np.dot(A,B)t(A) | A.Tcrossprod(A,B) | np.dot(A.T,B)tcrossprod(A,B) | np.dot(A,B.T) ###Code ##.getEstimate <- function(mat, design, coef, B=NULL, permutations=NULL, ##full=FALSE) { ##v <- design[,coef] ##A <- design[,-coef, drop=FALSE] ##qa <- qr(A) ##S <- diag(nrow(A)) - tcrossprod(qr.Q(qa)) ##vv <- if (is.null(B)) matrix(v, ncol=1) else{ ##if(is.null(permutations)){ ##replicate(B, sample(v)) ##} else{ ##apply(permutations,2,function(i) v[i]) ##} ##} ##sv <- S %*% vv ##vsv <- diag(crossprod(vv,sv)) ##b <- (mat %*% crossprod(S, vv)) / vsv ##if(!is.matrix(b)) ##b <- matrix(b, ncol = 1) ##if (full) { ##sy <- mat %*% S ##df.residual <- ncol(mat) - qa$rank - 1 ##if (is.null(B)) { ##sigma <- matrix(sqrt(rowSums((sy - tcrossprod(b, sv))^2) / df.residual), ncol=1) ##} else { ##sigma <- b ##tmp <- sy ##for (j in 1:B) { ##tmp <- tcrossprod(b[,j], sv[,j]) ##sigma[,j] <- rowSums((sy-tmp)^2) ##} ##sigma <- sqrt(sigma/df.residual) ##} ##out <- list(coef=b, ##sigma=sigma, ##stdev.unscaled=sqrt(1/vsv), ##df.residual=df.residual) ##if (is.null(B)) out$stdev <- as.numeric(out$stdev) ##} else { ##out <- b ##} ##return(out) ##} ##Default values ##coef = 2 --> no need for this in Python implementation B=None ##Works with B > 0 when tested permutations=None full=False ##Works with full = True when tested ##Select the columns of the data frame that are actual phenotype descriptors v = phenoDesign.loc[:,phenoDesign.columns!="(Intercept)"] ##Select the first, non-phenotype column of the design data frame Adf = phenoDesign["(Intercept)"] ##Save this one dataframe column as a numpy array A = np.array(Adf) ##Make sure the array is 2 dimensional A = A.reshape(-1,1) ##Calculate the QR decomposition of the matrix ####May want to replace with scipy.linalg.qr to get rank more legitimately later qa = np.linalg.qr(A) ##Create a diagonal matrix with the same dimensions as the number of samples diagonal = np.zeros((A.shape[0], A.shape[0]), int) np.fill_diagonal(diagonal, 1) ##Subtract the cross product of qa times the transposition of itself from the diagonal matrix qa_mat = np.matrix(qa[0]) S = diagonal - np.dot(qa_mat,qa_mat.T) ##If the user didn't specify a number of permutations in the function input if B is None: ##use the array version of v (the phenotype column(s)) for vv vv = np.array(v) else: ##If the user didn't provide a matrix for the permutations argument if permutations is None: ##convert pandas series v into an array and flatten it to one dimensional v_arr = np.array(v) v_arr = v_arr.reshape(v_arr.shape[0]) ##Randomly permute the phenotypes among the samples B times vv = np.random.choice(v_arr,v_arr.shape[0],replace=False) for i in range(B-1): next_sample = np.random.choice(v_arr,v_arr.shape[0],replace=False) vv = np.vstack((vv,next_sample)) vv = vv.T ##Phenotype permutation matrix vv_mat = np.matrix(vv) S_mat = np.matrix(S) sv = np.dot(S_mat,vv_mat) vsv = np.diag(np.dot(vv_mat.T,sv)) ##Bring the matrix of methylation values for each probe into the math beta_mat = np.matrix(betaVals) b = np.dot(beta_mat,np.dot(S_mat.T, vv_mat)) / vsv ##If b doesn't turn out to be a matrix, shape the values into a one-column matrix if type(b) is not np.matrix: b = np.matrix(b) b = b.reshape(b.shape[0]*b.shape[1],1) if full: sy = np.dot(beta_mat,S_mat) ##Calculate degrees of freedom? df_residual = beta_mat.shape[1] - qa_mat.shape[1] -1 ##If no number of permutations was specified by the user if B is None: sigma = np.matrix(np.sqrt(np.sum(np.square(sy-np.dot(b,sv.T)),axis=1)/df_residual)) sigma = sigma.reshape(sigma.shape[0]*sigma.shape[1],1) else: sigma = b tmp = sy for j in range(B): tmp = np.dot(b[:,j],sv[:,j].T) sigma[:,j] = np.sum(np.square(sy-tmp),axis=1) sigma = np.sqrt(sigma/df_residual) coef = b stdev_unscaled = np.sqrt(1/vsv) ##Below are the data structures returned by .getEstimate() ##out <- list(coef=b, ##sigma=sigma, ##stdev.unscaled=sqrt(1/vsv), ##df.residual=df.residual) ##if (is.null(B)) out$stdev <- as.numeric(out$stdev) ##} else { ##out <- b ##} ##return(out) ##} ###Output _____no_output_____ ###Markdown Proceeding without weights but with smoothingThe output of the previous .getEstimate commands are used as the input rawBeta for the smoothing function. ###Code ##if (smooth) { ##if (verbose) ##message("[bumphunterEngine] Smoothing coefficients.") ##beta <- smoother(y = rawBeta, x = pos, cluster = cluster, ##weights = weights, smoothFunction = smoothFunction, ##verbose = subverbose, ...) ##Index <- which(beta$smoothed) ##beta <- beta$fitted ##} else { ##beta <- rawBeta ##Index <- seq(along = beta) ##} ##smoother <- function(y, x=NULL, cluster, weights=NULL, ##smoothFunction, verbose=TRUE, ...) { ## y = rawBeta --> b output from previous commands ## x = pos --> probePositions.Position ## cluster --> clusterIDs ###Output _____no_output_____ ###Markdown smoother() function commandsThis function can use parallel processing, but it has NOT been implemented yet in this python translation ###Code ##smoother <- function(y, x=NULL, cluster, weights=NULL, ##smoothFunction, verbose=TRUE, ...) { weights = None verbose = True ##if(is.null(dim(y))) ##y <- matrix(y, ncol=1) ##need to change this to be more robust if type(b) is np.matrix: ##If b is not a matrix y = b else: ##reshape its values into a 1 column matrix y = np.matrix(b) y = y.reshape(y.shape[0]*y.shape[1],1) ##if(!is.null(weights) && is.null(dim(weights))) ##weights <- matrix(weights, ncol=1) if (weights is not None) and (type(weights) is not np.matrix): weights = np.matrix(weights) weights = weights.reshape(weights.shape[0]*weights.shape[1],1) ##if (!getDoParRegistered()) ##registerDoSEQ() ##cores <- getDoParWorkers() cores = 1 ##Indexes <- split(seq(along=cluster), cluster) ##baseSize <- length(Indexes) %/% cores ##remain <- length(Indexes) %% cores ##done <- 0L ##IndexesChunks <- vector("list", length = cores) Indexes = [] ID_num = clusterIDs[0] thisInd = [1] for i in range(1,len(clusterIDs)): if clusterIDs[i] == ID_num: thisInd.append(i) ID_num = clusterIDs[i] else: Indexes.append(thisInd) thisInd = [i] ID_num = clusterIDs[i] baseSize = int(len(Indexes)/cores) ##number of clusters to assign to each core remain = len(Indexes) % cores ##leftover clusters if they didn't divide evenly among cores done = 0 ##counter to keep track of clusters that have already been assigned to a core IndexesChunks = [0]*cores ##list to hold each cores' list of clusters ##for(ii in 1:cores) { ##if(remain > 0) { ## ##IndexesChunks[[ii]] <- done + 1:(baseSize + 1) ##remain <- remain - 1L ##done <- done + baseSize + 1L ##} else { ##IndexesChunks[[ii]] <- done + 1:baseSize ##done <- done + baseSize ##} ##} ##For each available core, create a list of for i in range(cores): if remain > 0: baseList = range(baseSize+1) IndexesChunks[i] = [num+done for num in baseList] remain -= 1 done += baseSize + 1 else: baseList = range(baseSize) IndexesChunks[i] = [num+done for num in baseList] done += baseSize ##Commands for parallelization with R's foreach ##IndexesChunks <- lapply(IndexesChunks, function(idxes) { ##do.call(c, unname(Indexes[idxes])) ##}) ##idx <- NULL ## for R CMD check ##ret <- foreach(idx = iter(IndexesChunks), .packages = "bumphunter") %dorng% { ####APPLY SMOOTHING FUNCTION##### ##sm <- smoothFunction(y=y[idx,], x=x[idx], cluster=cluster[idx], ##weights=weights[idx,], verbose=verbose, ...) ##c(sm, list(idx = idx)) ##} ##smoothFunction can be one of three options as specified in the smoother() arguments: ##locfit ##loess ##runmed if smoothFunction == "loess": sm.nonparametric.lowess(y,x) elif smoothFunction == "runmed": pd.rolling_median(y,window) ##window in this case is an integer --> need to update for each cluster somehow ##attributes(ret)[["rng"]] <- NULL ## Paste together results from different workers ##ret <- reduceIt(ret) ## Now fixing order issue ##revOrder <- ret$idx ##names(revOrder) <- seq_along(ret$idx) ##revOrder <- sort(revOrder) ##revOrder <- as.integer(names(revOrder)) ##ret$smoother <- ret$smoother[1] ##ret$fitted <- ret$fitted[revOrder,,drop=FALSE] ##ret$smoothed <- ret$smoothed[revOrder] ##ret$idx <- NULL ##return(ret) ##} baseSize ###Output _____no_output_____ ###Markdown Python equivalents for R's smoothing function options used in bumphunter[locfit](http://ugrad.stat.ubc.ca/R/library/locfit/html/locfit.html) - returns a fit object fitted to a local regression model (methods are outlined in the book [Local Regression and Likelihood](http://web.ipac.caltech.edu/staff/fmasci/home/astro_refs/LocalRegressionBook_1999.pdf)) Python options: * [Python wrapper for Locfit C routines](https://github.com/chairmank/python-locfit) that uses numpy conventions in a github repository. Hasn't been updated in years, but says it has an MIT Open Source Software license (link is dead).* Github project for a [Gradient Boosting Machine that uses Locfit](https://github.com/materialsproject/gbml/) for local regression. It's been updated recently, but hard to tell how you actually use it in Python... Seems to rely on wrapper project above![loess](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/loess.html) - also uses local regression to smooth polynomial Python options: * ~~An individual wrote up [code for a LOESS non-parametric smoothing function](http://www.jtrive.com/loess-nonparametric-scatterplot-smoothing-in-python.html) (dependencies: pandas, numpy, scipy)~~* A function for lowess smoothing is available [in the statsmodel module](https://www.statsmodels.org/dev/generated/statsmodels.nonparametric.smoothers_lowess.lowess.html)* ~~The scikit-misc module also offers a [loess function](https://has2k1.github.io/scikit-misc/loess.html).~~* ~~Another individual on github made a [lowess smoothing script](https://gist.github.com/agramfort/850437). (dependencies: numpy, scipy)~~[runmed](https://www.rdocumentation.org/packages/stats/versions/3.5.1/topics/runmed) - calculates a running median across a list of values for a given window Python options:* pandas has a [rolling median function](https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_median.html), sold! smoothFunction() commands --> loessByCluster() smoothingIn the middle of smoother, the R function calls one of three different smootherFunctions depending on user specification. The default is locfit, but another option is loess which is also based on local regression. ###Code ##sm <- smoothFunction(y=y[idx,], x=x[idx], cluster=cluster[idx], ##weights=weights[idx,], verbose=verbose, ...) ##loessByCluster <- function(y, x=NULL, cluster, weights= NULL, ##bpSpan = 1000, minNum=7, minInSpan=5, ##maxSpan=1, verbose=TRUE) # x = chromosome positions # y = regression beta values ## Depends on limma ## bpSpan is in basepairs ## assumed x are ordered ## if y is vector change to matrix x = probePositions.Position y = b bpSpan = 1000 minNum = 7 ##minimum number of probes in a cluster to be able to smooth the cluster minInSpan = 5 maxSpan = 1 verbose = True ##if(is.null(dim(y))) ##y <- matrix(y, ncol=1) ##need to change this to be more robust ##if(!is.null(weights) && is.null(dim(weights))) ##weights <- matrix(weights,ncol=1) ##if(is.null(x)) ##x <- seq(along=y) if x is None: ##if no x variable is provided, use a sequential list the length of y x = range(y.shape[0]) ##if(is.null(weights)) ##weights <- matrix(1, nrow=nrow(y), ncol=ncol(y)) if weights is None: ##if no weights are provided, make a matrix the same size as y weights = np.zeros((y.shape[0],y.shape[1])) weights += 1 ##with every weight equal to 1 ##Indexes <- split(seq(along=cluster), cluster) --> done in cell above for smoother() ##clusterL <- sapply(Indexes, length) ##spans <- rep(NA, length(Indexes)) ##smoothed <- rep(TRUE, nrow(y)) clusterL = [] ##list that counts the number of probes in each cluster for i in range(len(Indexes)): clusterL.append(len(Indexes[i])) spans = [None]*len(Indexes) smoothed = [True]*y.shape[0] ##for(i in seq(along=Indexes)) { for i in range(len(Indexes)): ##if(verbose) if(i %% 1e4 == 0) cat(".") ##Index <- Indexes[[i]] Index = Indexes[i] ##if(clusterL[i] >= minNum) { ##if this cluster contains the minimum number of probes required for smoothing if (clusterL[i] >= minNum) ##span = bpSpan/median(diff(x[Index]))/length(Index) # make a span ##if(span > maxSpan) span <- maxSpan ##spans[i] <- span span = bpSpan/np.median(np.diff(x[Index]))/len(Index) if span > maxSpan: span = maxSpan spans[i] = span ##if(span*length(Index)>minInSpan){ ##this can be parallelized ##for(j in 1:ncol(y)){ ##y[Index,j] <- limma::loessFit(y[Index,j], x[Index], span = span, ##weights = weights[Index,j])$fitted ##} if span*len(Index) > minInSpan: for j in range(y.shape[0]): y[Index,j] ##} else{ ##y[Index,] <- NA ##smoothed[Index] <- FALSE ##} ##} else{ ##y[Index,] <- NA ##spans[i] <- NA ##smoothed[Index] <- FALSE ##} ##} ##return(list(fitted=y, smoothed=smoothed, smoother="loess")) ##} x = probePositions.Position ##span = bpSpan/median(diff(x[Index]))/length(Index) # make a span ##if(span > maxSpan) span <- maxSpan ##spans[i] <- span Index = Indexes[16] bpSpan=1000 bpSpan/np.median(np.diff(x[Index]))/len(Index) coef.shape ###Output _____no_output_____ ###Markdown smoothFunction() commands --> runmed smoothing ###Code clusterIDs[:50] weights ###Output _____no_output_____
P1/actors_and_movies2.0.ipynb
###Markdown We have duplicated movies in some actors ###Code for i in range(df["Movies"].count()): df["Movies"][i] = list(set(df["Movies"][i])) #Can't use pandas.unique() cos type of ["Movies"][i] is -> list df["Movies"][18] ###Output _____no_output_____ ###Markdown We already eliminate duplicates and get the df to a correct format so we cant start with: Graph analysis with networkx ###Code import networkx as nx G = nx.Graph() start_time = time.time() #Compute time of execution for i in range(df["Movies"].count()): G.add_nodes_from(df["Movies"][i]) #1896 nodes def add_all_edges(G, total_actors): for i in range(total_actors): for j in range(len(df["Movies"][i])-1): #Dont go over the full list -> quicker #why? -> last element connected in previous iter for k in range(len(df["Movies"][i])): if(j >= k): #Dont add equal edges or already added str1 = df["Movies"][i][j] str2 = df["Movies"][i][k] G.add_edge(str1,str2) start_time = time.time() #Compute time of execution total_actors = df["Movies"].count() #total_actors = int(total_actors*0.01) #Gets 20% of the actors, comment out to get full set print("Nº Actors:", total_actors) add_all_edges(G, total_actors) print("--- %s seconds ---" % (time.time() - start_time)) print("Nº Nodes:", G.number_of_nodes()) print("Nº Edges:",G.number_of_edges()) degrees = nx.degree(G) degrees = dict(degrees) mean_deg = [] for k,v in degrees.items(): mean_deg.append(v) if(v == 0): G.remove_node(k) print("\n--- After degree 0 removing ---") print("Nº Nodes:", G.number_of_nodes()) print("Nº Edges:",G.number_of_edges()) G_less = G.copy() G_great = G.copy() for k,v in degrees.items(): if( v != 0): if(v > 5): G_less.remove_node(k) if(v < 30): G_great.remove_node(k) #Quitar nodos con menos de x enlaces print(G_less.number_of_nodes()) print(G_great.number_of_nodes()) #Quitar nodos con muchos enlaces ###Output 389 244
machine_learning/gan/cgan/tf_cgan/tf_cgan_run_module_local.ipynb
###Markdown Run model module locally ###Code import os # Import os environment variables for file hyperparameters. os.environ["TRAIN_FILE_PATTERN"] = "gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord" os.environ["EVAL_FILE_PATTERN"] = "gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord" os.environ["OUTPUT_DIR"] = "gs://machine-learning-1234-bucket/gan/cgan/trained_model2" # Import os environment variables for train hyperparameters. os.environ["TRAIN_BATCH_SIZE"] = str(100) os.environ["TRAIN_STEPS"] = str(60000) os.environ["SAVE_SUMMARY_STEPS"] = str(100) os.environ["SAVE_CHECKPOINTS_STEPS"] = str(5000) os.environ["KEEP_CHECKPOINT_MAX"] = str(10) os.environ["INPUT_FN_AUTOTUNE"] = "False" # Import os environment variables for eval hyperparameters. os.environ["EVAL_BATCH_SIZE"] = str(16) os.environ["EVAL_STEPS"] = str(10) os.environ["START_DELAY_SECS"] = str(6000) os.environ["THROTTLE_SECS"] = str(6000) # Import os environment variables for image hyperparameters. os.environ["HEIGHT"] = str(28) os.environ["WIDTH"] = str(28) os.environ["DEPTH"] = str(1) # Import os environment variables for label hyperparameters. num_classes = 10 os.environ["NUM_CLASSES"] = str(num_classes) os.environ["LABEL_EMBEDDING_DIMENSION"] = str(10) # Import os environment variables for generator hyperparameters. os.environ["LATENT_SIZE"] = str(512) os.environ["GENERATOR_USE_LABELS"] = "True" os.environ["GENERATOR_EMBED_LABELS"] = "True" os.environ["GENERATOR_CONCATENATE_LABELS"] = "True" os.environ["GENERATOR_DENSE_BEFORE_CONCATENATE"] = "False" os.environ["GENERATOR_HIDDEN_UNITS"] = "256,512,1024" os.environ["GENERATOR_LEAKY_RELU_ALPHA"] = str(0.2) os.environ["GENERATOR_FINAL_ACTIVATION"] = "tanh" os.environ["GENERATOR_L1_REGULARIZATION_SCALE"] = str(0.) os.environ["GENERATOR_L2_REGULARIZATION_SCALE"] = str(0.) os.environ["GENERATOR_OPTIMIZER"] = "Adam" os.environ["GENERATOR_LEARNING_RATE"] = str(0.0002) os.environ["GENERATOR_ADAM_BETA1"] = str(0.5) os.environ["GENERATOR_ADAM_BETA2"] = str(0.999) os.environ["GENERATOR_ADAM_EPSILON"] = str(1e-8) os.environ["GENERATOR_CLIP_GRADIENTS"] = "None" os.environ["GENERATOR_TRAIN_STEPS"] = str(1) # Import os environment variables for discriminator hyperparameters. os.environ["DISCRIMINATOR_USE_LABELS"] = "True" os.environ["DISCRIMINATOR_EMBED_LABELS"] = "True" os.environ["DISCRIMINATOR_CONCATENATE_LABELS"] = "True" os.environ["DISCRIMINATOR_DENSE_BEFORE_CONCATENATE"] = "False" os.environ["DISCRIMINATOR_HIDDEN_UNITS"] = "1024,512,256" os.environ["DISCRIMINATOR_LEAKY_RELU_ALPHA"] = str(0.2) os.environ["DISCRIMINATOR_L1_REGULARIZATION_SCALE"] = str(0.) os.environ["DISCRIMINATOR_L2_REGULARIZATION_SCALE"] = str(0.) os.environ["DISCRIMINATOR_OPTIMIZER"] = "Adam" os.environ["DISCRIMINATOR_LEARNING_RATE"] = str(0.0002) os.environ["DISCRIMINATOR_ADAM_BETA1"] = str(0.5) os.environ["DISCRIMINATOR_ADAM_BETA2"] = str(0.999) os.environ["DISCRIMINATOR_ADAM_EPSILON"] = str(1e-8) os.environ["DISCRIMINATOR_CLIP_GRADIENTS"] = "None" os.environ["DISCRIMINATOR_TRAIN_STEPS"] = str(1) os.environ["LABEL_SMOOTHING"] = str(0.9) ###Output _____no_output_____ ###Markdown Train Vanilla GAN model ###Code %%bash gsutil -m rm -rf ${OUTPUT_DIR} export PYTHONPATH=$PYTHONPATH:$PWD/cgan_module python3 -m trainer.task \ --train_file_pattern=${TRAIN_FILE_PATTERN} \ --eval_file_pattern=${EVAL_FILE_PATTERN} \ --output_dir=${OUTPUT_DIR} \ --job-dir=./tmp \ \ --train_batch_size=${TRAIN_BATCH_SIZE} \ --train_steps=${TRAIN_STEPS} \ --save_summary_steps=${SAVE_SUMMARY_STEPS} \ --save_checkpoints_steps=${SAVE_CHECKPOINTS_STEPS} \ --keep_checkpoint_max=${KEEP_CHECKPOINT_MAX} \ --input_fn_autotune=${INPUT_FN_AUTOTUNE} \ \ --eval_batch_size=${EVAL_BATCH_SIZE} \ --eval_steps=${EVAL_STEPS} \ --start_delay_secs=${START_DELAY_SECS} \ --throttle_secs=${THROTTLE_SECS} \ \ --height=${HEIGHT} \ --width=${WIDTH} \ --depth=${DEPTH} \ \ --num_classes=${NUM_CLASSES} \ --label_embedding_dimension=${LABEL_EMBEDDING_DIMENSION} \ \ --latent_size=${LATENT_SIZE} \ --generator_use_labels=${GENERATOR_USE_LABELS} \ --generator_embed_labels=${GENERATOR_EMBED_LABELS} \ --generator_concatenate_labels=${GENERATOR_CONCATENATE_LABELS} \ --generator_dense_before_concatenate=${GENERATOR_DENSE_BEFORE_CONCATENATE} \ --generator_hidden_units=${GENERATOR_HIDDEN_UNITS} \ --generator_leaky_relu_alpha=${GENERATOR_LEAKY_RELU_ALPHA} \ --generator_final_activation=${GENERATOR_FINAL_ACTIVATION} \ --generator_l1_regularization_scale=${GENERATOR_L1_REGULARIZATION_SCALE} \ --generator_l2_regularization_scale=${GENERATOR_L2_REGULARIZATION_SCALE} \ --generator_optimizer=${GENERATOR_OPTIMIZER} \ --generator_learning_rate=${GENERATOR_LEARNING_RATE} \ --generator_adam_beta1=${GENERATOR_ADAM_BETA1} \ --generator_adam_beta2=${GENERATOR_ADAM_BETA2} \ --generator_adam_epsilon=${GENERATOR_ADAM_EPSILON} \ --generator_clip_gradients=${GENERATOR_CLIP_GRADIENTS} \ --generator_train_steps=${GENERATOR_TRAIN_STEPS} \ \ --discriminator_use_labels=${DISCRIMINATOR_USE_LABELS} \ --discriminator_embed_labels=${DISCRIMINATOR_EMBED_LABELS} \ --discriminator_concatenate_labels=${DISCRIMINATOR_CONCATENATE_LABELS} \ --discriminator_dense_before_concatenate=${DISCRIMINATOR_DENSE_BEFORE_CONCATENATE} \ --discriminator_hidden_units=${DISCRIMINATOR_HIDDEN_UNITS} \ --discriminator_leaky_relu_alpha=${DISCRIMINATOR_LEAKY_RELU_ALPHA} \ --discriminator_l1_regularization_scale=${DISCRIMINATOR_L1_REGULARIZATION_SCALE} \ --discriminator_l2_regularization_scale=${DISCRIMINATOR_L2_REGULARIZATION_SCALE} \ --discriminator_optimizer=${DISCRIMINATOR_OPTIMIZER} \ --discriminator_learning_rate=${DISCRIMINATOR_LEARNING_RATE} \ --discriminator_adam_beta1=${DISCRIMINATOR_ADAM_BETA1} \ --discriminator_adam_beta2=${DISCRIMINATOR_ADAM_BETA2} \ --discriminator_adam_epsilon=${DISCRIMINATOR_ADAM_EPSILON} \ --discriminator_clip_gradients=${DISCRIMINATOR_CLIP_GRADIENTS} \ --discriminator_train_steps=${DISCRIMINATOR_TRAIN_STEPS} \ --label_smoothing=${LABEL_SMOOTHING} ###Output train_and_evaluate: args = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} decode_example: features = {'image_raw': FixedLenFeature(shape=[], dtype=tf.string, default_value=None), 'label': FixedLenFeature(shape=[], dtype=tf.int64, default_value=None)} decode_example: image = Tensor("DecodeRaw:0", shape=(?,), dtype=uint8) decode_example: image = Tensor("Reshape:0", shape=(28, 28, 1), dtype=uint8) preprocess_image: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: label = Tensor("Cast_1:0", shape=(), dtype=int32) cgan_model: features = {'image': <tf.Tensor 'IteratorGetNext:0' shape=(?, 28, 28, 1) dtype=float32>} cgan_model: labels = Tensor("IteratorGetNext:1", shape=(?,), dtype=int32, device=/device:CPU:0) cgan_model: mode = train cgan_model: params = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} cgan_model: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) Training discriminator. get_logits_and_losses: real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_logits_and_losses: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) Call generator with Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_images = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) Call discriminator with real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_1/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_1/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_discriminator_loss: discriminator_real_loss = Tensor("discriminator_real_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_fake_loss = Tensor("discriminator_fake_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_loss = Tensor("discriminator_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_reg_loss = Tensor("Const_3:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_total_loss = Tensor("discriminator_total_loss:0", shape=(), dtype=float32) Training generator. get_logits_and_losses: fake_labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) Call generator with fake_Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator_1/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_fake_images = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_2/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_2/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_generator_loss: generator_loss = Tensor("generator_loss:0", shape=(), dtype=float32) get_generator_loss: generator_reg_loss = Tensor("Const_5:0", shape=(), dtype=float32) get_generator_loss: generator_total_loss = Tensor("generator_total_loss:0", shape=(), dtype=float32) get_fake_images: Z = Tensor("image_summary_Z:0", shape=(10, 512), dtype=float32) get_fake_images: labels = Tensor("image_summary_fake_labels:0", shape=(10, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: network = Tensor("generator_2/generator/concat_labels:0", shape=(10, 522), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_0/BiasAdd:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_0:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_1/BiasAdd:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_1:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_2/BiasAdd:0", shape=(10, 1024), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_2:0", shape=(10, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_2/layers_dense_generated_outputs/Tanh:0", shape=(10, 784), dtype=float32) get_variables_and_gradients_generator: variables = [<tf.Variable 'generator/generator/generator/label_embedding_matrix:0' shape=(10, 10) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_0/kernel:0' shape=(522, 256) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_0/bias:0' shape=(256,) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_1/kernel:0' shape=(256, 512) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_1/bias:0' shape=(512,) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_2/kernel:0' shape=(512, 1024) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_2/bias:0' shape=(1024,) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_generated_outputs/kernel:0' shape=(1024, 784) dtype=float32_ref>, <tf.Variable 'generator/layers_dense_generated_outputs/bias:0' shape=(784,) dtype=float32_ref>] get_variables_and_gradients_generator: gradients = [<tensorflow.python.framework.indexed_slices.IndexedSlices object at 0x7f896676df90>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_0/MatMul_grad/MatMul_1:0' shape=(522, 256) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_0/BiasAdd_grad/BiasAddGrad:0' shape=(256,) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_1/MatMul_grad/MatMul_1:0' shape=(256, 512) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_1/BiasAdd_grad/BiasAddGrad:0' shape=(512,) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_2/MatMul_grad/MatMul_1:0' shape=(512, 1024) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_2/BiasAdd_grad/BiasAddGrad:0' shape=(1024,) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_generated_outputs/MatMul_grad/MatMul_1:0' shape=(1024, 784) dtype=float32>, <tf.Tensor 'generator_gradients/generator_1/layers_dense_generated_outputs/BiasAdd_grad/BiasAddGrad:0' shape=(784,) dtype=float32>] get_variables_and_gradients_generator: gradients = [<tf.Tensor 'get_variables_and_gradients_generator/generator/generator/label_embedding_matrix_gradients:0' shape=(10, 10) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_0/kernel_gradients:0' shape=(522, 256) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_0/bias_gradients:0' shape=(256,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_1/kernel_gradients:0' shape=(256, 512) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_1/bias_gradients:0' shape=(512,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_2/kernel_gradients:0' shape=(512, 1024) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_2/bias_gradients:0' shape=(1024,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_generated_outputs/kernel_gradients:0' shape=(1024, 784) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_generator/layers_dense_generated_outputs/bias_gradients:0' shape=(784,) dtype=float32>] get_variables_and_gradients_discriminator: variables = [<tf.Variable 'discriminator/discriminator/discriminator/label_embedding_matrix:0' shape=(10, 10) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_0/kernel:0' shape=(794, 1024) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_0/bias:0' shape=(1024,) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_1/kernel:0' shape=(1024, 512) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_1/bias:0' shape=(512,) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_2/kernel:0' shape=(512, 256) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_2/bias:0' shape=(256,) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_logits/kernel:0' shape=(256, 1) dtype=float32_ref>, <tf.Variable 'discriminator/layers_dense_logits/bias:0' shape=(1,) dtype=float32_ref>] get_variables_and_gradients_discriminator: gradients = [<tensorflow.python.framework.indexed_slices.IndexedSlices object at 0x7f89666fbd10>, <tf.Tensor 'discriminator_gradients/AddN_9:0' shape=(794, 1024) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_8:0' shape=(1024,) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_7:0' shape=(1024, 512) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_6:0' shape=(512,) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_5:0' shape=(512, 256) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_4:0' shape=(256,) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_3:0' shape=(256, 1) dtype=float32>, <tf.Tensor 'discriminator_gradients/AddN_2:0' shape=(1,) dtype=float32>] get_variables_and_gradients_discriminator: gradients = [<tf.Tensor 'get_variables_and_gradients_discriminator/discriminator/discriminator/label_embedding_matrix_gradients:0' shape=(10, 10) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_0/kernel_gradients:0' shape=(794, 1024) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_0/bias_gradients:0' shape=(1024,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_1/kernel_gradients:0' shape=(1024, 512) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_1/bias_gradients:0' shape=(512,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_2/kernel_gradients:0' shape=(512, 256) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_2/bias_gradients:0' shape=(256,) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_logits/kernel_gradients:0' shape=(256, 1) dtype=float32>, <tf.Tensor 'get_variables_and_gradients_discriminator/layers_dense_logits/bias_gradients:0' shape=(1,) dtype=float32>] train_network: scope = discriminator train_network_discriminator: optimizer = <tensorflow.python.training.adam.AdamOptimizer object at 0x7f89666ac3d0> train_network_discriminator: gradients = [<tensorflow.python.framework.indexed_slices.IndexedSlices object at 0x7f89666c3d90>, <tf.Tensor 'cond/discriminator_gradients/AddN_9:0' shape=(794, 1024) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_8:0' shape=(1024,) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_7:0' shape=(1024, 512) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_6:0' shape=(512,) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_5:0' shape=(512, 256) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_4:0' shape=(256,) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_3:0' shape=(256, 1) dtype=float32>, <tf.Tensor 'cond/discriminator_gradients/AddN_2:0' shape=(1,) dtype=float32>] train_network_discriminator: grads_and_vars = <zip object at 0x7f89666ba320> train_network: scope = generator train_network_generator: optimizer = <tensorflow.python.training.adam.AdamOptimizer object at 0x7f89666ac3d0> train_network_generator: gradients = [<tensorflow.python.framework.indexed_slices.IndexedSlices object at 0x7f8966501250>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_0/MatMul_grad/MatMul_1:0' shape=(522, 256) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_0/BiasAdd_grad/BiasAddGrad:0' shape=(256,) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_1/MatMul_grad/MatMul_1:0' shape=(256, 512) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_1/BiasAdd_grad/BiasAddGrad:0' shape=(512,) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_2/MatMul_grad/MatMul_1:0' shape=(512, 1024) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_2/BiasAdd_grad/BiasAddGrad:0' shape=(1024,) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_generated_outputs/MatMul_grad/MatMul_1:0' shape=(1024, 784) dtype=float32>, <tf.Tensor 'cond/generator_gradients/generator_1/layers_dense_generated_outputs/BiasAdd_grad/BiasAddGrad:0' shape=(784,) dtype=float32>] train_network_generator: grads_and_vars = <zip object at 0x7f896662d5a0> decode_example: features = {'image_raw': FixedLenFeature(shape=[], dtype=tf.string, default_value=None), 'label': FixedLenFeature(shape=[], dtype=tf.int64, default_value=None)} decode_example: image = Tensor("DecodeRaw:0", shape=(?,), dtype=uint8) decode_example: image = Tensor("Reshape:0", shape=(28, 28, 1), dtype=uint8) preprocess_image: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: label = Tensor("Cast_1:0", shape=(), dtype=int32) cgan_model: features = {'image': <tf.Tensor 'IteratorGetNext:0' shape=(?, 28, 28, 1) dtype=float32>} cgan_model: labels = Tensor("IteratorGetNext:1", shape=(?,), dtype=int32, device=/device:CPU:0) cgan_model: mode = eval cgan_model: params = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} cgan_model: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) Training discriminator. get_logits_and_losses: real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_logits_and_losses: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) Call generator with Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_images = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) Call discriminator with real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_1/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_1/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_discriminator_loss: discriminator_real_loss = Tensor("discriminator_real_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_fake_loss = Tensor("discriminator_fake_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_loss = Tensor("discriminator_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_reg_loss = Tensor("Const_3:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_total_loss = Tensor("discriminator_total_loss:0", shape=(), dtype=float32) Training generator. get_logits_and_losses: fake_labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) Call generator with fake_Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator_1/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_fake_images = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_2/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_2/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_generator_loss: generator_loss = Tensor("generator_loss:0", shape=(), dtype=float32) get_generator_loss: generator_reg_loss = Tensor("Const_5:0", shape=(), dtype=float32) get_generator_loss: generator_total_loss = Tensor("generator_total_loss:0", shape=(), dtype=float32) get_fake_images: Z = Tensor("image_summary_Z:0", shape=(10, 512), dtype=float32) get_fake_images: labels = Tensor("image_summary_fake_labels:0", shape=(10, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: network = Tensor("generator_2/generator/concat_labels:0", shape=(10, 522), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_0/BiasAdd:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_0:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_1/BiasAdd:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_1:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_2/BiasAdd:0", shape=(10, 1024), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_2:0", shape=(10, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_2/layers_dense_generated_outputs/Tanh:0", shape=(10, 784), dtype=float32) get_eval_metric_ops: discriminator_logits = Tensor("discriminator_concat_logits:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: discriminator_labels = Tensor("discriminator_concat_labels:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: discriminator_probabilities = Tensor("discriminator_probabilities:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: eval_metric_ops = {'accuracy': (<tf.Tensor 'discriminator_accuracy/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_accuracy/update_op:0' shape=() dtype=float32>), 'precision': (<tf.Tensor 'discriminator_precision/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_precision/update_op:0' shape=() dtype=float32>), 'recall': (<tf.Tensor 'discriminator_recall/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_recall/update_op:0' shape=() dtype=float32>), 'auc_roc': (<tf.Tensor 'discriminator_auc_roc/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_auc_roc/update_op:0' shape=() dtype=float32>), 'auc_pr': (<tf.Tensor 'discriminator_auc_pr/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_auc_pr/update_op:0' shape=() dtype=float32>)} serving_input_fn: feature_placeholders = {'Z': <tf.Tensor 'serving_input_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_placeholder_label:0' shape=(?,) dtype=int32>} serving_input_fn: features = {'Z': <tf.Tensor 'serving_input_fn_identity_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_fn_identity_placeholder_label:0' shape=(?,) dtype=int32>} cgan_model: features = {'Z': <tf.Tensor 'serving_input_fn_identity_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_fn_identity_placeholder_label:0' shape=(?,) dtype=int32>} cgan_model: labels = None cgan_model: mode = infer cgan_model: params = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} get_predictions_and_export_outputs: Z = Tensor("serving_input_fn_identity_placeholder_Z:0", shape=(?, 512), dtype=float32) get_predictions_and_export_outputs: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) get_fake_images: Z = Tensor("serving_input_fn_identity_placeholder_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_predictions_and_export_outputs: fake_images = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_predictions_and_export_outputs: generated_images = Tensor("Reshape:0", shape=(?, 28, 28, 1), dtype=float32) get_predictions_and_export_outputs: predictions_dict = {'generated_images': <tf.Tensor 'Reshape:0' shape=(?, 28, 28, 1) dtype=float32>} get_predictions_and_export_outputs: export_outputs = {'predict_export_outputs': <tensorflow.python.saved_model.model_utils.export_output.PredictOutput object at 0x7f89142a5690>} decode_example: features = {'image_raw': FixedLenFeature(shape=[], dtype=tf.string, default_value=None), 'label': FixedLenFeature(shape=[], dtype=tf.int64, default_value=None)} decode_example: image = Tensor("DecodeRaw:0", shape=(?,), dtype=uint8) decode_example: image = Tensor("Reshape:0", shape=(28, 28, 1), dtype=uint8) preprocess_image: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: image = Tensor("sub:0", shape=(28, 28, 1), dtype=float32) decode_example: label = Tensor("Cast_1:0", shape=(), dtype=int32) cgan_model: features = {'image': <tf.Tensor 'IteratorGetNext:0' shape=(?, 28, 28, 1) dtype=float32>} cgan_model: labels = Tensor("IteratorGetNext:1", shape=(?,), dtype=int32, device=/device:CPU:0) cgan_model: mode = eval cgan_model: params = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} cgan_model: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) Training discriminator. get_logits_and_losses: real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_logits_and_losses: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) Call generator with Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("discriminator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_images = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) Call discriminator with real_images = Tensor("real_images:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("real_images:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_1/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_1/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_1/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_1/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_discriminator_loss: discriminator_real_loss = Tensor("discriminator_real_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_fake_loss = Tensor("discriminator_fake_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_loss = Tensor("discriminator_loss:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_reg_loss = Tensor("Const_3:0", shape=(), dtype=float32) get_discriminator_loss: discriminator_total_loss = Tensor("discriminator_total_loss:0", shape=(), dtype=float32) Training generator. get_logits_and_losses: fake_labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) Call generator with fake_Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32). get_fake_images: Z = Tensor("generator_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_1/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator_1/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator_1/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator_1/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) Call discriminator with fake_fake_images = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32). get_discriminator_logits: X = Tensor("generator_1/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_discriminator_logits: labels = Tensor("fake_labels:0", shape=(?, 1), dtype=int32) discriminator_embed_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: label_vectors = Tensor("discriminator_2/discriminator/discriminator/label_vectors:0", shape=(?, 10), dtype=float32) discriminator_use_labels: network = Tensor("discriminator_2/discriminator/concat_labels:0", shape=(?, 794), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_0/BiasAdd:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_0:0", shape=(?, 1024), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/layers_dense_2/BiasAdd:0", shape=(?, 256), dtype=float32) get_discriminator_logits: network = Tensor("discriminator_2/leaky_relu_2:0", shape=(?, 256), dtype=float32) get_discriminator_logits: logits = Tensor("discriminator_2/layers_dense_logits/BiasAdd:0", shape=(?, 1), dtype=float32) get_generator_loss: generator_loss = Tensor("generator_loss:0", shape=(), dtype=float32) get_generator_loss: generator_reg_loss = Tensor("Const_5:0", shape=(), dtype=float32) get_generator_loss: generator_total_loss = Tensor("generator_total_loss:0", shape=(), dtype=float32) get_fake_images: Z = Tensor("image_summary_Z:0", shape=(10, 512), dtype=float32) get_fake_images: labels = Tensor("image_summary_fake_labels:0", shape=(10, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator_2/generator/generator/label_vectors:0", shape=(10, 10), dtype=float32) generator_use_labels: network = Tensor("generator_2/generator/concat_labels:0", shape=(10, 522), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_0/BiasAdd:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_0:0", shape=(10, 256), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_1/BiasAdd:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_1:0", shape=(10, 512), dtype=float32) get_fake_images: network = Tensor("generator_2/layers_dense_2/BiasAdd:0", shape=(10, 1024), dtype=float32) get_fake_images: network = Tensor("generator_2/leaky_relu_2:0", shape=(10, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator_2/layers_dense_generated_outputs/Tanh:0", shape=(10, 784), dtype=float32) get_eval_metric_ops: discriminator_logits = Tensor("discriminator_concat_logits:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: discriminator_labels = Tensor("discriminator_concat_labels:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: discriminator_probabilities = Tensor("discriminator_probabilities:0", shape=(?, 1), dtype=float32) get_eval_metric_ops: eval_metric_ops = {'accuracy': (<tf.Tensor 'discriminator_accuracy/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_accuracy/update_op:0' shape=() dtype=float32>), 'precision': (<tf.Tensor 'discriminator_precision/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_precision/update_op:0' shape=() dtype=float32>), 'recall': (<tf.Tensor 'discriminator_recall/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_recall/update_op:0' shape=() dtype=float32>), 'auc_roc': (<tf.Tensor 'discriminator_auc_roc/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_auc_roc/update_op:0' shape=() dtype=float32>), 'auc_pr': (<tf.Tensor 'discriminator_auc_pr/value:0' shape=() dtype=float32>, <tf.Tensor 'discriminator_auc_pr/update_op:0' shape=() dtype=float32>)} serving_input_fn: feature_placeholders = {'Z': <tf.Tensor 'serving_input_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_placeholder_label:0' shape=(?,) dtype=int32>} serving_input_fn: features = {'Z': <tf.Tensor 'serving_input_fn_identity_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_fn_identity_placeholder_label:0' shape=(?,) dtype=int32>} cgan_model: features = {'Z': <tf.Tensor 'serving_input_fn_identity_placeholder_Z:0' shape=(?, 512) dtype=float32>, 'label': <tf.Tensor 'serving_input_fn_identity_placeholder_label:0' shape=(?,) dtype=int32>} cgan_model: labels = None cgan_model: mode = infer cgan_model: params = {'train_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/train*.tfrecord', 'eval_file_pattern': 'gs://machine-learning-1234-bucket/gan/data/mnist/test*.tfrecord', 'output_dir': 'gs://machine-learning-1234-bucket/gan/cgan/trained_model2/', 'train_batch_size': 100, 'train_steps': 60000, 'save_summary_steps': 100, 'save_checkpoints_steps': 5000, 'keep_checkpoint_max': 10, 'eval_batch_size': 16, 'eval_steps': 10, 'start_delay_secs': 6000, 'throttle_secs': 6000, 'height': 28, 'width': 28, 'depth': 1, 'num_classes': 10, 'label_embedding_dimension': 10, 'latent_size': 512, 'generator_use_labels': True, 'generator_embed_labels': True, 'generator_concatenate_labels': True, 'generator_dense_before_concatenate': False, 'generator_hidden_units': [256, 512, 1024], 'generator_leaky_relu_alpha': 0.2, 'generator_final_activation': 'tanh', 'generator_l1_regularization_scale': 0.0, 'generator_l2_regularization_scale': 0.0, 'generator_optimizer': 'Adam', 'generator_learning_rate': 0.0002, 'generator_adam_beta1': 0.5, 'generator_adam_beta2': 0.999, 'generator_adam_epsilon': 1e-08, 'generator_clip_gradients': None, 'generator_train_steps': 1, 'discriminator_use_labels': True, 'discriminator_embed_labels': True, 'discriminator_concatenate_labels': True, 'discriminator_dense_before_concatenate': False, 'discriminator_hidden_units': [1024, 512, 256], 'discriminator_leaky_relu_alpha': 0.2, 'discriminator_l1_regularization_scale': 0.0, 'discriminator_l2_regularization_scale': 0.0, 'discriminator_optimizer': 'Adam', 'discriminator_learning_rate': 0.0002, 'discriminator_adam_beta1': 0.5, 'discriminator_adam_beta2': 0.999, 'discriminator_adam_epsilon': 1e-08, 'discriminator_clip_gradients': None, 'discriminator_train_steps': 1, 'label_smoothing': 0.9} get_predictions_and_export_outputs: Z = Tensor("serving_input_fn_identity_placeholder_Z:0", shape=(?, 512), dtype=float32) get_predictions_and_export_outputs: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) get_fake_images: Z = Tensor("serving_input_fn_identity_placeholder_Z:0", shape=(?, 512), dtype=float32) get_fake_images: labels = Tensor("ExpandDims:0", shape=(?, 1), dtype=int32) generator_embed_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: label_vectors = Tensor("generator/generator/generator/label_vectors:0", shape=(?, 10), dtype=float32) generator_use_labels: network = Tensor("generator/generator/concat_labels:0", shape=(?, 522), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_0/BiasAdd:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_0:0", shape=(?, 256), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_1/BiasAdd:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_1:0", shape=(?, 512), dtype=float32) get_fake_images: network = Tensor("generator/layers_dense_2/BiasAdd:0", shape=(?, 1024), dtype=float32) get_fake_images: network = Tensor("generator/leaky_relu_2:0", shape=(?, 1024), dtype=float32) get_fake_images: generated_outputs = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_predictions_and_export_outputs: fake_images = Tensor("generator/layers_dense_generated_outputs/Tanh:0", shape=(?, 784), dtype=float32) get_predictions_and_export_outputs: generated_images = Tensor("Reshape:0", shape=(?, 28, 28, 1), dtype=float32) get_predictions_and_export_outputs: predictions_dict = {'generated_images': <tf.Tensor 'Reshape:0' shape=(?, 28, 28, 1) dtype=float32>} get_predictions_and_export_outputs: export_outputs = {'predict_export_outputs': <tensorflow.python.saved_model.model_utils.export_output.PredictOutput object at 0x7f88f478ded0>} ###Markdown Prediction ###Code import matplotlib.pyplot as plt import numpy as np import tensorflow as tf !gsutil ls gs://machine-learning-1234-bucket/gan/cgan/trained_model/export/exporter predict_fn = tf.contrib.predictor.from_saved_model( "gs://machine-learning-1234-bucket/gan/cgan/trained_model/export/exporter/1592753841" ) predictions = predict_fn( { "Z": np.random.normal(size=(num_classes, 100)), "label": np.arange(num_classes) } ) print(list(predictions.keys())) ###Output ['generated_images'] ###Markdown Convert image back to the original scale. ###Code generated_images = np.clip( a=((predictions["generated_images"] + 1.0) * (255. / 2)).astype(np.int32), a_min=0, a_max=255 ) print(generated_images.shape) def plot_images(images): """Plots images. Args: images: np.array, array of images of [num_images, height, width, depth]. """ num_images = len(images) plt.figure(figsize=(20, 20)) for i in range(num_images): image = images[i] plt.subplot(1, num_images, i + 1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow( image.reshape(image.shape[:-1]), cmap="gray_r" ) plt.show() plot_images(generated_images) ###Output _____no_output_____
Preprocessing/SpacyCleaning-sentence.ipynb
###Markdown * Mark Twain: Mark + Various* Fitzgerald: Fitzgerald + Various * Charles: Charles + all ###Code df_charles = pd.concat(charleslist,ignore_index=True) df_charles['Label'] = "1" df_charles = df_charles[['Text','Label']] df_others = pd.concat(marklist +variouslsit+ janelist +fitzgeraldlist,ignore_index=True) df_others['Label'] = "0" df_others = df_others[['Text','Label']] df_charles_f = pd.concat([df_charles,df_others],ignore_index=True) print(df_charles_f.shape[0]) df_charles_f.Label.describe() df_mark = pd.concat(marklist,ignore_index=True) df_mark['Label'] = "1" df_mark = df_mark[['Text','Label']] df_others = pd.concat(variouslsit,ignore_index=True) df_others['Label'] = "0" df_others = df_others[['Text','Label']] df_mark_f = pd.concat([df_mark,df_others],ignore_index=True) print(df_mark_f.shape[0]) df_mark_f.Label.describe() df_fitzgerald = pd.concat(fitzgeraldlist,ignore_index=True) df_fitzgerald['Label'] = "1" df_fitzgerald = df_fitzgerald[['Text','Label']] df_others = pd.concat(variouslsit,ignore_index=True) df_others['Label'] = "0" df_others = df_others[['Text','Label']] df_fitzgerald_f = pd.concat([df_fitzgerald,df_others],ignore_index=True) print(df_fitzgerald_f.shape[0]) df_fitzgerald_f.Label.describe() # apply on the df['Text'] # retain all columns and add addtional columns spacy_words def NER_replace(df): df['spacy_words'] = df['Text'].apply(lambda x: list(nlp(x).ents)) for index, row in df.iterrows(): thistext = row.Text for ent in row.spacy_words: if ent.label_ in ['PERSON','FAC','GPE','LOC','ORG']: thistext = thistext.replace(ent.text,ent.label_) df.at[index, 'Text'] = thistext return df df_fitzgerald_f = NER_replace(df_fitzgerald_f) #df_mark_f = NER_replace(df_mark_f) df_charles_f = NER_replace(df_charles_f) df_fitzgerald_f.Text[40] for ent in df_fitzgerald_f.spacy_words[40]: if ent.label_ in ['PERSON','FAC','GPE','LOC','ORG']: print(ent.text, ent.start_char, ent.end_char, ent.label_) df_fitzgerald_f.to_csv("../Dataset_v3/deidentified/Fitzgerald_sent_di.csv") df_charles_f.to_csv("../Dataset_v3/deidentified/Charles_sent_di.csv") #df_mark_f.to_csv("../Dataset_v3/deidentified/Mark_sent_di.csv") ###Output _____no_output_____
DAY-5/DAY-5.ipynb
###Markdown Question 1 :Write a Python program to find the first 20 non-even prime natural numbers. ###Code import sympy prime_no = list(sympy.primerange(0, 75)) for i in prime_no: if i%2!=0: print(i) ###Output 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 ###Markdown Question 2 :Write a Python program to implement 15 functions of string. ###Code # 1. strip(): The strip() method removes any whitespace from the beginning or the end. a = " Hello, World! " print(a.strip()) #2. lower(): The lower() method returns the string in lower case. a = "Hello, World!" print(a.lower()) #3. upper(): The upper() method returns the string in upper case. a = "Hello, World!" print(a.upper()) #4. replace(): The replace() method replaces a string with another string. a = "Hello, World!" print(a.replace("W", "J")) #5. split(): The split() method splits the string into substrings if it finds instances of the separator. a = "Hello, World!" print(a.split(",")) #6. isdigit(): txt = "50800" x = txt.isdigit() print(x) #7. isidentifier(): txt = "Demo" x = txt.isidentifier() print(x) #8. islower(): txt = "hello world!" x = txt.islower() print(x) #9. isupper(): txt = "THIS IS NOW!" x = txt.isupper() print(x) #10. isspace(): txt = " " x = txt.isspace() print(x) #11. istitle(): txt = "Hello, And Welcome To My World!" x = txt.istitle() print(x) #12. isnumeric(): txt = "565543" x = txt.isnumeric() print(x) #13. isprintable(): txt = "Hello! Are you #1?" x = txt.isprintable() print(x) #14. isalnum(): txt = "Company12" x = txt.isalnum() print(x) #15. isalpha(): txt = "CompanyX" x = txt.isalpha() print(x) #16. isdecimal(): txt = "\u0033" #unicode for 3 x = txt.isdecimal() print(x) #17. capitalize(): txt = "hello, and welcome to my world." x = txt.capitalize() print (x) #18. casefold(): txt = "Hello, And Welcome To My World!" x = txt.casefold() print(x) #19. center(): txt = "banana" x = txt.center(20) print(x) #20. count(): txt = "I love apples, apple are my favorite fruit" x = txt.count("apple") print(x) #21. encode(): txt = "My name is Ståle" x = txt.encode() print(x) #22. endswith(): txt = "Hello, welcome to my world." x = txt.endswith(".") print(x) #23. expandtabs(): txt = "H\te\tl\tl\to" x = txt.expandtabs(2) print(x) #24. find(): txt = "Hello, welcome to my world." x = txt.find("welcome") print(x) #25. format(): txt = "For only {price:.2f} dollars!" print(txt.format(price = 49)) #26. index(): txt = "Hello, welcome to my world." x = txt.index("welcome") print(x) #27. rsplit(): txt = "apple, banana, cherry" x = txt.rsplit(", ") print(x) #28. rstrip(): txt = " banana " x = txt.rstrip() print("of all fruits", x, "is my favorite") #29. splitlines(): txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines() print(x) #30. startswith(): txt = "Hello, welcome to my world." x = txt.startswith("Hello") print(x) #31. swapcase(): txt = "Hello My Name Is PETER" x = txt.swapcase() print(x) #32. title(): txt = "Welcome to my world" x = txt.title() print(x) #33. zfill(): txt = "50" x = txt.zfill(10) print(x) #34. partition(): txt = "I could eat bananas all day" x = txt.partition("bananas") print(x) #35. replace(): txt = "I like bananas" x = txt.replace("bananas", "apples") print(x) #36. rfind(): txt = "Mi casa, su casa." x = txt.rfind("casa") print(x) #37. rindex(): txt = "Mi casa, su casa." x = txt.rindex("casa") print(x) #38. rjust(): txt = "banana" x = txt.rjust(20) print(x, "is my favorite fruit.") #39. rpartition(): txt = "I could eat bananas all day, bananas are my favorite fruit" x = txt.rpartition("bananas") print(x) #40. join(): myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) #41. ljust(): txt = "banana" x = txt.ljust(20) print(x, "is my favorite fruit.") #42. lstrip(): txt = " banana " x = txt.lstrip() print("of all fruits", x, "is my favorite") ###Output of all fruits banana is my favorite ###Markdown Question 3:Write a Python program to check if the given string is a Palindrome or Anagram or None of them.Display the message accordingly to the user. ###Code def is_anagram(str1, str2): list_str1 = list(str1) list_str1.sort() list_str2 = list(str2) list_str2.sort() return (list_str1 == list_str2) string = input("Enter first string to check whether it is a anagram: ") string1 = input("Enter second string to check whether it is a anagram: ") ana_check = is_anagram(string,string1) pali_check = string==string[::-1] if pali_check and ana_check: print("The entered string is a Palindrome as well as an Anagram.") elif pali_check: print("The entered string is a Palindrome") elif ana_check: print("The entered string is an Anagram") else: print("None of them") ###Output Enter first string to check whether it is a anagram: wasitacatisaw Enter second string to check whether it is a anagram: acatisawwasit The entered string is a Palindrome as well as an Anagram. ###Markdown Question 4:Write a Python's user defined function that removes all the additional characters from the stringand converts it finally to lower case using built-in lower(). eg: If the string is "Dr. Darshan Ingle@AI-ML Trainer", then the output be "drdarshaningleaimltrainer". ###Code def replace_char(z): invalid_list = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', ',', '.', '?', ':', ';', " "] for i in invalid_list: z = z.replace(i,'') z = z.lower() print("After removing all special characters from the string!") print("Resultant String is: ",z) string = "Dr. Darshan Ingle @AI-ML Trainer." print("The String is: ", string) replace_char(string) ###Output The String is: Dr. Darshan Ingle @AI-ML Trainer. After removing all special characters from the string! Resultant String is: drdarshaningleaimltrainer
TD-Learning/TD learning.ipynb
###Markdown 引入CliffWalking-v0环境,及环境初探 ###Code import gym env = gym.make('CliffWalking-v0') # 经典悬崖寻路环境 print('状态空间:',env.observation_space) print('动作空间:',env.action_space) print('状态35执行[⬆️-0,➡️-1,⬇️-2,⬅️-3]动作后的四元组,分别表示(prob ,next_state, reward, down):') env.P[35] env.reset() env.render() ###Output o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o x C C C C C C C C C C T ###Markdown 1. Solving CliffWalking-v0 via Sarsa ###Code import numpy as np import random def select_action_behavior_policy(action_value_set, epsilon): '''使用epsilon-greedy采样action''' prob = random.random() if prob > epsilon: action = np.argmax(action_value_set) else: action = random.randint(0,3) return action def Sarsa(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9, Q_table=None): ''' Sarsa算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q表 if Q_table is None: Q = np.zeros( (env.nS, env.nA), dtype=np.float ) else: Q = Q_table # 方便后续作图,不做图的话可以忽略本行和Q_table形参 sum_reward = 0 for num in range(num_of_episode): # sum_reward = 0 state = env.reset() # Init S # 2.通过behavior policy采样初始state下的action action = select_action_behavior_policy(Q[state], epsilon) while True: # 3.执行action并观察R和next state next_state, reward, done, info = env.step(action) # 4.再次通过behavior policy采样next_action next_action = select_action_behavior_policy(Q[next_state], epsilon) # 5.更新Q(S,A),使用下一个状态-动作二元组更新 Q[state][action] += alpha * (reward + gamma*Q[next_state][next_action] - Q[state][action]) sum_reward += reward if done: break state, action = next_state, next_action # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] # if num % 20 == 0: print("Episode: {}, Score: {}".format(num, sum_reward)) return Q, sum_reward def get_optimal_policy(env, Q): '''从Q表中得到最优策略''' nS = Q.shape[0] policy = np.full(nS, 0) # 初始化为全0元素 for state in range(nS): action = np.argmax( Q[state] ) next_state = env.P[state][action][0][1] policy[state] = action return policy def print_policy(policy): print("\n【Sarsa Optimal Policy】:") for i, p in enumerate(policy): if i % 12 == 0 and i != 0: print() if p == 0: print('⬆️', end=' ') elif p == 1: print('➡️', end=' ') elif p == 2: print('⬇️', end=' ') elif p == 3: print('⬅️', end=' ') env = gym.make('CliffWalking-v0') # 经典悬崖寻路环境 # Q-learning学习出Q表 Q_table, _ = Sarsa(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=2000, gamma=0.9) # 通过训练好的Q表获取最优policy policy = get_optimal_policy(env, Q_table) # 打印最优policy print_policy(policy) ###Output 【Sarsa Optimal Policy】: ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ⬇️ ⬆️ ⬆️ ➡️ ⬅️ ➡️ ⬆️ ➡️ ➡️ ➡️ ➡️ ➡️ ⬇️ ⬆️ ➡️ ⬆️ ⬆️ ⬆️ ⬆️ ➡️ ⬆️ ⬆️ ⬆️ ➡️ ⬇️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ###Markdown 2. Solving CliffWalking-v0 via Q-learning ###Code import numpy as np import random def select_action_behavior_policy(action_value_set, epsilon): '''使用epsilon-greedy采样action''' prob = random.random() if prob > epsilon: action = np.argmax(action_value_set) else: action = random.randint(0,3) return action def Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9, Q_table=None): ''' Q学习算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q表 if Q_table is None: Q = np.zeros( (env.nS, env.nA), dtype=np.float ) else: Q = Q_table sum_reward = 0 for num in range(num_of_episode): # sum_reward = 0 state = env.reset() # Init S while True: # 2.通过behavior policy采样action action = select_action_behavior_policy(Q[state], epsilon) # 3.执行action并观察R和next state next_state, reward, done, info = env.step(action) # 4.更新Q(S,A),使用max操作更新 Q[state][action] += alpha * (reward + gamma*max( Q[next_state] ) - Q[state][action]) sum_reward += reward if done: break state = next_state # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] # if num % 20 == 0: print("Episode: {}, Score: {}".format(num, sum_reward)) return Q, sum_reward def get_optimal_policy(env, Q): '''从Q表中得到最优策略''' nS = Q.shape[0] policy = np.full(nS, 0) # 初始化为全0元素 for state in range(nS): action = np.argmax( Q[state] ) next_state = env.P[state][action][0][1] policy[state] = action return policy def print_policy(policy): print("\n【Q-learning Optimal Policy】:") for i, p in enumerate(policy): if i % 12 == 0 and i != 0: print() if p == 0: print('⬆️', end=' ') elif p == 1: print('➡️', end=' ') elif p == 2: print('⬇️', end=' ') elif p == 3: print('⬅️', end=' ') env = gym.make('CliffWalking-v0') # 经典悬崖寻路环境 # Q-learning学习出Q表 Q_table, _ = Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9) # 通过训练好的Q表获取最优policy policy = get_optimal_policy(env, Q_table) # 打印最优policy print_policy(policy) ###Output 【Q-learning Optimal Policy】: ⬆️ ➡️ ⬅️ ⬅️ ⬇️ ➡️ ➡️ ➡️ ➡️ ➡️ ⬅️ ⬇️ ⬇️ ⬇️ ➡️ ➡️ ➡️ ⬇️ ⬇️ ➡️ ➡️ ➡️ ➡️ ⬇️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ➡️ ⬇️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ###Markdown - 两种算法Average reward对比 ###Code from tqdm import tqdm import matplotlib matplotlib.use('nbAgg') import matplotlib.pyplot as plt import matplotlib as mpl def plot_Sarsa_and_Q_learning(env, episodes=500, runs=50): '''绘图Q-learning''' Sarsa_table, Q_learning_table, Sarsa_average_reward, Q_learning_average_reward = None, None, [], [] for i in tqdm(range(episodes)): Sarsa_table, Sarsa_sum_reward = Sarsa(env, alpha=0.2, epsilon_scope=[0.1,0.1,0.99], num_of_episode=runs, gamma=0.9, Q_table=Sarsa_table) Q_learning_table, Q_learning_sum_reward = Q_learning(env, alpha=0.2, epsilon_scope=[0.1,0.1,0.99], num_of_episode=runs, gamma=0.9, Q_table=Q_learning_table) Sarsa_average_reward.append(Sarsa_sum_reward/runs) Q_learning_average_reward.append(Q_learning_sum_reward/runs) plt.plot(Q_learning_average_reward, label='Q-Learning') plt.plot(Sarsa_average_reward, label='Sarsa') plt.xlabel('Episodes') plt.ylabel('Average of rewards during episode') plt.ylim([-120, 0]) plt.legend() plt.show() plt.close() env.reset() plot_Sarsa_and_Q_learning(env, episodes=500, runs=60) ###Output 100%|██████████| 500/500 [00:15<00:00, 34.04it/s] ###Markdown - 两种算法耗时对比 ###Code from timeit import repeat consum_time = repeat( lambda:Q_learning(env, 0.2, [0.2,0.05,0.99], 1000, gamma=0.9), number=1, repeat=3 ) print('\nQ-learning在CliffWalking-v0任务上的最短耗时:%.4f秒' % ( min(consum_time) ) ) consum_time = repeat( lambda:Sarsa(env, 0.2, [0.2,0.05,0.99], 1000, gamma=0.9), number=1, repeat=3 ) print('\nSarsa在CliffWalking-v0任务上的最短耗时:%.4f秒' % ( min(consum_time) ) ) ###Output Q-learning在CliffWalking-v0任务上的最短耗时:0.3044秒 Sarsa在CliffWalking-v0任务上的最短耗时:0.2843秒 ###Markdown 3. Double Q-learning - 构建环境 ###Code import numpy as np class Env(): '''构造一个环境类''' def __init__(self, mu, sigma, nB): self.mu = mu self.sigma = sigma self.STATE_A = self.left = 0 self.STATE_B = self.right = 1 self.Terminal = 2 self.nS = 3 # 加上Terminal即3个状态 self.nA = 2 self.nB = nB # 状态B的动作数 self.state = self.STATE_A def reset(self): self.state = self.STATE_A return self.state def step(self, action): # A--left if self.state == self.STATE_A and action == self.left: self.state = self.STATE_B return self.state, 0, False # next_state, reward, done # A--right elif self.state == self.STATE_A and action == self.right: self.state = self.Terminal return self.state, 0, True # B--all_actions elif self.state == self.STATE_B: self.state = self.Terminal reward = random.normalvariate(self.mu, self.sigma) return self.state, reward, True ###Output _____no_output_____ ###Markdown - 初始化Q表+采样动作函数定义 ###Code import numpy as np import random def init_Q_table(env): '''初始化Q表''' Q = {env.STATE_A:{action:0 for action in range(env.nA)}, env.STATE_B:{action:0 for action in range(env.nB)}, env.Terminal:{action:0 for action in range(env.nA)}} return Q def select_action_behavior_policy(action_value_dict, epsilon): '''使用epsilon-greedy采样action''' if random.random() > epsilon: max_keys = [key for key, value in action_value_dict.items() if value == max( action_value_dict.values() )] action = random.choice(max_keys) else: # 从Q字典对应state中随机选取1个动作,由于返回list,因此通过[0]获取元素 action = random.sample(action_value_dict.keys(), 1)[0] return action ###Output _____no_output_____ ###Markdown - Q-learning算法实现 ###Code def Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9): ''' Q学习算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q表 Q = init_Q_table(env) for num in range(num_of_episode): state = env.reset() # Init S while True: # 2.通过behavior policy采样action action = select_action_behavior_policy(Q[state], epsilon) # 3.执行action并观察R和next state next_state, reward, done = env.step(action) # 4.更新Q(S,A),使用max操作更新 Q[state][action] += alpha * (reward + gamma*max( Q[next_state].values() ) - Q[state][action]) if done: break state = next_state # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] return Q env = Env(-0.1, 1, 10) # Q-learning学习出Q表 Q_table = Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=300, gamma=0.9) Q_table ###Output _____no_output_____ ###Markdown - Double Q-learning算法实现 ###Code def get_Q1_add_Q2(Q1_state_dict, Q2_state_dict): '''返回Q1[state]+Q2[state]''' return {action: Q1_value + Q2_state_dict[action] for action, Q1_value in Q1_state_dict.items()} def double_Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9): ''' 双Q学习算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q1表和Q2表 Q1 = init_Q_table(env) Q2 = init_Q_table(env) for num in range(num_of_episode): state = env.reset() # Init S while True: # 2.通过behavior policy采样action add_Q1_Q2_state = get_Q1_add_Q2(Q1[state], Q1[state]) action = select_action_behavior_policy(add_Q1_Q2_state, epsilon) # 3.执行action并观察R和next state next_state, reward, done = env.step(action) # 4.更新Q(S,A),使用max操作更新 if random.random() >= 0.5: # 从Q1表中的下一步state找出状态价值最高对应的action视为Q1[state]的最优动作 A1 = random.choice( [action for action, value in Q1[next_state].items() if value == max( Q1[next_state].values() )] ) # 将Q1[state]得到的最优动作A1代入到Q2[state][A1]中的值作为Q1[state]的更新 Q1[state][action] += alpha * (reward + gamma*Q2[next_state][A1] - Q1[state][action]) else: A2 = random.choice( [action for action, value in Q2[next_state].items() if value == max( Q2[next_state].values() )] ) Q2[state][action] += alpha * (reward + gamma*Q1[next_state][A2] - Q2[state][action]) if done: break state = next_state # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] return Q1 env = Env(-0.1, 1, 10) # Q-learning学习出Q表 Q_table = double_Q_learning(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=300, gamma=0.9) Q_table ###Output _____no_output_____ ###Markdown - Action Distribution思想实现 ###Code def Action_Distribution(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9): ''' 按当前state的动作分布选择动作,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q表 Q = init_Q_table(env) for num in range(num_of_episode): state = env.reset() # Init S while True: # 2.通过behavior policy采样action action = select_action_behavior_policy(Q[state], epsilon) # 3.执行action并观察R和next state next_state, reward, done = env.step(action) # 4.更新Q(S,A),使用max操作更新 Q[state][action] += alpha * (reward + gamma*random.choice(list( Q[next_state].values() )) - Q[state][action]) if done: break state = next_state # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] return Q env = Env(-0.1, 1, 10) # Q-learning学习出Q表 Q_table = Action_Distribution(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=300, gamma=0.9) Q_table ###Output _____no_output_____ ###Markdown - Expected Sarsa算法实现 ###Code def Expected_Sarsa(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9): ''' 期望Sarsa算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q表 Q = init_Q_table(env) for num in range(num_of_episode): state = env.reset() # Init S while True: # 2.通过behavior policy采样action action = select_action_behavior_policy(Q[state], epsilon) # 3.执行action并观察R和next state next_state, reward, done = env.step(action) # 4.更新Q(S,A),使用max操作更新 Q[state][action] += alpha * (reward + gamma*sum( Q[next_state].values() ) / len(Q[next_state]) - Q[state][action]) if done: break state = next_state # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] return Q env = Env(-0.1, 1, 10) # Q-learning学习出Q表 Q_table = Expected_Sarsa(env, alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=300, gamma=0.9) Q_table ###Output _____no_output_____ ###Markdown TD-Learing Summary ###Code def TD_learning(env, method='Q-Learning', alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=1000, gamma=0.9): ''' TD学习算法,返回Q表和估计的最优策略 其中epsilon_scope由高到低衰减,从左到右分别是[最高值,最低值,衰减因子] ''' epsilon = epsilon_scope[0] # 1. 初始化Q1表和Q2表 Q = init_Q_table(env) if method == 'Double-Q': Q2 = init_Q_table(env) bool_A_left = np.zeros(num_of_episode) Aleft_Q_values = [] B_max_Q_values = [] for num in range(num_of_episode): state = env.reset() # Init S while True: # 2.通过behavior policy采样action if method == 'Double-Q': add_Q1_Q2_state = {action: Q1_value + Q2[state][action] for action, Q1_value in Q[state].items()} action = select_action_behavior_policy(add_Q1_Q2_state, epsilon) else: action = select_action_behavior_policy(Q[state], epsilon) if state == env.STATE_A and action == env.left: bool_A_left[int(num)] += 1 # 3.执行action并观察R和next state next_state, reward, done = env.step(action) # 4.更新Q(S,A),使用max操作更新 if method == 'Q-Learning': Q[state][action] += alpha * (reward + gamma*max( Q[next_state].values() ) - Q[state][action]) elif method == 'Expected_Sarsa': Q[state][action] += alpha * (reward + gamma*sum( Q[next_state].values() ) / len(Q[next_state]) - Q[state][action]) elif method == 'Action_Distribution': Q[state][action] += alpha * (reward + gamma*random.choice(list( Q[next_state].values() )) - Q[state][action]) elif method == 'Double-Q': if random.random() >= 0.5: # 从Q1表中的下一步state找出状态价值最高对应的action视为Q1[state]的最优动作 A1 = random.choice( [action for action, value in Q[next_state].items() if value == max( Q[next_state].values() )] ) # 将Q1[state]得到的最优动作A1代入到Q2[state][A1]中的值作为Q1[state]的更新 Q[state][action] += alpha * (reward + gamma*Q2[next_state][A1] - Q[state][action]) else: A2 = random.choice( [action for action, value in Q2[next_state].items() if value == max( Q2[next_state].values() )] ) Q2[state][action] += alpha * (reward + gamma*Q[next_state][A2] - Q2[state][action]) if done: break state = next_state Aleft_Q_values.append(Q[env.STATE_A][env.left]) B_max_Q_values.append(max(Q[env.STATE_B].values())) # 对epsilon进行衰减 if epsilon >= epsilon_scope[1]: epsilon *= epsilon_scope[2] # if num % 20 == 0: print("Episode: {}, Score: {}".format(num, sum_reward)) return Q, bool_A_left, Aleft_Q_values, B_max_Q_values # method = ['Q-Learning', 'Expected_Sarsa', 'Action_Distribution', 'Double-Q'] env = Env(-0.1, 1, 10) # Q-learning学习出Q表 Q_table, _, _, _ = TD_learning(env, method='Double-Q', alpha=0.2, epsilon_scope=[0.2,0.05,0.99], num_of_episode=300, gamma=0.9) Q_table def show_figure(prob_Q_A_left, prob_E_A_left, prob_AD_A_left, prob_Q2_A_left): import matplotlib.pyplot as plt plt.ylabel('% left actions from A') plt.xlabel('Episodes') x_ticks = np.arange(0,301, 20) y_ticks = np.arange(0,1.1,0.1) plt.xticks(x_ticks) plt.yticks(y_ticks,['0%','10%','20%','30%','40%','50%','60%','70%','80%','90%','100%']) plt.plot(range(300), prob_Q_A_left, '-',label='Q Learning') plt.plot(range(300), prob_E_A_left, '-',label='Double Q-Learning') plt.plot(range(300), prob_AD_A_left, '-',label='Action Distribution') plt.plot(range(300), prob_Q2_A_left, '-',label='Expected Sarsa') plt.plot(np.ones(300) * 0.05, label='Optimal') plt.title('Comparison of the effect of 4 algorithms on Ex 6.7') plt.legend() plt.grid() plt.show() plt.close() total_num = 1000 A_Q_lst, B_Q_lst = np.zeros( (total_num, 300) ) ,np.zeros( (total_num, 300) ) A_Q2_lst, B_Q2_lst = np.zeros( (total_num, 300) ) ,np.zeros( (total_num, 300) ) A_AD_lst, B_AD_lst = np.zeros( (total_num, 300) ) ,np.zeros( (total_num, 300) ) A_E_lst, B_E_lst = np.zeros( (total_num, 300) ) ,np.zeros( (total_num, 300) ) prob_Q_A_left = np.zeros( (total_num, 300) ) prob_Q2_A_left = np.zeros( (total_num, 300) ) prob_AD_A_left = np.zeros( (total_num, 300) ) prob_E_A_left = np.zeros( (total_num, 300) ) # 计算在STATE_A下采样动作left的概率 alpha = 0.1 start_epsilon = 0.1 gamma = 0.9 num_of_episode = 300 for num in tqdm(range(total_num)): _, A_left1, A_Q1, B_Q1 = TD_learning(env, 'Q-Learning', alpha, epsilon_scope=[start_epsilon,0.05,1], num_of_episode=num_of_episode, gamma=gamma) _, A_left2, A_Q2, B_Q2 = TD_learning(env, 'Double-Q', alpha, epsilon_scope=[start_epsilon,0.05,1], num_of_episode=num_of_episode, gamma=gamma) _, A_left3, A_Q3, B_Q3 = TD_learning(env, 'Action_Distribution', alpha, epsilon_scope=[start_epsilon,0.05,1], num_of_episode=num_of_episode, gamma=gamma) _, A_left4, A_Q4, B_Q4 = TD_learning(env, 'Expected_Sarsa', alpha, epsilon_scope=[start_epsilon,0.05,1], num_of_episode=num_of_episode, gamma=gamma) prob_Q_A_left[int(num)] = A_left1 prob_Q2_A_left[int(num)] = A_left2 prob_AD_A_left[int(num)] = A_left3 prob_E_A_left[int(num)] = A_left4 A_Q_lst[int(num)], B_Q_lst[int(num)] = A_Q1, B_Q1 A_Q2_lst[int(num)], B_Q2_lst[int(num)] = A_Q2, B_Q2 A_AD_lst[int(num)], B_AD_lst[int(num)] = A_Q3, B_Q3 A_E_lst[int(num)], B_E_lst[int(num)] = A_Q4, B_Q4 a = prob_Q_A_left.mean(axis=0) b = prob_Q2_A_left.mean(axis=0) c = prob_AD_A_left.mean(axis=0) d = prob_E_A_left.mean(axis=0) show_figure(a, b, c, d) ###Output 100%|██████████| 1000/1000 [00:09<00:00, 107.57it/s]
experimental/widgets/2_Widget List.ipynb
###Markdown [Index](Index.ipynb) - [Back](Widget Basics.ipynb) - [Next](Output Widget.ipynb) Widget List ###Code import ipywidgets as widgets ###Output _____no_output_____ ###Markdown Numeric widgets There are many widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing `Float` with `Int` in the widget name, you can find the Integer equivalent. IntSlider ###Code widgets.IntSlider( value=7, min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) ###Output _____no_output_____ ###Markdown FloatSlider ###Code widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) ###Output _____no_output_____ ###Markdown Sliders can also be **displayed vertically**. ###Code widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.1f', ) ###Output _____no_output_____ ###Markdown FloatLogSlider The `FloatLogSlider` has a log scale, which makes it easy to have a slider that covers a wide range of positive magnitudes. The `min` and `max` refer to the minimum and maximum exponents of the base, and the `value` refers to the actual value of the slider. ###Code widgets.FloatLogSlider( value=10, base=10, min=-10, # max exponent of base max=10, # min exponent of base step=0.2, # exponent step description='Log Slider' ) ###Output _____no_output_____ ###Markdown IntRangeSlider ###Code widgets.IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) ###Output _____no_output_____ ###Markdown FloatRangeSlider ###Code widgets.FloatRangeSlider( value=[5, 7.5], min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) ###Output _____no_output_____ ###Markdown IntProgress ###Code widgets.IntProgress( value=7, min=0, max=10, step=1, description='Loading:', bar_style='', # 'success', 'info', 'warning', 'danger' or '' orientation='horizontal' ) ###Output _____no_output_____ ###Markdown FloatProgress ###Code widgets.FloatProgress( value=7.5, min=0, max=10.0, step=0.1, description='Loading:', bar_style='info', orientation='horizontal' ) ###Output _____no_output_____ ###Markdown The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter. BoundedIntText ###Code widgets.BoundedIntText( value=7, min=0, max=10, step=1, description='Text:', disabled=False ) ###Output _____no_output_____ ###Markdown BoundedFloatText ###Code widgets.BoundedFloatText( value=7.5, min=0, max=10.0, step=0.1, description='Text:', disabled=False ) ###Output _____no_output_____ ###Markdown IntText ###Code widgets.IntText( value=7, description='Any:', disabled=False ) ###Output _____no_output_____ ###Markdown FloatText ###Code widgets.FloatText( value=7.5, description='Any:', disabled=False ) ###Output _____no_output_____ ###Markdown Boolean widgets There are three widgets that are designed to display a boolean value. ToggleButton ###Code widgets.ToggleButton( value=False, description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='check' ) ###Output _____no_output_____ ###Markdown Checkbox ###Code widgets.Checkbox( value=False, description='Check me', disabled=False ) ###Output _____no_output_____ ###Markdown ValidThe valid widget provides a read-only indicator. ###Code widgets.Valid( value=False, description='Valid!', ) ###Output _____no_output_____ ###Markdown Selection widgets There are several widgets that can be used to display single selection lists, and two that can be used to select multiple values. All inherit from the same base class. You can specify the **enumeration of selectable options by passing a list** (options are either (label, value) pairs, or simply values for which the labels are derived by calling `str`). Dropdown ###Code widgets.Dropdown( options=['1', '2', '3'], value='2', description='Number:', disabled=False, ) ###Output _____no_output_____ ###Markdown RadioButtons ###Code widgets.RadioButtons( options=['pepperoni', 'pineapple', 'anchovies'], # value='pineapple', description='Pizza topping:', disabled=False ) ###Output _____no_output_____ ###Markdown Select ###Code widgets.Select( options=['Linux', 'Windows', 'OSX'], value='OSX', # rows=10, description='OS:', disabled=False ) ###Output _____no_output_____ ###Markdown SelectionSlider ###Code widgets.SelectionSlider( options=['scrambled', 'sunny side up', 'poached', 'over easy'], value='sunny side up', description='I like my eggs ...', disabled=False, continuous_update=False, orientation='horizontal', readout=True ) ###Output _____no_output_____ ###Markdown SelectionRangeSliderThe value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty. ###Code import datetime dates = [datetime.date(2015,i,1) for i in range(1,13)] options = [(i.strftime('%b'), i) for i in dates] widgets.SelectionRangeSlider( options=options, index=(0,11), description='Months (2015)', disabled=False ) ###Output _____no_output_____ ###Markdown ToggleButtons ###Code widgets.ToggleButtons( options=['Slow', 'Regular', 'Fast'], description='Speed:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Description of slow', 'Description of regular', 'Description of fast'], # icons=['check'] * 3 ) ###Output _____no_output_____ ###Markdown SelectMultipleMultiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys. ###Code widgets.SelectMultiple( options=['Apples', 'Oranges', 'Pears'], value=['Oranges'], #rows=10, description='Fruits', disabled=False ) ###Output _____no_output_____ ###Markdown String widgets There are several widgets that can be used to display a string value. The `Text` and `Textarea` widgets accept input. The `HTML` and `HTMLMath` widgets display a string as HTML (`HTMLMath` also renders math). The `Label` widget can be used to construct a custom control label. Text ###Code widgets.Text( value='Hello World', placeholder='Type something', description='String:', disabled=False ) ###Output _____no_output_____ ###Markdown Textarea ###Code widgets.Textarea( value='Hello World', placeholder='Type something', description='String:', disabled=False ) ###Output _____no_output_____ ###Markdown LabelThe `Label` widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions. ###Code widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()]) ###Output _____no_output_____ ###Markdown HTML ###Code widgets.HTML( value="Hello <b>World</b>", placeholder='Some HTML', description='Some HTML', ) ###Output _____no_output_____ ###Markdown HTML Math ###Code widgets.HTMLMath( value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$", placeholder='Some HTML', description='Some HTML', ) ###Output _____no_output_____ ###Markdown Image ###Code file = open("images/WidgetArch.png", "rb") image = file.read() widgets.Image( value=image, format='png', width=300, height=400, ) ###Output _____no_output_____ ###Markdown Button ###Code widgets.Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check' ) ###Output _____no_output_____ ###Markdown OutputThe `Output` widget can capture and display stdout, stderr and [rich output generated by IPython](http://ipython.readthedocs.io/en/stable/api/generated/IPython.display.htmlmodule-IPython.display). For detailed documentation, see the [output widget examples](https://ipywidgets.readthedocs.io/en/latest/examples/Output Widget.html). Play (Animation) widget The `Play` widget is useful to perform animations by iterating on a sequence of integers with a certain speed. The value of the slider below is linked to the player. ###Code play = widgets.Play( # interval=10, value=50, min=0, max=100, step=1, description="Press play", disabled=False ) slider = widgets.IntSlider() widgets.jslink((play, 'value'), (slider, 'value')) widgets.HBox([play, slider]) ###Output _____no_output_____ ###Markdown Date pickerThe date picker widget works in Chrome, Firefox and IE Edge, but does not currently work in Safari because it does not support the HTML date input field. ###Code widgets.DatePicker( description='Pick a Date', disabled=False ) ###Output _____no_output_____ ###Markdown Color picker ###Code widgets.ColorPicker( concise=False, description='Pick a color', value='blue', disabled=False ) ###Output _____no_output_____ ###Markdown ControllerThe `Controller` allows a game controller to be used as an input device. ###Code widgets.Controller( index=0, ) ###Output _____no_output_____ ###Markdown Container/Layout widgetsThese widgets are used to hold other widgets, called children. Each has a `children` property that may be set either when the widget is created or later. Box ###Code items = [widgets.Label(str(i)) for i in range(4)] widgets.Box(items) ###Output _____no_output_____ ###Markdown HBox ###Code items = [widgets.Label(str(i)) for i in range(4)] widgets.HBox(items) ###Output _____no_output_____ ###Markdown VBox ###Code items = [widgets.Label(str(i)) for i in range(4)] left_box = widgets.VBox([items[0], items[1]]) right_box = widgets.VBox([items[2], items[3]]) widgets.HBox([left_box, right_box]) ###Output _____no_output_____ ###Markdown Accordion ###Code accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()]) accordion.set_title(0, 'Slider') accordion.set_title(1, 'Text') accordion ###Output _____no_output_____ ###Markdown TabsIn this example the children are set after the tab is created. Titles for the tabes are set in the same way they are for `Accordion`. ###Code tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4'] children = [widgets.Text(description=name) for name in tab_contents] tab = widgets.Tab() tab.children = children for i in range(len(children)): tab.set_title(i, str(i)) tab ###Output _____no_output_____ ###Markdown Accordion and Tab use `selected_index`, not valueUnlike the rest of the widgets discussed earlier, the container widgets `Accordion` and `Tab` update their `selected_index` attribute when the user changes which accordion or tab is selected. That means that you can both see what the user is doing *and* programmatically set what the user sees by setting the value of `selected_index`.Setting `selected_index = None` closes all of the accordions or deselects all tabs. In the cells below try displaying or setting the `selected_index` of the `tab` and/or `accordion`. ###Code tab.selected_index = 3 accordion.selected_index = None ###Output _____no_output_____ ###Markdown Nesting tabs and accordionsTabs and accordions can be nested as deeply as you want. If you have a few minutes, try nesting a few accordions or putting an accordion inside a tab or a tab inside an accordion. The example below makes a couple of tabs with an accordion children in one of them ###Code tab_nest = widgets.Tab() tab_nest.children = [accordion, accordion] tab_nest.set_title(0, 'An accordion') tab_nest.set_title(1, 'Copy of the accordion') tab_nest ###Output _____no_output_____
docs/source/notebooks/two_knife_edges.ipynb
###Markdown Double knife-edge diffractionexample [Vavilov S. A., Lytaev M. S. Modeling Equation for Multiple Knife-Edge Diffraction//IEEE Transactions on Antennas and Propagation. – 2020. – Vol. 68. – Iss. 5. – pp. 3869-3877.](https://doi.org/10.1109/TAP.2019.2957085) ###Code import os os.chdir('../../') from rwp.kediffraction import * from rwp.antennas import * from rwp.environment import * from rwp.vis import * ###Output _____no_output_____ ###Markdown Preparing environment ###Code env = Troposphere(flat=True) env.z_max = 150 env.knife_edges = [KnifeEdge(range=200, height=50), KnifeEdge(range=800, height=50)] antenna = GaussAntenna(freq_hz=300e6, height=50, beam_width=15, eval_angle=0, polarz='H') ###Output _____no_output_____ ###Markdown Starting calculation ###Code kdc = KnifeEdgeDiffractionCalculator(src=antenna, env=env, max_range_m=1000) field = kdc.calculate() ###Output _____no_output_____ ###Markdown Visualising results ###Code vis = FieldVisualiser(field, env=env, trans_func=lambda v: 10 * cm.log10(1e-16 + abs(v)), label='ke') plt = vis.plot2d(min=-40, max=0) plt.title('The intensity of the field component 10log10|u|') plt.xlabel('Range (m)') plt.ylabel('Height (m)') plt.show() plt = vis.plot_hor(51) plt.title('The intensity of the field component 10log10|u| at the height 51 m') plt.xlabel('Range (m)') plt.ylabel('10log|u| (dB)') plt.show() ###Output _____no_output_____
4_channelomics/07_build_figure_supplement.ipynb
###Markdown Figures for supplement Histograms summarizing fits ###Code import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pickle %matplotlib inline import sys; sys.path.append('../') from common import col, svg !mkdir -p svg/ nfidxs = pickle.load(open('results/net_maf/idxs.pkl', 'rb')) nfccs = np.asarray(pickle.load(open('results/net_maf/ccs.pkl', 'rb'))) mfidxs = pickle.load(open('results/manual_fit/idxs.pkl', 'rb')) mfccs = np.asarray(pickle.load(open('results/manual_fit/ccs.pkl', 'rb'))) # We exclude CCs smaller than 0.9 since those models are outliers and the problem # is with the modfiles rather than with inference/fitting. cutoff = 0.9 nfidxs_valid = np.asarray(nfidxs)[np.argwhere(nfccs > cutoff).reshape(-1)] nfccs_valid = nfccs[np.argwhere(nfccs > cutoff).reshape(-1)] nfidxs_valid_sorted = nfidxs_valid[np.argsort(nfccs_valid).reshape(-1)] nfccs_valid_sorted = nfccs_valid[np.argsort(nfccs_valid).reshape(-1)] mfidxs_valid = np.asarray(mfidxs)[np.argwhere(mfccs > cutoff).reshape(-1)] mfccs_valid = mfccs[np.argwhere(mfccs > cutoff).reshape(-1)] mfidxs_valid_sorted = mfidxs_valid[np.argsort(mfccs_valid).reshape(-1)] mfccs_valid_sorted = mfccs_valid[np.argsort(mfccs_valid).reshape(-1)] ccs_combined = np.empty((373, 2)) ccs_combined[nfidxs_valid,0] = nfccs_valid ccs_combined[mfidxs_valid,1] = mfccs_valid with mpl.rc_context(fname='../.matplotlibrc'): plt.figure(figsize=(10/2.54, 8/2.54)) plt.hist(ccs_combined, bins=np.linspace(0.9, 1.0, 11), color=[col['SNPE'], col['MCMC']], label=['posterior mode', 'curve fitting'], fill=False, histtype='step', density=False, linewidth=1.5, clip_on=False) plt.ylim([0, 350]) plt.legend(loc='upper left', frameon=False, title='Parameters via') sns.despine(offset=10, trim=True) plt.xticks(np.linspace(0.9, 1.0, 5)) plt.ylabel('# models') plt.xlabel('CC between observation and prediction') PANEL_CCS = 'fig/fig4_channelomics_supp_hists.svg' plt.savefig(PANEL_CCS, transparent=True) plt.close() svg(PANEL_CCS) ###Output _____no_output_____
queue_imbalance/logistic_regression/queue_imbalance-9065.ipynb
###Markdown Testing of queue imbalance for stock 9095Order of this notebook is as follows:1. [Data](Data)2. [Data visualization](Data-visualization)3. [Tests](Tests)4. [Conclusions](Conclusions)Goal is to implement queue imbalance predictor from [[1]](Resources). ###Code %matplotlib inline import warnings import matplotlib.dates as md import matplotlib.pyplot as plt import seaborn as sns from lob_data_utils import lob from sklearn.metrics import roc_curve, roc_auc_score warnings.filterwarnings('ignore') ###Output _____no_output_____ ###Markdown DataMarket is open between 8-16 on every weekday. We decided to use data from only 9-15 for each day. Test and train dataFor training data we used data from 2013-09-01 - 2013-11-16:* 0916* 1001* 1016* 1101The data from 09-01 is the test data. ###Code df, df_test = lob.load_prepared_data('9065', data_dir='../data/prepared/', length=None) df.head() ###Output Training set length for 9065: 10320 Testing set length for 9065: 3810 ###Markdown Data visualization ###Code df['sum_buy_bid'].plot(label='total size of buy orders', style='--') df['sum_sell_ask'].plot(label='total size of sell orders', style='-') plt.title('Summed volumens for ask and bid lists') plt.xlabel('Time') plt.ylabel('Whole volume') plt.legend() df[['bid_price', 'ask_price', 'mid_price']].plot(style='.') plt.legend() plt.title('Prices') plt.xlabel('Time') plt.ylabel('Price') sns.jointplot(x="mid_price", y="queue_imbalance", data=df.loc[:, ['mid_price', 'queue_imbalance']], kind="kde") plt.title('Density') plt.plot() df['mid_price_indicator'].plot('kde') plt.legend() plt.xlabel('Mid price indicator') plt.title('Mid price indicator density') df['queue_imbalance'].plot('kde') plt.legend() plt.xlabel('Queue imbalance') plt.title('Queue imbalance density') ###Output _____no_output_____ ###Markdown TestsWe use logistic regression to predict `mid_price_indicator`. Mean square error We calculate residual $r_i$:$$ r_i = \hat{y_i} - y_i $$where $$ \hat{y}(I) = \frac{1}{1 + e^{-(x_0 + Ix_1 )}}$$Calculating mean square residual for all observations in the testing set is also useful to assess the predictive power.The predective power of null-model is 25%. ###Code reg = lob.logistic_regression(df, 0, len(df)) probabilities = reg.predict_proba(df_test['queue_imbalance'].values.reshape(-1,1)) probabilities = [p1 for p0, p1 in probabilities] err = ((df_test['mid_price_indicator'] - probabilities) ** 2).mean() predictions = reg.predict(df_test['queue_imbalance'].values.reshape(-1, 1)) print('Mean square error is', err) ###Output Mean square error is 0.24600292829391873 ###Markdown Logistic regression fit curve ###Code plt.plot(df_test['queue_imbalance'].values, lob.sigmoid(reg.coef_[0] * df_test['queue_imbalance'].values + reg.intercept_)) plt.title('Logistic regression fit curve') plt.xlabel('Imbalance') plt.ylabel('Probability') ###Output _____no_output_____ ###Markdown ROC curveFor assessing the predectivity power we can calculate ROC score. ###Code a, b, c = roc_curve(df_test['mid_price_indicator'], predictions) logit_roc_auc = roc_auc_score(df_test['mid_price_indicator'], predictions) plt.plot(a, b, label='predictions (area {})'.format(logit_roc_auc)) plt.plot([0, 1], [0, 1], color='navy', linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend() st = 0 end = len(df) plt.plot(df_test.index[st:end], predictions[st:end], 'ro', label='prediction') plt.plot(df_test.index[st:end], probabilities[st:end], 'g.', label='probability') plt.plot(df_test.index[st:end], df_test['mid_price_indicator'].values[st:end], 'b.', label='mid price') plt.xticks(rotation=25) plt.legend(loc=1) plt.xlabel('Time') plt.ylabel('Mid price prediction') ###Output _____no_output_____
samples/dynamic_shapes/dynamic_shapes.ipynb
###Markdown Copyright 2021 The IREE Authors ###Code #@title Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ###Output _____no_output_____ ###Markdown Dynamic ShapesThis notebook1. Creates a TensorFlow program with dynamic shapes2. Imports that program into IREE's compiler3. Compiles the imported program to an IREE VM bytecode module4. Tests running the compiled VM module using IREE's runtime5. Downloads compilation artifacts for use with the native (C API) sample application ###Code #@title General setup import os import tempfile ARTIFACTS_DIR = os.path.join(tempfile.gettempdir(), "iree", "colab_artifacts") os.makedirs(ARTIFACTS_DIR, exist_ok=True) print(f"Using artifacts directory '{ARTIFACTS_DIR}'") ###Output Using artifacts directory '/tmp/iree/colab_artifacts' ###Markdown Create a program using TensorFlow and import it into IREENOTE: as in other domains, providing more information to a compiler allows itto generate more efficient code. As a general rule, the slowest varyingdimensions of program data like batch index or timestep are safer to treat asdynamic than faster varying dimensions like image x/y/channel. See[this paper](https://arxiv.org/pdf/2006.03031.pdf) for a discussion of thechallenges imposed by dynamic shapes and one project's approach to addressingthem. ###Code #@title Define a sample TensorFlow module using dynamic shapes import tensorflow as tf class DynamicShapesModule(tf.Module): # reduce_sum_1d (dynamic input size, static output size) # e.g. [1, 2, 3] -> 6 @tf.function(input_signature=[tf.TensorSpec([None], tf.int32)]) def reduce_sum_1d(self, values): return tf.math.reduce_sum(values) # reduce_sum_2d (partially dynamic input size, static output size) # e.g. [[1, 2, 3], [10, 20, 30]] -> [11, 22, 33] @tf.function(input_signature=[tf.TensorSpec([None, 3], tf.int32)]) def reduce_sum_2d(self, values): return tf.math.reduce_sum(values, 0) # add_one (dynamic input size, dynamic output size) # e.g. [1, 2, 3] -> [2, 3, 4] @tf.function(input_signature=[tf.TensorSpec([None], tf.int32)]) def add_one(self, values): return tf.math.add(values, tf.constant(1, dtype=tf.int32)) %%capture !python -m pip install iree-compiler iree-tools-tf -f https://github.com/google/iree/releases #@title Import the TensorFlow program into IREE as MLIR from IPython.display import clear_output from iree.compiler import tf as tfc compiler_module = tfc.compile_module( DynamicShapesModule(), import_only=True, output_mlir_debuginfo=False) clear_output() # Skip over TensorFlow's output. # Print the imported MLIR to see how the compiler views this program. print("Dynamic Shapes MLIR:\n```\n%s```\n" % compiler_module.decode("utf-8")) # Save the imported MLIR to disk. imported_mlir_path = os.path.join(ARTIFACTS_DIR, "dynamic_shapes.mlir") with open(imported_mlir_path, "wt") as output_file: output_file.write(compiler_module.decode("utf-8")) print(f"Wrote MLIR to path '{imported_mlir_path}'") ###Output Dynamic Shapes MLIR: ``` "builtin.module"() ( { "builtin.func"() ( { ^bb0(%arg0: !iree_input.buffer_view): // no predecessors %0 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?xi32> %1 = "std.call"(%0) {callee = @__inference_add_one_70} : (tensor<?xi32>) -> tensor<?xi32> %2 = "iree_input.cast.tensor_to_buffer_view"(%1) : (tensor<?xi32>) -> !iree_input.buffer_view "std.return"(%2) : (!iree_input.buffer_view) -> () }) {iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,1,null]],\22r\22:[[\22ndarray\22,\22i32\22,1,null]],\22v\22:1}", sym_name = "add_one", type = (!iree_input.buffer_view) -> !iree_input.buffer_view} : () -> () "builtin.func"() ( { ^bb0(%arg0: tensor<?xi32>): // no predecessors %0 = "mhlo.constant"() {value = dense<1> : tensor<i32>} : () -> tensor<i32> %1 = "chlo.broadcast_add"(%arg0, %0) {broadcast_dimensions = dense<> : tensor<0xi64>} : (tensor<?xi32>, tensor<i32>) -> tensor<?xi32> "std.return"(%1) : (tensor<?xi32>) -> () }) {arg_attrs = [{tf._user_specified_name = "values"}], sym_name = "__inference_add_one_70", sym_visibility = "private", tf._construction_context = "kEagerRuntime", tf._input_shapes = [#tf_type.shape<?>], type = (tensor<?xi32>) -> tensor<?xi32>} : () -> () "builtin.func"() ( { ^bb0(%arg0: !iree_input.buffer_view): // no predecessors %0 = "mhlo.constant"() {value = dense<0> : tensor<i32>} : () -> tensor<i32> %1 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?xi32> %2 = "mhlo.reduce"(%1, %0) ( { ^bb0(%arg1: tensor<i32>, %arg2: tensor<i32>): // no predecessors %4 = "mhlo.add"(%arg1, %arg2) : (tensor<i32>, tensor<i32>) -> tensor<i32> "mhlo.return"(%4) : (tensor<i32>) -> () }) {dimensions = dense<0> : tensor<1xi64>} : (tensor<?xi32>, tensor<i32>) -> tensor<i32> %3 = "iree_input.cast.tensor_to_buffer_view"(%2) : (tensor<i32>) -> !iree_input.buffer_view "std.return"(%3) : (!iree_input.buffer_view) -> () }) {iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,1,null]],\22r\22:[[\22ndarray\22,\22i32\22,0]],\22v\22:1}", sym_name = "reduce_sum_1d", type = (!iree_input.buffer_view) -> !iree_input.buffer_view} : () -> () "builtin.func"() ( { ^bb0(%arg0: !iree_input.buffer_view): // no predecessors %0 = "mhlo.constant"() {value = dense<0> : tensor<i32>} : () -> tensor<i32> %1 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?x3xi32> %2 = "mhlo.reduce"(%1, %0) ( { ^bb0(%arg1: tensor<i32>, %arg2: tensor<i32>): // no predecessors %4 = "mhlo.add"(%arg1, %arg2) : (tensor<i32>, tensor<i32>) -> tensor<i32> "mhlo.return"(%4) : (tensor<i32>) -> () }) {dimensions = dense<0> : tensor<1xi64>} : (tensor<?x3xi32>, tensor<i32>) -> tensor<3xi32> %3 = "iree_input.cast.tensor_to_buffer_view"(%2) : (tensor<3xi32>) -> !iree_input.buffer_view "std.return"(%3) : (!iree_input.buffer_view) -> () }) {iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,2,null,3]],\22r\22:[[\22ndarray\22,\22i32\22,1,3]],\22v\22:1}", sym_name = "reduce_sum_2d", type = (!iree_input.buffer_view) -> !iree_input.buffer_view} : () -> () }) : () -> () ``` Wrote MLIR to path '/tmp/iree/colab_artifacts/dynamic_shapes.mlir' ###Markdown Test the imported program_Note: you can stop after each step and use intermediate outputs with other tools outside of Colab.__See the [README](https://github.com/google/iree/tree/main/iree/samples/dynamic_shapesinstructions) for more details and example command line instructions._* _The "imported MLIR" can be used by IREE's generic compiler tools_* _The "flatbuffer blob" can be saved and used by runtime applications__The specific point at which you switch from Python to native tools will depend on your project._ ###Code %%capture !python -m pip install iree-compiler -f https://github.com/google/iree/releases #@title Compile the imported MLIR further into an IREE VM bytecode module from iree.compiler import compile_str # Note: we'll use the dylib-llvm-aot backend since it has the best support # for dynamic shapes among our compiler targets. flatbuffer_blob = compile_str(compiler_module, target_backends=["dylib-llvm-aot"], input_type="mhlo") # Note: the dylib-llvm-aot target produces platform-specific code. Since you # may need to recompile it yourself using the appropriate # `-iree-llvm-target-triple` flag, we skip saving it to disk and downloading it. %%capture !python -m pip install iree-runtime -f https://github.com/google/iree/releases #@title Test running the compiled VM module using IREE's runtime from iree import runtime as ireert vm_module = ireert.VmModule.from_flatbuffer(flatbuffer_blob) config = ireert.Config("dylib") ctx = ireert.SystemContext(config=config) ctx.add_vm_module(vm_module) import numpy as np # Our @tf.functions are accessible by name on the module named 'module' dynamic_shapes_program = ctx.modules.module print(dynamic_shapes_program.reduce_sum_1d(np.array([1, 10, 100], dtype=np.int32))) print(dynamic_shapes_program.reduce_sum_2d(np.array([[1, 2, 3], [10, 20, 30]], dtype=np.int32))) print(dynamic_shapes_program.reduce_sum_2d(np.array([[1, 2, 3], [10, 20, 30], [100, 200, 300]], dtype=np.int32))) print(dynamic_shapes_program.add_one(np.array([1, 10, 100], dtype=np.int32))) ###Output 111 [11 22 33] [111 222 333] [ 2 11 101] ###Markdown Download compilation artifacts ###Code ARTIFACTS_ZIP = "/tmp/dynamic_shapes_colab_artifacts.zip" print(f"Zipping '{ARTIFACTS_DIR}' to '{ARTIFACTS_ZIP}' for download...") !cd {ARTIFACTS_DIR} && zip -r {ARTIFACTS_ZIP} . # Note: you can also download files using Colab's file explorer try: from google.colab import files print("Downloading the artifacts zip file...") files.download(ARTIFACTS_ZIP) except ImportError: print("Missing google_colab Python package, can't download files") ###Output Zipping '/tmp/iree/colab_artifacts' to '/tmp/dynamic_shapes_colab_artifacts.zip' for download... adding: dynamic_shapes.mlir (deflated 80%) Downloading the artifacts zip file... ###Markdown Copyright 2021 The IREE Authors ###Code #@title Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ###Output _____no_output_____ ###Markdown Dynamic ShapesThis notebook1. Creates a TensorFlow program with dynamic shapes2. Imports that program into IREE's compiler3. Compiles the imported program to an IREE VM bytecode module4. Tests running the compiled VM module using IREE's runtime5. Downloads compilation artifacts for use with the native (C API) sample application ###Code #@title General setup import os import tempfile ARTIFACTS_DIR = os.path.join(tempfile.gettempdir(), "iree", "colab_artifacts") os.makedirs(ARTIFACTS_DIR, exist_ok=True) print(f"Using artifacts directory '{ARTIFACTS_DIR}'") ###Output Using artifacts directory '/tmp/iree/colab_artifacts' ###Markdown Create a program using TensorFlow and import it into IREENOTE: as in other domains, providing more information to a compiler allows itto generate more efficient code. As a general rule, the slowest varyingdimensions of program data like batch index or timestep are safer to treat asdynamic than faster varying dimensions like image x/y/channel. See[this paper](https://arxiv.org/pdf/2006.03031.pdf) for a discussion of thechallenges imposed by dynamic shapes and one project's approach to addressingthem. ###Code #@title Define a sample TensorFlow module using dynamic shapes import tensorflow as tf class DynamicShapesModule(tf.Module): # reduce_sum_1d (dynamic input size, static output size) # e.g. [1, 2, 3] -> 6 @tf.function(input_signature=[tf.TensorSpec([None], tf.int32)]) def reduce_sum_1d(self, values): return tf.math.reduce_sum(values) # reduce_sum_2d (partially dynamic input size, static output size) # e.g. [[1, 2, 3], [10, 20, 30]] -> [11, 22, 33] @tf.function(input_signature=[tf.TensorSpec([None, 3], tf.int32)]) def reduce_sum_2d(self, values): return tf.math.reduce_sum(values, 0) # add_one (dynamic input size, dynamic output size) # e.g. [1, 2, 3] -> [2, 3, 4] @tf.function(input_signature=[tf.TensorSpec([None], tf.int32)]) def add_one(self, values): return tf.math.add(values, tf.constant(1, dtype=tf.int32)) %%capture !python -m pip install iree-compiler iree-tools-tf -f https://github.com/google/iree/releases #@title Import the TensorFlow program into IREE as MLIR from IPython.display import clear_output from iree.compiler import tf as tfc compiler_module = tfc.compile_module( DynamicShapesModule(), import_only=True, output_mlir_debuginfo=False) clear_output() # Skip over TensorFlow's output. # Print the imported MLIR to see how the compiler views this program. print("Dynamic Shapes MLIR:\n```\n%s```\n" % compiler_module.decode("utf-8")) # Save the imported MLIR to disk. imported_mlir_path = os.path.join(ARTIFACTS_DIR, "dynamic_shapes.mlir") with open(imported_mlir_path, "wt") as output_file: output_file.write(compiler_module.decode("utf-8")) print(f"Wrote MLIR to path '{imported_mlir_path}'") ###Output Dynamic Shapes MLIR: ``` "builtin.module"() ({ "func.func"() ({ ^bb0(%arg0: !iree_input.buffer_view): %0 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?xi32> %1 = "func.call"(%0) {callee = @__inference_add_one_70} : (tensor<?xi32>) -> tensor<?xi32> %2 = "iree_input.cast.tensor_to_buffer_view"(%1) : (tensor<?xi32>) -> !iree_input.buffer_view "func.return"(%2) : (!iree_input.buffer_view) -> () }) {function_type = (!iree_input.buffer_view) -> !iree_input.buffer_view, iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,1,null]],\22r\22:[[\22ndarray\22,\22i32\22,1,null]],\22v\22:1}", sym_name = "add_one"} : () -> () "func.func"() ({ ^bb0(%arg0: tensor<?xi32>): %0 = "mhlo.constant"() {value = dense<1> : tensor<i32>} : () -> tensor<i32> %1 = "chlo.broadcast_add"(%arg0, %0) {broadcast_dimensions = dense<> : tensor<0xi64>} : (tensor<?xi32>, tensor<i32>) -> tensor<?xi32> "func.return"(%1) : (tensor<?xi32>) -> () }) {arg_attrs = [{tf._user_specified_name = "values"}], function_type = (tensor<?xi32>) -> tensor<?xi32>, sym_name = "__inference_add_one_70", sym_visibility = "private", tf._construction_context = "kEagerRuntime", tf._input_shapes = [#tf_type.shape<?>]} : () -> () "func.func"() ({ ^bb0(%arg0: !iree_input.buffer_view): %0 = "mhlo.constant"() {value = dense<0> : tensor<i32>} : () -> tensor<i32> %1 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?xi32> %2 = "mhlo.reduce"(%1, %0) ({ ^bb0(%arg1: tensor<i32>, %arg2: tensor<i32>): %4 = "mhlo.add"(%arg1, %arg2) : (tensor<i32>, tensor<i32>) -> tensor<i32> "mhlo.return"(%4) : (tensor<i32>) -> () }) {dimensions = dense<0> : tensor<1xi64>} : (tensor<?xi32>, tensor<i32>) -> tensor<i32> %3 = "iree_input.cast.tensor_to_buffer_view"(%2) : (tensor<i32>) -> !iree_input.buffer_view "func.return"(%3) : (!iree_input.buffer_view) -> () }) {function_type = (!iree_input.buffer_view) -> !iree_input.buffer_view, iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,1,null]],\22r\22:[[\22ndarray\22,\22i32\22,0]],\22v\22:1}", sym_name = "reduce_sum_1d"} : () -> () "func.func"() ({ ^bb0(%arg0: !iree_input.buffer_view): %0 = "mhlo.constant"() {value = dense<0> : tensor<i32>} : () -> tensor<i32> %1 = "iree_input.cast.buffer_view_to_tensor"(%arg0) : (!iree_input.buffer_view) -> tensor<?x3xi32> %2 = "mhlo.reduce"(%1, %0) ({ ^bb0(%arg1: tensor<i32>, %arg2: tensor<i32>): %4 = "mhlo.add"(%arg1, %arg2) : (tensor<i32>, tensor<i32>) -> tensor<i32> "mhlo.return"(%4) : (tensor<i32>) -> () }) {dimensions = dense<0> : tensor<1xi64>} : (tensor<?x3xi32>, tensor<i32>) -> tensor<3xi32> %3 = "iree_input.cast.tensor_to_buffer_view"(%2) : (tensor<3xi32>) -> !iree_input.buffer_view "func.return"(%3) : (!iree_input.buffer_view) -> () }) {function_type = (!iree_input.buffer_view) -> !iree_input.buffer_view, iree.abi = "{\22a\22:[[\22ndarray\22,\22i32\22,2,null,3]],\22r\22:[[\22ndarray\22,\22i32\22,1,3]],\22v\22:1}", sym_name = "reduce_sum_2d"} : () -> () }) : () -> () ``` Wrote MLIR to path '/tmp/iree/colab_artifacts/dynamic_shapes.mlir' ###Markdown Test the imported program_Note: you can stop after each step and use intermediate outputs with other tools outside of Colab.__See the [README](https://github.com/google/iree/tree/main/iree/samples/dynamic_shapesinstructions) for more details and example command line instructions._* _The "imported MLIR" can be used by IREE's generic compiler tools_* _The "flatbuffer blob" can be saved and used by runtime applications__The specific point at which you switch from Python to native tools will depend on your project._ ###Code %%capture !python -m pip install iree-compiler -f https://github.com/google/iree/releases #@title Compile the imported MLIR further into an IREE VM bytecode module from iree.compiler import compile_str # Note: we'll use the cpu (LLVM) backend since it has the best support # for dynamic shapes among our compiler targets. flatbuffer_blob = compile_str(compiler_module, target_backends=["cpu"], input_type="mhlo") # Save the compiled program to disk. flatbuffer_path = os.path.join(ARTIFACTS_DIR, "dynamic_shapes_cpu.vmfb") with open(flatbuffer_path, "wb") as output_file: output_file.write(flatbuffer_blob) print(f"Wrote compiled program to path '{flatbuffer_path}'") %%capture !python -m pip install iree-runtime -f https://github.com/google/iree/releases #@title Test running the compiled VM module using IREE's runtime from iree import runtime as ireert vm_module = ireert.VmModule.from_flatbuffer(flatbuffer_blob) config = ireert.Config("local-task") ctx = ireert.SystemContext(config=config) ctx.add_vm_module(vm_module) import numpy as np # Our @tf.functions are accessible by name on the module named 'module' dynamic_shapes_program = ctx.modules.module print(dynamic_shapes_program.reduce_sum_1d(np.array([1, 10, 100], dtype=np.int32)).to_host()) print(dynamic_shapes_program.reduce_sum_2d(np.array([[1, 2, 3], [10, 20, 30]], dtype=np.int32)).to_host()) print(dynamic_shapes_program.reduce_sum_2d(np.array([[1, 2, 3], [10, 20, 30], [100, 200, 300]], dtype=np.int32)).to_host()) print(dynamic_shapes_program.add_one(np.array([1, 10, 100], dtype=np.int32)).to_host()) ###Output 111 [11 22 33] [111 222 333] [ 2 11 101] ###Markdown Download compilation artifacts ###Code ARTIFACTS_ZIP = "/tmp/dynamic_shapes_colab_artifacts.zip" print(f"Zipping '{ARTIFACTS_DIR}' to '{ARTIFACTS_ZIP}' for download...") !cd {ARTIFACTS_DIR} && zip -r {ARTIFACTS_ZIP} . # Note: you can also download files using Colab's file explorer try: from google.colab import files print("Downloading the artifacts zip file...") files.download(ARTIFACTS_ZIP) except ImportError: print("Missing google_colab Python package, can't download files") ###Output Zipping '/tmp/iree/colab_artifacts' to '/tmp/dynamic_shapes_colab_artifacts.zip' for download... updating: dynamic_shapes.mlir (deflated 80%) adding: dynamic_shapes_cpu.vmfb (deflated 63%) Downloading the artifacts zip file...
Keras/Diabetes Keras.ipynb
###Markdown Iris dataset in Keras library Imports ###Code import pandas as pd import numpy as np import tensorflow as tf from tensorflow.keras.utils import to_categorical from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix print("TensorFlow version:", tf.__version__) ###Output TensorFlow version: 2.2.0 ###Markdown Load data ###Code # Load data np_data = pd.read_csv("../data/diabetes.csv").values # Split data into X and y X_raw = np_data[:,0:-1].astype(float) y_raw = np_data[:,-1] # Shuffle data X_raw, y_raw = shuffle(X_raw, y_raw, random_state=0) # Convert class label strings to integers encoder = LabelEncoder() encoder.fit(y_raw) y = encoder.transform(y_raw) # Normalize data to avoid high input values scaler = StandardScaler() scaler.fit(X_raw) X = scaler.transform(X_raw) # Convert labels to one-hot vector y = to_categorical(y, 2) # Print some stuff print("Example:") print(X[0], "->", y_raw[0], "=", y[0]) print("") print("Data shape:", X.shape) ###Output Example: [-0.84488505 2.44447821 0.35643175 1.40909441 -0.69289057 1.38436175 2.784923 -0.95646168] -> YES = [0. 1.] Data shape: (768, 8) ###Markdown Train-test split ###Code # Split data into 80% training and 20% testing X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20) # Print some stuff print("Training data shape:", X_train.shape) print("Testing data shape:", X_test.shape) ###Output Training data shape: (614, 8) Testing data shape: (154, 8) ###Markdown Train and evaluate NN model on all data ###Code # Create neural network model model = Sequential() model.add(Dense(64, input_dim=8, activation="relu", kernel_initializer="he_normal")) model.add(Dense(2, activation="softmax")) # Compile model model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) # Train the model on all data model.fit(X, y, epochs=200, batch_size=32, verbose=0) # Evaluate on all data score = model.evaluate(X, y, verbose=0) # Print results print("Accuracy: {0:.2f}%".format(score[1]*100)) ###Output Accuracy: 85.29% ###Markdown Train and evaluate NN model on test data ###Code # Create neural network model model = Sequential() model.add(Dense(64, input_dim=8, activation="relu", kernel_initializer="he_normal")) model.add(Dense(2, activation="softmax")) # Compile model model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) # Train the model on training data model.fit(X_train, y_train, epochs=200, batch_size=32, verbose=0) # Evaluate on test data score = model.evaluate(X_test, y_test, verbose=0) # Print results print("Accuracy: {0:.2f}%".format(score[1]*100)) ###Output Accuracy: 78.57% ###Markdown Confusion matrix ###Code import numpy as np from sklearn.metrics import confusion_matrix # Make predictions y_pred = model.predict(X_test) # Confusion matrix conf_mx = confusion_matrix( np.argmax(y_test,axis=1), np.argmax(y_pred, axis=1)) print(conf_mx) ###Output [[89 19] [14 32]] ###Markdown Predict new examples ###Code # Create two new examples example = [ [6,149,71,34,0,33.6,0.637,48], [1,83,67,28,0,27.6,0.359,32] ] # Normalize values example = scaler.transform(example) # Make prediction res = model.predict(example) print("Prediction:", np.argmax(res, axis=1)) ###Output Prediction: [1 0]
Identificando_e_Removendo_Outliers.ipynb
###Markdown ###Code %matplotlib inline import pandas as pd import matplotlib.pyplot as plt plt.rc('figure', figsize = (14, 6)) dados = pd.read_csv('aluguel_residencial.csv', sep= ';') #<img src='Box-Plot.png' width=70%> dados.boxplot(['Valor']) dados[dados['Valor'] >= 50000] valor = dados['Valor'] plt.rc('figure', figsize = (8, 3)) dados = pd.read_csv('aluguel_residencial.csv', sep= ';') Q1 = valor.quantile(.25) Q3 = valor.quantile(.75) IIQ = Q3 - Q1 limite_inferior = Q1 - 1.5 * IIQ limite_superior = Q3 + 1.5 * IIQ selecao = (valor >= limite_inferior) & (valor <= limite_superior) dados_new = dados[selecao] dados.boxplot(['Valor']) dados.hist(['Valor']) dados_new.hist(['Valor']) # exercicio data = pd.read_csv('aluguel_amostra.csv', sep = ';') data.head() dados.boxplot(['Valor']) grupo_tipo = dados.groupby('Tipo') type(grupo_tipo) grupo_tipo.groups Q1 = grupo_tipo.quantile(.25) Q3 = grupo_tipo.quantile(.75) IIQ = Q3 - Q1 limite_inferior = Q1 - 1.5 * IIQ limite_superior = Q3 + 1.5 * IIQ Q1 Q3 limite_inferior limite_superior dados_new = pd.DataFrame() for tipo in grupo_tipo.groups.keys(): eh_tipo = dados['Tipo'] == tipo eh_dentro_limite = (dados['Valor'] >= limite_inferior[tipo]) and (dados['Valor'] <= limite_superior[tipo]) selecao = eh_tipo & eh_dentro_limite dados_selecao = dados[selecao] dados_new = pd.concat([dado_new, dados_selecao]) ###Output _____no_output_____
2-resources/BLOG/Python/python_teaching_fall_2018-master/Functions.ipynb
###Markdown Functions===A function is a named block of code. You can call it as many times as you want.You can use other people's functions. ###Code # A simple example. def greeter(): print("Hello!") greeter() ###Output Hello! ###Markdown Arguments---An argument is a piece of information that you send to a function. ###Code # Example, with one argument. def greet_person(name): print(f"Hello {name}!") greet_person('philip') def greet_person(name): print(f"Hello {name}!") names = ['eric', 'evan', 'devin', 'philip', 'barack obama', 'abraham', 'psalm'] for name in names: greet_person(name) ###Output Hello eric! Hello evan! Hello devin! Hello philip! Hello barack obama! Hello abraham! Hello psalm! ###Markdown A fun example--- ###Code # Text to speech. from gtts import gTTS import os tts = gTTS(text='Good morning, gandhi.', lang='en') tts.save("hello.mp3") os.system("start hello.mp3") from gtts import gTTS import os def say_message(message): tts = gTTS(text=message, lang='en') tts.save("message.mp3") os.system("start message.mp3") say_message('oink oink!') names = ['eric', 'evan', 'devin', 'philip', 'barack obama', 'abraham', 'psalm'] for name in names: say_message(f"Hello, {name}!") ###Output _____no_output_____ ###Markdown Returning values---You can write a function that does a bunch of work, and then returns something to the line that called the function: ###Code def get_full_name(f_name, l_name): """Return a full name.""" full_name = f"{f_name} {l_name}" return full_name full_name = get_full_name('alex', 'honnold') print(full_name) ###Output alex honnold
loading_data/pandas_features.ipynb
###Markdown Pandas can have datetime indexes and work with them ###Code today = datetime.today() date_list = [today + timedelta(days=x) for x in range(0, 100)] df = pd.DataFrame({'values': range(0, 100)}, index=date_list) df[today:today + timedelta(days=3)] ###Output _____no_output_____ ###Markdown We can also use partial date objects or another formats. Pandas will try to infer. ###Code df[str(today.date())] df[str(today.date())] ###Output _____no_output_____
code_files/Linear Regression on Medical Insurance Dataset.ipynb
###Markdown Linear Regression on Medical Insurance Dataset ###Code import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error data = pd.read_csv("C:\\Users\\black\\Desktop\\ml_py\\datasets\\insurance.csv") data.head() data.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 1338 entries, 0 to 1337 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 age 1338 non-null int64 1 sex 1338 non-null object 2 bmi 1338 non-null float64 3 children 1338 non-null int64 4 smoker 1338 non-null object 5 region 1338 non-null object 6 charges 1338 non-null float64 dtypes: float64(2), int64(2), object(3) memory usage: 73.3+ KB ###Markdown Simple Linear Model ###Code x = data[["age"]].values y = data.iloc[:,6:].values x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state=40) from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_test = sc.transform(x_test) lr = LinearRegression() lr.fit(x_train, y_train) y_pred = lr.predict(x_test) r2 = r2_score(y_test, y_pred) r2 from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred))) ###Output Mean Absolute Error: 9099.67487979512 Mean Squared Error: 137472322.7051458 Root Mean Squared Error: 11724.859176346034 ###Markdown Multi Linear Model ###Code x = data[["children","bmi"]].values y = data.iloc[:,6:].values from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_test = sc.transform(x_test) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state=40) lr = LinearRegression() lr.fit(x_train, y_train) y_pred = lr.predict(x_test) r2 = r2_score(y_test, y_pred) r2 from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred))) ###Output Mean Absolute Error: 9426.280328467989 Mean Squared Error: 143983516.1469823 Root Mean Squared Error: 11999.31315313432
demos/location-based-recommendation/04-nuclio-process_user_location.ipynb
###Markdown Nuclio - Process user location signal Setup the environment ###Code # nuclio: ignore import nuclio ###Output _____no_output_____ ###Markdown Define environment variables ###Code import os # nuclio: ignore os.environ['STORES_TABLE'] = os.path.join(os.getenv('V3IO_USERNAME', 'iguazio'), 'stores') os.environ['CUSTOMERS_TABLE'] = os.path.join(os.getenv('V3IO_USERNAME', 'iguazio'), 'customers') os.environ['CUSTOMERS_STREAM'] = os.path.join(os.getenv('V3IO_USERNAME', 'iguazio'), 'customers_stream') os.environ['PREDICTIONS_STREAM'] = os.path.join(os.getenv('V3IO_USERNAME', 'iguazio'), 'predictions') # DB Acess %nuclio env V3IO_API=${V3IO_FRAMESD} %nuclio env V3IO_ACCESS_KEY=${V3IO_ACCESS_KEY} # Customers %nuclio env COSTUMERS_STREAM=${CUSTOMERS_STREAM} %nuclio env COSTUMERS_TABLE=${CUSTOMERS_TABLE} %nuclio env STORES_TABLE=${STORES_TABLE} # Predictions %nuclio env PREDICTIONS_STREAM=${PREDICTIONS_STREAM} %nuclio env PREDICTION_SERVER=http://prediction-server:8080 ###Output %nuclio: setting 'V3IO_API' environment variable %nuclio: setting 'V3IO_ACCESS_KEY' environment variable %nuclio: setting 'COSTUMERS_STREAM' environment variable %nuclio: setting 'COSTUMERS_TABLE' environment variable %nuclio: setting 'STORES_TABLE' environment variable %nuclio: setting 'PREDICTIONS_STREAM' environment variable %nuclio: setting 'PREDICTION_SERVER' environment variable ###Markdown Base image ###Code %nuclio config spec.build.baseImage = "python:3.6-jessie" ###Output %nuclio: setting spec.build.baseImage to 'python:3.6-jessie' ###Markdown Set cron trigger to read from stream ###Code %nuclio config spec.triggers.secs.kind = "cron" %nuclio config spec.triggers.secs.attributes.interval = "1m" ###Output %nuclio: setting spec.triggers.secs.kind to 'cron' %nuclio: setting spec.triggers.secs.attributes.interval to '1m' ###Markdown Install packages ###Code %%nuclio cmd -c pip install v3io_frames pip install v3io==0.1.1 --upgrade pip install requests pip install pandas ###Output _____no_output_____ ###Markdown Function code ###Code import json import os import requests import time # Data handling import pandas as pd # DB import v3io import v3io.dataplane import v3io.logger import v3io_frames as v3f ###Output _____no_output_____ ###Markdown Init context ###Code def init_context(context): # DB Contexts v3c = v3io.dataplane.Context(v3io.logger.Logger('DEBUG')).new_session().new_container('users') setattr(context, 'v3c', v3c) v3c_frames = v3f.Client('framesd:8081', container='users') setattr(context, 'v3f', v3c_frames) # DB Tables customers_table = os.environ['COSTUMERS_TABLE'] setattr(context, 'customers', customers_table) stores_table = os.environ['STORES_TABLE'] setattr(context, 'stores', stores_table) predictions_stream = os.environ['PREDICTIONS_STREAM'] setattr(context, 'predictions', predictions_stream) customers_stream = os.environ['COSTUMERS_STREAM'] setattr(context, 'customers_stream', customers_stream) # Prediction server prediction_server = os.getenv('PREDICTION_SERVER') setattr(context, 'prediction_server', prediction_server) ###Output _____no_output_____ ###Markdown Helper functions ###Code def is_customer_in_store(customer, context) -> bool: store_location = customer['location'] store = context.v3f.read('kv', context.stores, filter=f'__name=="{store_location}"') return not store.empty def is_customer_out_of_store(context, new_customer_locations): if not new_customer_locations.empty: users = new_customer_locations['id'].values.astype('int').astype('str') filter_line = str(list(users)) filter_line = f'__name IN ({filter_line[1:-1]})' old_customer_locations = context.v3f.read('kv', context.customers, columns=['location'], filter=filter_line) old_customer_locations['is_store'] = old_customer_locations.apply(is_customer_in_store, args=[context], axis=1) return old_customer_locations[old_customer_locations['is_store'] == True]['location'] def update_customer_location(context, customer_id: str, location: str): context.v3f.execute('kv', context.customers , 'update', args={'key':customer_id, 'expression': f'SET location="{location}"', 'condition':''}) def update_store_count(customer, context, is_add=True): operator = '+' if is_add else '-' context.v3f.execute('kv', context.stores , 'update', args={'key': customer, 'expression': f'SET customers=customers{operator}1', 'condition':''}) def save_predictions(context, customer_id: str, prediction: pd.DataFrame): context.v3f.write('tsdb', context.predictions, prediction) ###Output _____no_output_____ ###Markdown Handler ###Code def handler(context, event): # Get latest customer locations from the customers stream customers_stream = context.v3f.read('tsdb', context.customers_stream, start='now-1m') if not customers_stream.empty: # Has anyone moved out of any store? stores_to_update = is_customer_out_of_store(context, customers_stream) stores_to_update.apply(update_store_count, args=[context, False]) # Update the customer's new location [update_customer_location(context, str(int(customer['id'])), customer['location']) for idx, customer in customers_stream.iterrows()] # Get all customers that are in stores customers_stream['is_store'] = customers_stream.apply(is_customer_in_store, args=[context], axis=1) customers_stream = customers_stream[customers_stream['is_store']] # Update customers in stores count customers_stream['update_stores'] = customers_stream['location'].apply(update_store_count, args=[context]) context.logger.debug(customers_stream) [requests.post(context.prediction_server, json={'id': str(int(customer['id'])), 'store': str(customer['location'])}) for idx, customer in customers_stream.iterrows()] # nuclio: ignore init_context(context) # nuclio: ignore event = nuclio.Event() handler(context, event) %nuclio deploy -n process_user_location -p recommendation_engine -c ###Output [nuclio.deploy] 2019-08-11 13:38:34,372 (info) Building processor image [nuclio.deploy] 2019-08-11 13:39:04,748 (info) Pushing image [nuclio.deploy] 2019-08-11 13:39:18,908 (info) Build complete [nuclio.deploy] 2019-08-11 13:39:22,100 done creating process-user-location, function address: 3.120.15.118:32537 %nuclio: function deployed
7.3-developing-and-evaluating-chunkers.ipynb
###Markdown 开发和评估分块器 读取 IOB 格式与 CoNLL2000 分块语料库使用转换函数 [chunk.conllstr2tree()](https://www.nltk.org/_modules/nltk/chunk/util.htmlconllstr2tree) 可以将 IOB 格式的字符串转换成树表示。此外,它允许我们选择使用语料库提供的三种块类型:NP、VP 和 PP 的任何子集。 ###Code import nltk text = """ he PRP B-NP accepted VBD B-VP the DT B-NP position NN I-NP of IN B-PP vice NN B-NP chairman NN I-NP of IN B-PP Carlyle NNP B-NP Group NNP I-NP , , O a DT B-NP merchant NN I-NP banking NN I-NP concern NN I-NP . . O """ nltk.chunk.conllstr2tree(text, chunk_types=['NP']).draw() ###Output _____no_output_____ ###Markdown ![ch07-tree-2.png](resources/ch07-tree-2.png) NLTK 的 corpus 模块包含了大量已分块的文本。CoNLL2000 语料库包含 27 万词的《华尔街日报》文本,分为“训练”和“测试”两部分,标注有词性标记和 IOB 格式分块标记: ###Code from nltk.corpus import conll2000 print(conll2000.chunked_sents('train.txt')[99]) ###Output (S (PP Over/IN) (NP a/DT cup/NN) (PP of/IN) (NP coffee/NN) ,/, (NP Mr./NNP Stone/NNP) (VP told/VBD) (NP his/PRP$ story/NN) ./.) ###Markdown 正如你看到的,CoNLL2000 语料库包含了三种块类型:NP 块如 a cup;VP 块如 told;PP 块如 of。由于现在我们唯一感兴趣的是 NP 块,我们可以使用 chunk_types 参数选择它: ###Code test_sent = conll2000.chunked_sents('train.txt', chunk_types=['NP'])[99] print(type(test_sent)) print(test_sent) ###Output <class 'nltk.tree.Tree'> (S Over/IN (NP a/DT cup/NN) of/IN (NP coffee/NN) ,/, (NP Mr./NNP Stone/NNP) told/VBD (NP his/PRP$ story/NN) ./.) ###Markdown 简单评估和基准首先,我们为不创建任何块的分块器建立一个基准(baseline): ###Code cp = nltk.RegexpParser('') test_sents = conll2000.chunked_sents('test.txt', chunk_types=['NP']) print(cp.parse(test_sent)) print(cp.evaluate(test_sents)) ###Output (S Over/IN (NP a/DT cup/NN) of/IN (NP coffee/NN) ,/, (NP Mr./NNP Stone/NNP) told/VBD (NP his/PRP$ story/NN) ./.) ChunkParse score: IOB Accuracy: 43.4%% Precision: 0.0%% Recall: 0.0%% F-Measure: 0.0%% ###Markdown IOB 标记准确性表明超过三分之一的词被标注为 O,即没有出现在 NP 块中。然而,由于我们的标注器没有找到任何块,其精度、召回率和 F 度量均为零。现在让我们尝试一个初级的正则表达式分类器,查找以名词短语标记的特征字母(如 CD、DT 和 JJ)开头的标记: ###Code grammar = r'NP: {<[CDJNP].*>+}' cp = nltk.RegexpParser(grammar) print(cp.parse(test_sent)) print(cp.evaluate(test_sents)) ###Output (S Over/IN (NP (NP a/DT cup/NN)) of/IN (NP (NP coffee/NN)) ,/, (NP (NP Mr./NNP Stone/NNP)) told/VBD (NP (NP his/PRP$ story/NN)) ./.) ChunkParse score: IOB Accuracy: 87.7%% Precision: 70.6%% Recall: 67.8%% F-Measure: 69.2%% ###Markdown 这种方法达到了不错的结果,但是我们可以采用更多数据驱动的方法改善它。这里我们定义了 UnigramChunker 类,使用 unigram 标注器给句子加块标记。这个类实现了 [nltk.ChunkParserI](https://www.nltk.org/_modules/nltk/chunk/api.htmlChunkParserI) 接口,定义了两个方法:一个构造函数,当我们建立新的 UnigramChunker 时调用;一个 parse 方法,用来给新句子分块。构造函数需要训练句子的一个链表,每个句子都是块树的形式。它首先通过 tree2conlltags 方法将块树转换成 IOB 标记,然后训练一个基于词性标记的 unigram 块标注器。parse 方法取一个已标注的句子作为输入,首先提取词性标记,然后使用在构造函数中训练过的标注器为词性标记标注 IOB 标记。接下来将块标记与原句组合,产生 conlltags。最后使用 conlltags2tree 将结果转换成一个块树。 ###Code class UnigramChunker(nltk.ChunkParserI): def __init__(self, train_sents): train_data = [[(t, c) for w, t, c in nltk.chunk.tree2conlltags(sent)] for sent in train_sents] self.tagger = nltk.UnigramTagger(train_data) def parse(self, sentence): pos_tags = [pos for (_, pos) in sentence] tagged_pos_tags = self.tagger.tag(pos_tags) chunktags = [chunktag for (pos, chunktag) in tagged_pos_tags] conlltags = [(word, pos, chunktag) for ((word, pos), chunktag) in zip(sentence, chunktags)] return nltk.chunk.conlltags2tree(conlltags) train_sents = conll2000.chunked_sents('train.txt', chunk_types=['NP']) test_sents = conll2000.chunked_sents('test.txt', chunk_types=['NP']) unigram_chunker = UnigramChunker(train_sents) print(unigram_chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 92.9%% Precision: 79.9%% Recall: 86.8%% F-Measure: 83.2%% ###Markdown 这个分块器相当不错,达到整体 F 度量 83% 的得分。现在我们来分析一下 unigram 标注器给每个词性标记分配了什么样的块标记: ###Code postags = sorted(set(pos for sent in train_sents for (_, pos) in sent.leaves())) print(unigram_chunker.tagger.tag(postags)) ###Output [('#', 'B-NP'), ('$', 'B-NP'), ("''", 'O'), ('(', 'O'), (')', 'O'), (',', 'O'), ('.', 'O'), (':', 'O'), ('CC', 'O'), ('CD', 'I-NP'), ('DT', 'B-NP'), ('EX', 'B-NP'), ('FW', 'I-NP'), ('IN', 'O'), ('JJ', 'I-NP'), ('JJR', 'B-NP'), ('JJS', 'I-NP'), ('MD', 'O'), ('NN', 'I-NP'), ('NNP', 'I-NP'), ('NNPS', 'I-NP'), ('NNS', 'I-NP'), ('PDT', 'B-NP'), ('POS', 'B-NP'), ('PRP', 'B-NP'), ('PRP$', 'B-NP'), ('RB', 'O'), ('RBR', 'O'), ('RBS', 'B-NP'), ('RP', 'O'), ('SYM', 'O'), ('TO', 'O'), ('UH', 'O'), ('VB', 'O'), ('VBD', 'O'), ('VBG', 'O'), ('VBN', 'O'), ('VBP', 'O'), ('VBZ', 'O'), ('WDT', 'B-NP'), ('WP', 'B-NP'), ('WP$', 'B-NP'), ('WRB', 'O'), ('``', 'O')] ###Markdown 可以发现大多数标点符号都出现在 NP 块外,除了货币符号 `` 和 `$`;限定词(DT)和所有格(PRP`$` 和 WP`$`)出现在 NP 块的开头,而名词类型(NN,NNP,NNPS,NNS)大多出现在 NP 块内。我们对 unigram 分块器稍作修改,建立一个 bigram 分块器,性能略有提升: ###Code class BigramChunker(nltk.ChunkParserI): def __init__(self, train_sents): train_data = [[(t, c) for w, t, c in nltk.chunk.tree2conlltags(sent)] for sent in train_sents] self.tagger = nltk.BigramTagger(train_data) def parse(self, sentence): pos_tags = [pos for (_, pos) in sentence] tagged_pos_tags = self.tagger.tag(pos_tags) chunktags = [chunktag for (pos, chunktag) in tagged_pos_tags] conlltags = [(word, pos, chunktag) for ((word, pos), chunktag) in zip(sentence, chunktags)] return nltk.chunk.conlltags2tree(conlltags) train_sents = conll2000.chunked_sents('train.txt', chunk_types=['NP']) test_sents = conll2000.chunked_sents('test.txt', chunk_types=['NP']) bigram_chunker = BigramChunker(train_sents) print(bigram_chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 93.3%% Precision: 82.3%% Recall: 86.8%% F-Measure: 84.5%% ###Markdown 训练基于分类器的分块器无论是基于正则表达式的分块器还是 n-gram 分块器,决定创建什么块完全基于词性标记。然而有时词性标记不足以确定一个句子应如何分块。例如:a. Joey/NN sold/VBD the/DT farmer/NN rice/NN ./.b. Nick/NN broke/VBD my/DT computer/NN monitor/NN ./.这两句话的词性标记相同,但分块方式不同。第一句中 the farmer 和 rice 都是单独的块,而第二个句子中相应的部分 the computer monitor 是一个单独的块。因此,为了最大限度地提升分块的性能,我们需要使用词的内容信息作为词性标注的补充。我们包含词的内容信息的方法之一是使用基于**分类器**的标注器对句子分块。在下面的例子中包括两个类:第一个类与 6.1 节中的 ConsecutivePosTagger 类似,仅有的区别在于使用 MaxentClassifier 代替 NaiveBayesClassifier;第二个类是标注器类的一个包装器,将它变成一个分块器。 ###Code class ConsecutiveNPChunkTagger(nltk.TaggerI): def __init__(self, train_sents): train_set = [] for tagged_sent in train_sents: untagged_sent = nltk.tag.untag(tagged_sent) history = [] for i, (word, tag) in enumerate(tagged_sent): featureset = npchunk_features(untagged_sent, i, history) train_set.append((featureset, tag)) history.append(tag) self.classifier = nltk.MaxentClassifier.train(train_set, trace=0) def tag(self, sentence): history = [] for i, word in enumerate(sentence): featureset = npchunk_features(sentence, i, history) tag = self.classifier.classify(featureset) history.append(tag) return zip(sentence, history) class ConsecutiveNPChunker(nltk.ChunkParserI): def __init__(self, train_sents): tagged_sents = [[((w, t), c) for (w, t, c) in nltk.chunk.tree2conlltags(sent)] for sent in train_sents] self.tagger = ConsecutiveNPChunkTagger(tagged_sents) def parse(self, sentence): tagged_sents = self.tagger.tag(sentence) conlltags = [(w, t, c) for ((w, t), c) in tagged_sents] return nltk.chunk.conlltags2tree(conlltags) ###Output _____no_output_____ ###Markdown 还需要定义用到的特征提取器 npchunk_features。首先,我们定义一个简单的特征提取器,它只提供当前标识符的词性标记。利用这个体征提取器的分块器性能与 unigram 分块器非常类似: ###Code def npchunk_features(sentence, i, history): word, pos = sentence[i] return {'pos': pos} chunker = ConsecutiveNPChunker(train_sents) print(chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 92.9%% Precision: 79.9%% Recall: 86.8%% F-Measure: 83.2%% ###Markdown 接着我们再添加一个特征:前面词的词性标记。添加此特征允许分类器模拟相邻标记间的相互作用,由此产生的分块器与 bigram 分块器非常接近: ###Code def npchunk_features(sentence, i, history): word, pos = sentence[i] if i == 0: prevword, prevpos = '<START>', '<START>' else: prevword, prevpos = sentence[i - 1] return {'pos': pos, 'prevpos': prevpos} chunker = ConsecutiveNPChunker(train_sents) print(chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 93.6%% Precision: 82.0%% Recall: 87.2%% F-Measure: 84.6%% ###Markdown 下一步,我们尝试把当前词增加为特征,可以发现这个特征确实提高了分块器的性能,大约 1.5 个百分点: ###Code def npchunk_features(sentence, i, history): word, pos = sentence[i] if i == 0: prevword, prevpos = '<START>', '<START>' else: prevword, prevpos = sentence[i - 1] return {'pos': pos, 'word': word, 'prevpos': prevpos} chunker = ConsecutiveNPChunker(train_sents) print(chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 94.6%% Precision: 84.6%% Recall: 89.8%% F-Measure: 87.1%% ###Markdown 最后,我们尝试用多种附加特征扩展特征提取器,例如:预取特征、配对功能和复杂的语境特征等: ###Code def npchunk_features(sentence, i, history): word, pos = sentence[i] if i == 0: prevword, prevpos = '<START>', '<START>' else: prevword, prevpos = sentence[i - 1] if i == len(sentence) - 1: nextword, nextpos = '<END', 'END>' else: nextword, nextpos = sentence[i + 1] return {'pos': pos, 'word': word, 'prevpos': prevpos, 'nextpos': nextpos, 'prevpos+pos': '%s+%s' % (prevpos, pos), 'pos+nextpos': '%s+%s' % (pos, nextpos), 'tags-since-dt': tags_since_dt(sentence, i)} def tags_since_dt(sentence, i): tags = set() for word, pos in sentence[:i]: if pos == 'DT': tags = set() else: tags.add(pos) return '+'.join(sorted(tags)) chunker = ConsecutiveNPChunker(train_sents) print(chunker.evaluate(test_sents)) ###Output ChunkParse score: IOB Accuracy: 96.0%% Precision: 88.3%% Recall: 91.1%% F-Measure: 89.7%%
Code/nn.ipynb
###Markdown Basic Instructions1. Enter your Name and UID in the provided space.2. Do the assignment in the notebook itself3. you are free to use Google Colab Name: **Arpit Aggarwal** UID: **116747189** In the first part, you will implement all the functions required to build a two layer neural network.In the next part, you will use these functions for image and text classification. Provide your code at the appropriate placeholders. 1. Packages ###Code import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage ###Output _____no_output_____ ###Markdown 2. Layer Initialization **Exercise:** Create and initialize the parameters of the 2-layer neural network. Use random initialization for the weight matrices and zero initialization for the biases. ###Code def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: parameters -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ np.random.seed(1) ### START CODE HERE ### (≈ 4 lines of code) W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros(shape=(n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros(shape=(n_y, 1)) ### END CODE HERE ### assert(W1.shape == (n_h, n_x)) assert(b1.shape == (n_h, 1)) assert(W2.shape == (n_y, n_h)) assert(b2.shape == (n_y, 1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters parameters = initialize_parameters(3,2,1) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) ###Output W1 = [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] b1 = [[0.] [0.]] W2 = [[ 0.01744812 -0.00761207]] b2 = [[0.]] ###Markdown **Expected output**: **W1** [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] **b1** [[ 0.] [ 0.]] **W2** [[ 0.01744812 -0.00761207]] **b2** [[ 0.]] 3. Forward Propagation Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:- LINEAR- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid.The linear module computes the following equation:$$Z = WA+b\tag{4}$$ 3.1 Exercise: Build the linear part of forward propagation. ###Code def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) Returns: Z -- the input of the activation function, also called pre-activation parameter cache -- a python dictionary containing "A", "W" and "b" ; stored for computing the backward pass efficiently """ ### START CODE HERE ### (≈ 1 line of code) Z = np.dot(W, A) + b ### END CODE HERE ### assert(Z.shape == (W.shape[0], A.shape[1])) cache = (A, W, b) return Z, cache np.random.seed(1) A = np.random.randn(3,2) W = np.random.randn(1,3) b = np.random.randn(1,1) Z, linear_cache = linear_forward(A, W, b) print("Z = " + str(Z)) ###Output Z = [[ 3.26295337 -1.23429987]] ###Markdown **Expected output**: **Z** [[ 3.26295337 -1.23429987]] 3.2 - Linear-Activation ForwardIn this notebook, you will use two activation functions:- **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. Write the code for the `sigmoid` function. This function returns **two** items: the activation value "`a`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call: ``` pythonA, activation_cache = sigmoid(Z)```- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. Write the code for the `relu` function. This function returns **two** items: the activation value "`A`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:``` pythonA, activation_cache = relu(Z)**Exercise**: - Implement the activation functions- Build the linear activation part of forward propagation. Mathematical relation is: $A = g(Z) = g(WA_{prev} +b)$ ###Code def sigmoid(Z): """ Implements the sigmoid activation in numpy Arguments: Z -- numpy array of any shape Returns: A -- output of sigmoid(z), same shape as Z cache -- returns Z, useful during backpropagation """ ### START CODE HERE ### (≈ 2 line of code) A = 1.0 / (1.0 + np.exp(-Z)) cache = Z ### END CODE HERE ### return A, cache def relu(Z): """ Implement the RELU function. Arguments: Z -- Output of the linear layer, of any shape Returns: A -- Post-activation parameter, of the same shape as Z cache -- returns Z, useful during backpropagation """ ### START CODE HERE ### (≈ 2 line of code) A = np.maximum(0, Z) cache = Z ### END CODE HERE ### assert(A.shape == Z.shape) return A, cache def linear_activation_forward(A_prev, W, b, activation): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: A -- the output of the activation function, also called the post-activation value cache -- a python dictionary containing "linear_cache" and "activation_cache"; stored for computing the backward pass efficiently """ if activation == "sigmoid": # Inputs: "A_prev, W, b". Outputs: "A, activation_cache". ### START CODE HERE ### (≈ 2 lines of code) Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = sigmoid(Z) ### END CODE HERE ### elif activation == "relu": # Inputs: "A_prev, W, b". Outputs: "A, activation_cache". ### START CODE HERE ### (≈ 2 lines of code) Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = relu(Z) ### END CODE HERE ### assert (A.shape == (W.shape[0], A_prev.shape[1])) cache = (linear_cache, activation_cache) return A, cache np.random.seed(2) A_prev = np.random.randn(3,2) W = np.random.randn(1,3) b = np.random.randn(1,1) A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid") print("With sigmoid: A = " + str(A)) A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu") print("With ReLU: A = " + str(A)) ###Output With sigmoid: A = [[0.96890023 0.11013289]] With ReLU: A = [[3.43896131 0. ]] ###Markdown **Expected output**: **With sigmoid: A ** [[ 0.96890023 0.11013289]] **With ReLU: A ** [[ 3.43896131 0. ]] 4 - Loss functionNow you will implement forward and backward propagation. You need to compute the loss, because you want to check if your model is actually learning.**Exercise**: Compute the cross-entropy loss $J$, using the following formula: $$-\frac{1}{m} \sum\limits_{i = 1}^{m} (y^{(i)}\log\left(a^{ (i)}\right) + (1-y^{(i)})\log\left(1- a^{(i)}\right)) \tag{7}$$ ###Code # GRADED FUNCTION: compute_loss def compute_loss(A, Y): """ Implement the loss function defined by equation (7). Arguments: A -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples) Returns: loss -- cross-entropy loss """ m = Y.shape[1] # Compute loss from aL and y. ### START CODE HERE ### (≈ 1 lines of code) loss = (-1.0 / m) * np.sum((Y * np.log(A)) + ((1.0 - Y) * np.log(1.0 - A))) ### END CODE HERE ### loss = np.squeeze(loss) # To make sure your loss's shape is what we expect (e.g. this turns [[17]] into 17). assert(loss.shape == ()) return loss Y = np.asarray([[1, 1, 1]]) A = np.array([[.8,.9,0.4]]) print("loss = " + str(compute_loss(A, Y))) ###Output loss = 0.41493159961539694 ###Markdown **Expected Output**: **loss** 0.41493159961539694 5 - Backward propagation moduleJust like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. Now, similar to forward propagation, you are going to build the backward propagation in two steps:- LINEAR backward- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation 5.1 - Linear backward ###Code # GRADED FUNCTION: linear_backward def linear_backward(dZ, cache): """ Implement the linear portion of backward propagation for a single layer (layer l) Arguments: dZ -- Gradient of the loss with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer Returns: dA_prev -- Gradient of the loss with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the loss with respect to W (current layer l), same shape as W db -- Gradient of the loss with respect to b (current layer l), same shape as b """ A_prev, W, b = cache m = A_prev.shape[1] ### START CODE HERE ### (≈ 3 lines of code) dA_prev = np.dot(W.T, dZ) dW = np.dot(dZ, A_prev.T) db = np.array([np.sum(dZ, axis = 1)]).T ### END CODE HERE ### assert (dA_prev.shape == A_prev.shape) assert (dW.shape == W.shape) assert (db.shape == b.shape) return dA_prev, dW, db np.random.seed(1) dZ = np.random.randn(1,2) A = np.random.randn(3,2) W = np.random.randn(1,3) b = np.random.randn(1,1) linear_cache = (A, W, b) dA_prev, dW, db = linear_backward(dZ, linear_cache) print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db)) ###Output dA_prev = [[ 0.51822968 -0.19517421] [-0.40506361 0.15255393] [ 2.37496825 -0.89445391]] dW = [[-0.2015379 2.81370193 3.2998501 ]] db = [[1.01258895]] ###Markdown **Expected Output**: **dA_prev** [[ 0.51822968 -0.19517421] [-0.40506361 0.15255393] [ 2.37496825 -0.89445391]] **dW** [[-0.2015379 2.81370193 3.2998501 ]] **db** [[1.01258895]] 5.2 - Linear Activation backwardNext, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. Before implementing `linear_activation_backward`, you need to implement two backward functions for each activations:- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:```pythondZ = sigmoid_backward(dA, activation_cache)```- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:```pythondZ = relu_backward(dA, activation_cache)```If $g(.)$ is the activation function, `sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \tag{11}$$. **Exercise**: - Implement the backward functions for the relu and sigmoid activation layer.- Implement the backpropagation for the *LINEAR->ACTIVATION* layer. ###Code def relu_backward(dA, cache): """ Implement the backward propagation for a single RELU unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the loss with respect to Z """ Z = cache dZ = np.array(dA, copy=True) # just converting dz to a correct object. ### START CODE HERE ### (≈ 1 line of code) dZ = dA * np.where(Z <= 0, 0, 1) ### END CODE HERE ### assert (dZ.shape == Z.shape) return dZ def sigmoid_backward(dA, cache): """ Implement the backward propagation for a single SIGMOID unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the loss with respect to Z """ Z = cache ### START CODE HERE ### (≈ 2 line of code) sigmoid_derivative = sigmoid(Z)[0] * (1.0 - sigmoid(Z)[0]) dZ = dA * sigmoid_derivative ### END CODE HERE ### assert (dZ.shape == Z.shape) return dZ # GRADED FUNCTION: linear_activation_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATION layer. Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: dA_prev -- Gradient of the loss with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the loss with respect to W (current layer l), same shape as W db -- Gradient of the loss with respect to b (current layer l), same shape as b """ linear_cache, activation_cache = cache if activation == "relu": ### START CODE HERE ### (≈ 2 lines of code) dZ = relu_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) ### END CODE HERE ### elif activation == "sigmoid": ### START CODE HERE ### (≈ 2 lines of code) dZ = sigmoid_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) ### END CODE HERE ### return dA_prev, dW, db np.random.seed(2) dA = np.random.randn(1,2) A = np.random.randn(3,2) W = np.random.randn(1,3) b = np.random.randn(1,1) Z = np.random.randn(1,2) linear_cache = (A, W, b) activation_cache = Z linear_activation_cache = (linear_cache, activation_cache) dA_prev, dW, db = linear_activation_backward(dA, linear_activation_cache, activation = "sigmoid") print ("sigmoid:") print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db) + "\n") dA_prev, dW, db = linear_activation_backward(dA, linear_activation_cache, activation = "relu") print ("relu:") print ("dA_prev = "+ str(dA_prev)) print ("dW = " + str(dW)) print ("db = " + str(db)) ###Output sigmoid: dA_prev = [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] dW = [[ 0.20533573 0.19557101 -0.03936168]] db = [[-0.11459244]] relu: dA_prev = [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] dW = [[ 0.89027649 0.74742835 -0.20957978]] db = [[-0.41675785]] ###Markdown **Expected output with sigmoid:** dA_prev [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] dW [[ 0.20533573 0.19557101 -0.03936168]] db [[-0.11459244]] **Expected output with relu:** dA_prev [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] dW [[ 0.89027649 0.74742835 -0.20957978]] db [[-0.41675785]] 6 - Update ParametersIn this section you will update the parameters of the model, using gradient descent: $$ W^{[1]} = W^{[1]} - \alpha \text{ } dW^{[1]} \tag{16}$$$$ b^{[1]} = b^{[1]} - \alpha \text{ } db^{[1]} \tag{17}$$$$ W^{[2]} = W^{[2]} - \alpha \text{ } dW^{[2} \tag{16}$$$$ b^{[2]} = b^{[2]} - \alpha \text{ } db^{[2]} \tag{17}$$where $\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. **Exercise**: Implement `update_parameters()` to update your parameters using gradient descent.**Instructions**:Update parameters using gradient descent. ###Code # GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate): """ Update parameters using gradient descent Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Returns: parameters -- python dictionary containing your updated parameters parameters["W" + str(l)] = ... parameters["b" + str(l)] = ... """ # Update rule for each parameter. Use a for loop. ### START CODE HERE ### (≈ 4 lines of code) for key in parameters: parameters[key] = parameters[key] - (learning_rate * grads["d" + str(key)]) ### END CODE HERE ### return parameters np.random.seed(2) W1 = np.random.randn(3,4) b1 = np.random.randn(3,1) W2 = np.random.randn(1,3) b2 = np.random.randn(1,1) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} np.random.seed(3) dW1 = np.random.randn(3,4) db1 = np.random.randn(3,1) dW2 = np.random.randn(1,3) db2 = np.random.randn(1,1) grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} parameters = update_parameters(parameters, grads, 0.1) print ("W1 = "+ str(parameters["W1"])) print ("b1 = "+ str(parameters["b1"])) print ("W2 = "+ str(parameters["W2"])) print ("b2 = "+ str(parameters["b2"])) ###Output W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008] [-1.76569676 -0.80627147 0.51115557 -1.18258802] [-1.0535704 -0.86128581 0.68284052 2.20374577]] b1 = [[-0.04659241] [-1.28888275] [ 0.53405496]] W2 = [[-0.55569196 0.0354055 1.32964895]] b2 = [[-0.84610769]] ###Markdown **Expected Output**: W1 [[-0.59562069 -0.09991781 -2.14584584 1.82662008] [-1.76569676 -0.80627147 0.51115557 -1.18258802] [-1.0535704 -0.86128581 0.68284052 2.20374577]] b1 [[-0.04659241] [-1.28888275] [ 0.53405496]] W2 [[-0.55569196 0.0354055 1.32964895]] b2 [[-0.84610769]] 7 - ConclusionCongrats on implementing all the functions required for building a deep neural network! We know it was a long assignment but going forward it will only get better. The next part of the assignment is easier. Part 2:In the next part you will put all these together to build a two-layer neural networks for image classification. ###Code %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ###Output _____no_output_____ ###Markdown Dataset **Problem Statement**: You are given a dataset ("data/train_catvnoncat.h5", "data/test_catvnoncat.h5") containing: - a training set of m_train images labelled as cat (1) or non-cat (0) - a test set of m_test images labelled as cat and non-cat - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB).Let's get more familiar with the dataset. Load the data by completing the function and run the cell below. ###Code def load_data(train_file, test_file): # Load the training data train_dataset = h5py.File(train_file, 'r') # Separate features(x) and labels(y) for training set train_set_x_orig = np.array(train_dataset['train_set_x']) train_set_y_orig = np.array(train_dataset['train_set_y']) # Load the test data test_dataset = h5py.File(test_file, 'r') # Separate features(x) and labels(y) for training set test_set_x_orig = np.array(test_dataset['test_set_x']) test_set_y_orig = np.array(test_dataset['test_set_y']) classes = np.array(test_dataset["list_classes"][:]) # the list of classes train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes train_file="data/train_catvnoncat.h5" test_file="data/test_catvnoncat.h5" train_x_orig, train_y, test_x_orig, test_y, classes = load_data(train_file, test_file) ###Output _____no_output_____ ###Markdown The following code will show you an image in the dataset. Feel free to change the index and re-run the cell multiple times to see other images. ###Code # Example of a picture index = 10 plt.imshow(train_x_orig[index]) print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") + " picture.") # Explore your dataset m_train = train_x_orig.shape[0] num_px = train_x_orig.shape[1] m_test = test_x_orig.shape[0] print ("Number of training examples: " + str(m_train)) print ("Number of testing examples: " + str(m_test)) print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)") print ("train_x_orig shape: " + str(train_x_orig.shape)) print ("train_y shape: " + str(train_y.shape)) print ("test_x_orig shape: " + str(test_x_orig.shape)) print ("test_y shape: " + str(test_y.shape)) ###Output Number of training examples: 209 Number of testing examples: 50 Each image is of size: (64, 64, 3) train_x_orig shape: (209, 64, 64, 3) train_y shape: (1, 209) test_x_orig shape: (50, 64, 64, 3) test_y shape: (1, 50) ###Markdown As usual, you reshape and standardize the images before feeding them to the network. Figure 1: Image to vector conversion. ###Code # Reshape the training and test examples train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The "-1" makes reshape flatten the remaining dimensions test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T # Standardize data to have feature values between 0 and 1. train_x = train_x_flatten/255. test_x = test_x_flatten/255. print ("train_x's shape: " + str(train_x.shape)) print ("test_x's shape: " + str(test_x.shape)) ###Output train_x's shape: (12288, 209) test_x's shape: (12288, 50) ###Markdown 3 - Architecture of your modelNow that you are familiar with the dataset, it is time to build a deep neural network to distinguish cat images from non-cat images. 2-layer neural network Figure 2: 2-layer neural network. The model can be summarized as: ***INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT***. Detailed Architecture of figure 2:- The input is a (64,64,3) image which is flattened to a vector of size $(12288,1)$. - The corresponding vector: $[x_0,x_1,...,x_{12287}]^T$ is then multiplied by the weight matrix $W^{[1]}$ of size $(n^{[1]}, 12288)$.- You then add a bias term and take its relu to get the following vector: $[a_0^{[1]}, a_1^{[1]},..., a_{n^{[1]}-1}^{[1]}]^T$.- You multiply the resulting vector by $W^{[2]}$ and add your intercept (bias). - Finally, you take the sigmoid of the result. If it is greater than 0.5, you classify it to be a cat. General methodologyAs usual you will follow the Deep Learning methodology to build the model: 1. Initialize parameters / Define hyperparameters 2. Loop for num_iterations: a. Forward propagation b. Compute loss function c. Backward propagation d. Update parameters (using parameters, and grads from backprop) 4. Use trained parameters to predict labelsLet's now implement those the model! **Question**: Use the helper functions you have implemented in the previous assignment to build a 2-layer neural network with the following structure: *LINEAR -> RELU -> LINEAR -> SIGMOID*. The functions you may need and their inputs are:```pythondef initialize_parameters(n_x, n_h, n_y): ... return parameters def linear_activation_forward(A_prev, W, b, activation): ... return A, cachedef compute_loss(AL, Y): ... return lossdef linear_activation_backward(dA, cache, activation): ... return dA_prev, dW, dbdef update_parameters(parameters, grads, learning_rate): ... return parameters``` ###Code ### CONSTANTS DEFINING THE MODEL #### n_x = 12288 # num_px * num_px * 3 n_h = 7 n_y = 1 layers_dims = (n_x, n_h, n_y) def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_loss=False): """ Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID. Arguments: X -- input data, of shape (n_x, number of examples) Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) layers_dims -- dimensions of the layers (n_x, n_h, n_y) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_loss -- If set to True, this will print the loss every 100 iterations Returns: parameters -- a dictionary containing W1, W2, b1, and b2 """ np.random.seed(1) grads = {} losses = [] # to keep track of the loss m = X.shape[1] # number of examples (n_x, n_h, n_y) = layers_dims # Initialize parameters dictionary, by calling one of the functions you'd previously implemented ### START CODE HERE ### (≈ 1 line of code) parameters = initialize_parameters(n_x, n_h, n_y) ### END CODE HERE ### # Get W1, b1, W2 and b2 from the dictionary parameters. W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: "X, W1, b1, W2, b2". Output: "A1, cache1, A2, cache2". ### START CODE HERE ### (≈ 2 lines of code) A1, cache1 = linear_activation_forward(X, W1, b1, "relu") A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid") ### END CODE HERE ### # Compute loss ### START CODE HERE ### (≈ 1 line of code) loss = compute_loss(A2, Y) ### END CODE HERE ### # Initializing backward propagation dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))/m # Backward propagation. Inputs: "dA2, cache2, cache1". Outputs: "dA1, dW2, db2; also dA0 (not used), dW1, db1". ### START CODE HERE ### (≈ 2 lines of code) dA1, dW2, db2 = linear_activation_backward(dA2, cache2, "sigmoid") dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "relu") ### END CODE HERE ### # Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2 ### START CODE HERE ### (≈ 4 lines of code) grads['dW1'] = dW1 grads['db1'] = db1 grads['dW2'] = dW2 grads['db2'] = db2 ### END CODE HERE ### # Update parameters. ### START CODE HERE ### (approx. 1 line of code) parameters = update_parameters(parameters, grads, learning_rate) ### END CODE HERE ### # Retrieve W1, b1, W2, b2 from parameters W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Print the loss every 100 training example if print_loss and i % 100 == 0: print("Loss after iteration {}: {}".format(i, np.squeeze(loss))) if print_loss and i % 100 == 0: losses.append(loss) # plot the loss plt.plot(np.squeeze(losses)) plt.ylabel('loss') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() return parameters parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), learning_rate=0.003, num_iterations = 7000, print_loss=True) ###Output Loss after iteration 0: 0.69304973566 Loss after iteration 100: 0.66358362054 Loss after iteration 200: 0.648272816823 Loss after iteration 300: 0.644370511753 Loss after iteration 400: 0.639397427608 Loss after iteration 500: 0.632374537296 Loss after iteration 600: 0.6222656789 Loss after iteration 700: 0.608749048358 Loss after iteration 800: 0.593317668528 Loss after iteration 900: 0.577051173035 Loss after iteration 1000: 0.559815202387 Loss after iteration 1100: 0.54260614129 Loss after iteration 1200: 0.524435258075 Loss after iteration 1300: 0.50629684946 Loss after iteration 1400: 0.488534059566 Loss after iteration 1500: 0.470691257416 Loss after iteration 1600: 0.452698521786 Loss after iteration 1700: 0.430112987407 Loss after iteration 1800: 0.40371365539 Loss after iteration 1900: 0.379037148229 Loss after iteration 2000: 0.355524892053 Loss after iteration 2100: 0.334077833925 Loss after iteration 2200: 0.31377615142 Loss after iteration 2300: 0.295163988192 Loss after iteration 2400: 0.277980886773 Loss after iteration 2500: 0.26172341494 Loss after iteration 2600: 0.24673638906 Loss after iteration 2700: 0.232723655169 Loss after iteration 2800: 0.219602225882 Loss after iteration 2900: 0.207130090975 Loss after iteration 3000: 0.1956742445 Loss after iteration 3100: 0.184661640146 Loss after iteration 3200: 0.173723977661 Loss after iteration 3300: 0.163918461958 Loss after iteration 3400: 0.154874149793 Loss after iteration 3500: 0.145669560808 Loss after iteration 3600: 0.137200381502 Loss after iteration 3700: 0.129435190953 Loss after iteration 3800: 0.122515828644 Loss after iteration 3900: 0.11610318636 Loss after iteration 4000: 0.110072191657 Loss after iteration 4100: 0.10406774094 Loss after iteration 4200: 0.0984590798725 Loss after iteration 4300: 0.0935180956028 Loss after iteration 4400: 0.0890586140023 Loss after iteration 4500: 0.0847087401318 Loss after iteration 4600: 0.0808851905079 Loss after iteration 4700: 0.0774511672646 Loss after iteration 4800: 0.0739222258769 Loss after iteration 4900: 0.070827789301 Loss after iteration 5000: 0.0679165909286 Loss after iteration 5100: 0.0651693765764 Loss after iteration 5200: 0.062481603939 Loss after iteration 5300: 0.0599379765221 Loss after iteration 5400: 0.0575760866184 Loss after iteration 5500: 0.0553193553812 Loss after iteration 5600: 0.0531034948389 Loss after iteration 5700: 0.0510428466166 Loss after iteration 5800: 0.0490311649651 Loss after iteration 5900: 0.0470733380646 Loss after iteration 6000: 0.045215782521 Loss after iteration 6100: 0.0434024427312 Loss after iteration 6200: 0.0416500470376 Loss after iteration 6300: 0.0399726228339 Loss after iteration 6400: 0.0383499390173 Loss after iteration 6500: 0.0368139336141 Loss after iteration 6600: 0.0353062856631 Loss after iteration 6700: 0.0338848414523 Loss after iteration 6800: 0.032537506473 Loss after iteration 6900: 0.0312628723581 ###Markdown **Expected Output**: **Loss after iteration 0** 0.6930497356599888 **Loss after iteration 100** 0.6464320953428849 **...** ... **Loss after iteration 2400** 0.048554785628770206 Good thing you built a vectorized implementation! Otherwise it might have taken 10 times longer to train this.Now, you can use the trained parameters to classify images from the dataset. ***Exercise:*** - Implement the forward function- Implement the predict function below to make prediction on test_images ###Code def two_layer_forward(X, parameters): """ Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- last post-activation value caches -- list of caches containing: every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2) the cache of linear_sigmoid_forward() (there is one, indexed L-1) """ caches = [] A = X # Implement LINEAR -> RELU. Add "cache" to the "caches" list. ### START CODE HERE ### (approx. 3 line of code) W1, b1 = parameters["W1"], parameters["b1"] A1, cache1 = linear_activation_forward(A, W1, b1, "relu") caches.append(cache1) ### END CODE HERE ### # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list. ### START CODE HERE ### (approx. 3 line of code) W2, b2 = parameters["W2"], parameters["b2"] A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid") caches.append(cache2) ### END CODE HERE ### assert(A2.shape == (1,X.shape[1])) return A2, caches def predict(X, y, parameters): """ This function is used to predict the results of a L-layer neural network. Arguments: X -- data set of examples you would like to label parameters -- parameters of the trained model Returns: p -- predictions for the given dataset X """ m = X.shape[1] n = len(parameters) // 2 # number of layers in the neural network p = np.zeros((1,m)) # Forward propagation ### START CODE HERE ### (≈ 1 lines of code) probas, caches = two_layer_forward(X, parameters) ### END CODE HERE ### # convert probas to 0/1 predictions for i in range(0, probas.shape[1]): ### START CODE HERE ### (≈ 4 lines of code) if(probas[0][i] > 0.5): p[0][i] = 1 else: p[0][i] = 0 ### END CODE HERE ### print("Accuracy: " + str(float(np.sum((p == y)/float(m))))) return p predictions_train = predict(train_x, train_y, parameters) predictions_test = predict(test_x, test_y, parameters) ###Output Accuracy: 0.76 ###Markdown ***Exercise:***Identify the hyperparameters in the model and For each hyperparameter- Briefly explain its role- Explore a range of values and describe their impact on (a) training loss and (b) test accuracy- Report the best hyperparameter value found.Note: Provide your results and explanations in the report for this question. **Hyperparameters**The hyperparameters are:1. Learning rate - It is used for updating the parameters of the neural network that is the weights and biases of the neural network. It controls the amount of update that needs to take place so that we are able to reach the minima of the loss function.2. Epochs - It represents the number of times the network sees the data and adjusts its parameters for optimal learning.**Values of Hyperparameters tried:**1. Learning rate = 0.005, Epochs = 2000, Training loss = 0.187, Testing accuracy: 70%2. Learning rate = 0.005, Epochs = 3000, Training loss = 0.073, Testing accuracy: 72%3. Learning rate = 0.005, Epochs = 4000, Training loss = 0.036, Testing accuracy: 72%4. Learning rate = 0.001, Epochs = 2000, Training loss = 0.617, Testing accuracy: 34%5. Learning rate = 0.001, Epochs = 3000, Training loss = 0.56, Testing accuracy: 34%6. Learning rate = 0.001, Epochs = 4000, Training loss = 0.5, Testing accuracy: 34%7. Learning rate = 0.01, Epochs = 2000, Training loss = 0.05, Testing accuracy: 72%8. Learning rate = 0.01, Epochs = 3000, Training loss = 0.01, Testing accuracy: 72%9. Learning rate = 0.01, Epochs = 4000, Training loss = 0.008, Testing accuracy: 72%10. Learning rate = 0.05, Epochs = 2000, Training loss = 0.58, Testing accuracy: 46%11. Learning rate = 0.01, Epochs = 3000, Training loss = 0.36, Testing accuracy: 56%12. Learning rate = 0.03, Epochs = 2000, Training loss = 0.0058, Testing accuracy: 72%13. Learning rate = 0.03, Epochs = 3000, Training loss = 0.0024, Testing accuracy: 72%14. Learning rate = 0.003, Epochs = 4000, Training loss = 0.11, Testing accuracy: 76%15. Learning rate = 0.003, Epochs = 7000, Training loss = 0.047, Testing accuracy: 76%16. Learning rate = 0.003, Epochs = 8000, Training loss = 0.021, Testing accuracy: 74%17. Learning rate = 0.002, Epochs = 4000, Training loss = 0.24, Testing accuracy: 76%18. Learning rate = 0.002, Epochs = 6000, Training loss = 0.113, Testing accuracy: 74%19. Learning rate = 0.002, Epochs = 8000, Training loss = 0.06, Testing accuracy: 74%18. Learning rate = 0.0025, Epochs = 6000, Training loss = 0.07, Testing accuracy: 74%19. Learning rate = 0.0025, Epochs = 8000, Training loss = 0.03, Testing accuracy: 72%**Optimal hyperparameters found**1. Learning rate = 0.0032. Epochs = 7000 Results AnalysisFirst, let's take a look at some images the 2-layer model labeled incorrectly. This will show a few mislabeled images. ###Code def print_mislabeled_images(classes, X, y, p): """ Plots images where predictions and truth were different. X -- dataset y -- true labels p -- predictions """ a = p + y mislabeled_indices = np.asarray(np.where(a == 1)) plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots num_images = len(mislabeled_indices[0]) for i in range(num_images): index = mislabeled_indices[1][i] plt.subplot(2, num_images, i + 1) plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest') plt.axis('off') plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8")) print_mislabeled_images(classes, test_x, test_y, predictions_test) ###Output _____no_output_____ ###Markdown ***Exercise:*** Identify a few types of images that tends to perform poorly on the model **Answer**The model performs poorly when the cat is at certain angle or rotated at some angle, which makes it classify it as a non-cat class. Now, lets use the same architecture to predict sentiment of movie reviews. In this section, most of the implementation is already provided. The exercises are mainly to understand what the workflow is when handling the text data. ###Code import re ###Output _____no_output_____ ###Markdown Dataset **Problem Statement**: You are given a dataset ("train_imdb.txt", "test_imdb.txt") containing: - a training set of m_train reviews - a test set of m_test reviews - the labels for the training examples are such that the first 50% belong to class 1 (positive) and the rest 50% of the data belong to class 0(negative) Let's get more familiar with the dataset. Load the data by completing the function and run the cell below. ###Code def load_data(train_file, test_file): train_dataset = [] test_dataset = [] # Read the training dataset file line by line for line in open(train_file, 'r'): train_dataset.append(line.strip()) for line in open(test_file, 'r'): test_dataset.append(line.strip()) return train_dataset, test_dataset train_file = "data/train_imdb.txt" test_file = "data/test_imdb.txt" train_dataset, test_dataset = load_data(train_file, test_file) # This is just how the data is organized. The first 50% data is positive and the rest 50% is negative for both train and test splits. y = [1 if i < len(train_dataset)*0.5 else 0 for i in range(len(train_dataset))] ###Output _____no_output_____ ###Markdown As usual, lets check our dataset ###Code # Example of a review index = 10 print(train_dataset[index]) print ("y = " + str(y[index])) # Explore your dataset m_train = len(train_dataset) m_test = len(test_dataset) print ("Number of training examples: " + str(m_train)) print ("Number of testing examples: " + str(m_test)) ###Output Number of training examples: 1001 Number of testing examples: 201 ###Markdown Pre-Processing From the example review, you can see that the raw data is really noisy! This is generally the case with the text data. Hence, Preprocessing the raw input and cleaning the text is essential. Please run the code snippet provided below.**Exercise**: Explain what pattern the model is trying to capture using re.compile in your report. **Answer**1. re.compile() removes special characters like ', . " etc and makes all characters in lowercase. It is learning properties from words. ###Code REPLACE_NO_SPACE = re.compile("(\.)|(\;)|(\:)|(\!)|(\')|(\?)|(\,)|(\")|(\()|(\))|(\[)|(\])|(\d+)") REPLACE_WITH_SPACE = re.compile("(<br\s*/><br\s*/>)|(\-)|(\/)") NO_SPACE = "" SPACE = " " def preprocess_reviews(reviews): reviews = [REPLACE_NO_SPACE.sub(NO_SPACE, line.lower()) for line in reviews] reviews = [REPLACE_WITH_SPACE.sub(SPACE, line) for line in reviews] return reviews train_dataset_clean = preprocess_reviews(train_dataset) test_dataset_clean = preprocess_reviews(test_dataset) # Example of a clean review index = 10 print(train_dataset_clean[index]) print ("y = " + str(y[index])) ###Output i liked the film some of the action scenes were very interesting tense and well done i especially liked the opening scene which had a semi truck in it a very tense action scene that seemed well done some of the transitional scenes were filmed in interesting ways such as time lapse photography unusual colors or interesting angles also the film is funny is several parts i also liked how the evil guy was portrayed too id give the film an out of y = 1 ###Markdown Vectorization Now lets create a feature vector for our reviews based on a simple bag of words model. So, given an input text, we need to create a numerical vector which is simply the vector of word counts for each word of the vocabulary. Run the code below to get the feature representation. ###Code from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(binary=True, stop_words="english", max_features=2000) cv.fit(train_dataset_clean) X = cv.transform(train_dataset_clean) X_test = cv.transform(test_dataset_clean) ###Output _____no_output_____ ###Markdown CountVectorizer provides a sparse feature representation by default which is reasonable because only some words occur in individual example. However, for training neural network models, we generally use a dense representation vector. ###Code X = np.array(X.todense()).astype(float) X_test = np.array(X_test.todense()).astype(float) y = np.array(y) ###Output _____no_output_____ ###Markdown Model ###Code from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val = train_test_split( X, y, train_size = 0.80 ) # This is just to correct the shape of the arrays as required by the two_layer_model X_train = X_train.T X_val = X_val.T y_train = y_train.reshape(1,-1) y_val = y_val.reshape(1,-1) ### CONSTANTS DEFINING THE MODEL #### n_x = X_train.shape[0] n_h = 200 n_y = 1 layers_dims = (n_x, n_h, n_y) ###Output _____no_output_____ ###Markdown We will use the same two layer model that you completed in the previous section for training. ###Code parameters = two_layer_model(X_train, y_train, layers_dims = (n_x, n_h, n_y), learning_rate=0.05, num_iterations = 3000, print_loss=True) ###Output Loss after iteration 0: 0.693079416169 Loss after iteration 100: 0.686569463673 Loss after iteration 200: 0.653746782902 Loss after iteration 300: 0.513637888328 Loss after iteration 400: 0.320195643458 Loss after iteration 500: 0.201724848093 Loss after iteration 600: 0.134819976219 Loss after iteration 700: 0.0948401309064 Loss after iteration 800: 0.0695863625855 Loss after iteration 900: 0.0528916264559 Loss after iteration 1000: 0.041486399968 Loss after iteration 1100: 0.0334640145333 Loss after iteration 1200: 0.027650556749 Loss after iteration 1300: 0.0233134006421 Loss after iteration 1400: 0.0199911510628 Loss after iteration 1500: 0.0173876238095 Loss after iteration 1600: 0.0153066762094 Loss after iteration 1700: 0.0136146620512 Loss after iteration 1800: 0.0122180889721 Loss after iteration 1900: 0.0110502249368 Loss after iteration 2000: 0.010062214655 Loss after iteration 2100: 0.00921766338755 Loss after iteration 2200: 0.00848910281476 Loss after iteration 2300: 0.00785537317867 Loss after iteration 2400: 0.00730000461864 Loss after iteration 2500: 0.00681003094208 Loss after iteration 2600: 0.00637506645976 Loss after iteration 2700: 0.00598679650114 Loss after iteration 2800: 0.00563846787071 Loss after iteration 2900: 0.0053244913391 ###Markdown Predict the review for our movies! ###Code predictions_train = predict(X_train, y_train, parameters) predictions_val = predict(X_val, y_val, parameters) ###Output Accuracy: 0.850746268657 ###Markdown Results AnalysisLet's take a look at some examples the 2-layer model labeled incorrectly ###Code def print_mislabeled_reviews(X, y, p): """ Plots images where predictions and truth were different. X -- dataset y -- true labels p -- predictions """ a = p + y mislabeled_indices = np.asarray(np.where(a == 1)) plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots num_reviews = len(mislabeled_indices[0]) for i in range(num_reviews): index = mislabeled_indices[1][i] print((" ").join(cv.inverse_transform(X[index])[0])) print("Prediction: " + str(int(p[0,index])) + " \n Class: " + str(y[0,index])) print_mislabeled_reviews(X_val.T, y_val, predictions_val) ###Output actors attempt beauty believable big bit charismatic claims definitely delivery did didnt disappointing disaster entertained fact film fine group job line looked lost miss offensive performance playing plays plot project recommend rent scenes screen seen strong talent wish writing Prediction: 0 Class: 1 acting add annoying bad change character dicaprio did director does eyes film filmmakers films glad going good great half hand hardly impressive just kate learned lesson love mean million movie opinion oscar performance possible really romance romantic second ship shouldnt single sit stories story sure talented think thinking time times titanic try watching win wonderful wont worst Prediction: 0 Class: 1 anna appearance away bad better bible big black blue book boys build capture cat catch chaos charles child city comic connected cops cult deal didnt doesnt earth edge exactly extreme far favorite fictional fine finished followed fond form fun gang gas genius giant god going good got government green guy guys half happening happens hard havent having heroes hey hospital include japanese join just kind know known like liked line looks lot make match monster movie mysterious naked named names new nice oh order paid past people place places police power problem project puts quickly red remains right seconds seeing series set sexy soon sorts special starts story taking thanks thats theres theyre thing tom unfortunately use using villains violence want whos woman world yeah year youd Prediction: 0 Class: 1 able action add admit adult ahead anna bit black boy characters cinematography come deserves disappointed disappointment does dont doubt downright elements end entirely expect expecting fear film forget genre girls guys hopes imagination instead intense knew leave lesbian level like little looking lot love managed memorable mid movie ok performances play pleasure prepared read real realized really received romance school secret shot shown soon stars story straight sudden teenagers theyre think time times trying unexpected watching way white women wont wrong years youll Prediction: 0 Class: 1 actor actually adults bringing calls cast child children doing era eyes famous focus fun given guess guy history host interesting john julia kenneth kind king like martin movie natural news park police provided question really say seeing short shouldnt simply smith sort story thought true version voice voices woman work worth wouldnt young Prediction: 0 Class: 1 based got involved movie moving mystery oscar review script slow star Prediction: 1 Class: 0 actually ahead better box budget burning character charlie come damn development did didnt dont enjoy eye fake far film flick forced genre good guinea guts hand hear heard horror hours interested just know like listen looks lot low making men minutes movie naturally offer painful pretty really recommend say scene scenes second seen set sharp short simply snuff story think thought throwing told torture trying ultimately unless various watching ways went woman worst Prediction: 0 Class: 1 cause early effort government heavy past people problems production propaganda short spending sudden time truly using war window Prediction: 1 Class: 0 ability acting actor ages anti better cheap cinema complete confused day decent direction disappointed disappointment does dont dull dvd explanation film finally finding flat gate good got great guess intriguing kind lead like liked love main meet mouth movie performance plot poor premise remind required result rip saw say store story tell thought took tv wanted way week written Prediction: 1 Class: 0 action adventure adventures bad camp character characters check crew decided doc elements familiar fan fans feel feeling film good hero heroes im james jones just know long lot major minutes movie movies music number ones promise provided really resulting savage say seeing somewhat spirit star thats theres throw time trying unfortunate way Prediction: 0 Class: 1 better body cast central cinema come coming comments company computer decides die entertaining exist failed fall fan film films genius gets getting going great hard hey highly hollywood house idea interested judging latest lesson lessons like make making man member money movie movies near potential premise puts review reviews role scenes seen set shock soon stupid taken takes type unless unrelated wish wow writer writing yes zero Prediction: 1 Class: 0 admit almighty attempt big bruce carrey cast cheesy comedy dont end enjoyable fan feel funny gets gone havent help hilarious ill im jim just know let light like movie movies music note poor positive really rest reviews saying seen shows somewhat start steve thinking want writers youre Prediction: 0 Class: 1 action age body brain building certainly computer crazy damme daughter dead entertaining especially fan fi fights folks genius goes going goldberg good government guess hes humor just keeps king lame later latest like manages mean named new original particularly perfect power pretty pro reason run sci sequel shoot site snake soldiers sort step super takes thriller train usual van war white working wrong year years youre Prediction: 1 Class: 0 acting animals best better die dont entire episode episodes funny good horrible ice just killing know life like movie obviously plot pro problem really remember right scene scenes season second series shocking suspense think torture turns victims watch women wonderful worst Prediction: 0 Class: 1 bunch doesnt feel got laugh laughed left like loud make masterpiece movie ok purpose smile times viewer worth Prediction: 0 Class: 1 acting away beautifully biggest burt came character drinking fact failure fast fell general help hoping job movie movies night notice played promising real right screen single state thats walk way Prediction: 1 Class: 0 charlie dont eye fake film final harder hot im know like look looks real said say scene scenes sure tell thing truth Prediction: 0 Class: 1 actually ago american begin begins big bring buy century circumstances couple does doesnt effects emotional flicks follows happen highly home house husband impact john life like man masterpiece mysterious old outside plot recommended simple special story strange supposedly things turn unknown went woman world Prediction: 0 Class: 1 absolutely add bad best better boat book brought cases classic clear cliché close course critics deserves didnt disappointed exactly excitement family felt field film finally giving grew hard hear hero heroes home ill im instead know latest like line mind missing musical names nature non offensive old particularly past poor professional race real reality reviewer ridiculous right rock sadly said scene scenes score sense shot shots shows smile sound spot starting supposed taking talking theres theyve thrill time took town versions water wonderful years yes Prediction: 1 Class: 0 ability able accident action actresses actually aspect away bad believe better bit blood brothers cause cgi charlie crap crime cut days deal death disturbing does doesnt dont effects especially eyes fact fake favorite film films footage forget funny happens hope horror im instead leaving like look lot make makers making marry money movie movies overall people plot point porn probably pull rape rating real saying says scene scenes seen series shocking snuff sound stand stars sucked sucks super supposed sure talent talking thing thinking time tried visual visuals want wanted wasnt watch wouldnt Prediction: 0 Class: 1 achieve acting approach art artistic background box brief cast cheap cinema close come cons considered consists contemporary country dealing deals deserves director fact fan fit good half hard history hope hot huge job just knows like make manage masterpiece meant media members money movie naked near office ones opinion perfect perfectly provide purpose real roles short single small success talent theatrical thing time touching tried usual waiting women word work Prediction: 1 Class: 0 acting actors admit annoying arent art bad ball beginning best better big billy bits book calling camera case character characters cinematic come coming cons crouse cusack david definitely dialogue did didnt direct directed does doesnt dont early end ending entertaining expecting extremely far feel film filmed films flat forth free fun game games gets getting girl going good guy half help heres hes hour house ill im inner involved isnt james john just keeps lesson let level like lindsay line lines little look looked lose mamet mantegna mark maybe mean men middle mind minutes moves movie narration nature new ones opening pick play precious pretty problem quality questions read reading real realize really result ring roll room scene second shes sort sound sounds speaking standard start stick story strange stuff supposed theatre theyre things true want wants watch way weird whats words work wouldnt write Prediction: 0 Class: 1 accept ago army away bad begins body bucks budget chase comes couple dolph door energy especially exist explained feel feeling fight fighting films flash flick follow forward goes good happens hell human idea ideas involved isnt just key lacks like long looks low lukas make man master member merely middle movie movies needless new order place plays potential previous satan say scene scenes secret sense sort stars story study sucks supposed sure takes theres thrown time underground wish wont years york youll Prediction: 1 Class: 0 absolutely acted art audience bad bar beginning came chinese come coming comments course deep didnt director doing drawn end ending entertaining essentially experience faces fact fantastic far feel festival film final following forget fresh fun gonna government half happy hard hidden hollywood hour hours im immediately incredibly intelligent intriguing judging just land late life likable long looked lot loved make making match meaning mention natural new number pain painful point post probably problem promising reading really reason reviews right russian said saw say sense sharp simply society sounds spent started state talking thank theatre thought time took try utter utterly view want wanted warned way week whats whatsoever words working years yes Prediction: 1 Class: 0 actually ago bad better book church course does enjoyable familiar film forgotten forward good hadnt heard hour instantly job know laid let long minute minutes missed mr nearly overall quick read really school second sense short simply story tales thats thing time trilogy watched worked write years Prediction: 0 Class: 1 actors ask blood cares character conclusion content crap crew damn day disturbing effort ends episode exception family fan fate gets going gore great gross hopes horror hour imagine lot mindless new performances pointless producers production reason season sense series shock stories story tend thinking utter values violence work worse Prediction: 1 Class: 0 absolutely acting bits casting cheap close come comments completely couldve did direction edge end film gone humor intense literally little loved mediocre movie number perfect phone points read rest ring scary script second spot story thrill time years Prediction: 0 Class: 1 ann cause characters comedy compared computer connection considered day days did dont end entertainment ex fight film films flight future george given going got hand having help hes home human including instead isnt issue just kids kill killed know lesson life like live losing lost love make making man matter maybe meets money necessary people pictures plan plays plot prior project rich school sets shows stars step street streets stupid technology tender theyre things think thrown treasure used using vote wall wants war wasnt woman work world written years young Prediction: 0 Class: 1 actors alive based childhood documentary got kill know man mission monster movie people personality played rate real scenes set seven turn used women work Prediction: 0 Class: 1 film forgotten late little long makers money movie night present subtle time todays tv Prediction: 0 Class: 1
notebooks/dataprep/01a-UniProtProtein.ipynb
###Markdown UniProt Viral and Host Protein Data**[Work in progress]**This notebook downloads and standardizes viral and host protein data from UniProt for ingestion into the Knowledge Graph.Data source: [UniProt](https://www.uniprot.org/)Authors: Peter Rose ([email protected]) ###Code import os import re import hashlib import urllib import pandas as pd import numpy as np from pathlib import Path pd.options.display.max_rows = None # display all rows pd.options.display.max_columns = None # display all columns NEO4J_IMPORT = Path(os.getenv('NEO4J_IMPORT')) print(NEO4J_IMPORT) ###Output /Users/peter/Library/Application Support/com.Neo4j.Relate/data/dbmss/dbms-8bf637fc-0d20-4d9f-9c6f-f7e72e92a4da/import ###Markdown Get list of organisms in the Knowledge Graph ###Code organisms = pd.read_csv("../../reference_data/Organism.csv", dtype=str) # exclude organisms without an NCBI taxonomy id organisms = organisms[organisms['id'].str.startswith('taxonomy')] # remove CURIE organisms['taxonomy'] = organisms['id'].apply(lambda x: x.split(':')[1]) taxonomy_ids = organisms['taxonomy'].unique() ###Output _____no_output_____ ###Markdown Download data from UniProt ###Code columns = 'id,entry%20name,p,sequence,length,protein%20names,reviewed,organism-id,feature(CHAIN),feature(PEPTIDE),go(biological%20process)' dfs = list() for taxon in taxonomy_ids: url = f'https://www.uniprot.org/uniprot/?query=organism:{taxon}&columns={columns}&format=tab' try: df = pd.read_csv(url, sep='\t', dtype='str') if df.shape[0] > 0: print(f'Downloaded {df.shape[0]} proteins for taxonomy id {taxon}') dfs.append(df) else: print(f'Downloaded 0 proteins for taxonomy id {taxon}') except: print(f'Downloaded 0 proteins for taxonomy id {taxon}') unp = pd.concat(dfs) unp.reset_index(drop=True,inplace=True) unp.fillna('', inplace=True) print(unp.shape) unp.tail() unp['reviewed'] = unp['Status'].apply(lambda s: 'True' if s == 'reviewed' else 'False') ###Output _____no_output_____ ###Markdown Format synonymes ###Code unp.query("Entry == 'P0DTC2'")['Protein names'].values ###Output _____no_output_____ ###Markdown Remove terms in brackets, e.g., [Cleaved into: ...]["Spike glycoprotein (S glycoprotein) (E2) (Peplomer protein) [Cleaved into: Spike protein S1; Spike protein S2; Spike protein S2'] ###Code unp['synonymes'] = unp['Protein names'].str.replace("\\[.+\\]", "") unp.query("Entry == 'P0DTC2'")['synonymes'].values ###Output _____no_output_____ ###Markdown Convert synonymes to a semicolon separated list to represent these one to many relationships in a CSV file. ###Code unp['synonymes'] = unp['synonymes'].str.replace('(', ';') unp['synonymes'] = unp['synonymes'].str.replace(' ;', ';') unp['synonymes'] = unp['synonymes'].str.replace(')', '') unp['synonymes'] = unp['synonymes'].str.strip() unp.query("Entry == 'P0DTC2'")['synonymes'].values unp.head() unp.query("Entry == 'P01042'")['Chain'].values unp.query("Entry == 'P01042'")['Peptide'].values def parse_feature_record(record, feature_type): items = record.split(';') feature = np.empty(5, dtype=object) feature[0] = feature_type for item in items: item = item.strip() if '..' in item: start_end = item.split('..') # in a few cases a '?' is used to represent an unknown start or end, check if it's a digit if start_end[0].isdigit(): feature[1] = start_end[0] else: feature[1] = '' if start_end[1].isdigit(): feature[2] = start_end[1] else: feature[2] = '' elif item.startswith("/note="): name = item[6:].replace('\"', '') feature[3] = name elif item.startswith("/id="): pro_id = item[4:].replace('\"', '') feature[4] = 'uniprot.chain:' + pro_id return feature def parse_features(row): chain_features = [] if 'CHAIN' in row['Chain']: chains = row['Chain'].split('CHAIN') if chains[0] == '': chains = chains[1:] chain_features = [parse_feature_record(chain, 'CHAIN') for chain in chains] protein_features = [] # Full-length (coding sequence) proteins are inconsistenly handled in UniProt. # For some entries, the full-length protein is included # in the chain features (e.g. P0DTD1), for others it's not (e.g., P01042) # Check if full-length protein is included in chain list full_length = False for f in chain_features: if f[1] == '1' and f[2] == row['Length']: full_length = True break # Add entry if full-length protein is not in chain list if not full_length: protein_name = row['Protein names'].split('(')[0] protein_features = [np.array(['PROTEIN','1', row['Length'], protein_name,''], dtype=object)] peptide_features = [] if 'PEPTIDE' in row['Peptide']: peptides = row['Peptide'].split('PEPTIDE') if peptides[0] == '': peptides = peptides[1:] peptide_features = [parse_feature_record(peptide, 'PEPTIDE') for peptide in peptides] return protein_features + chain_features + peptide_features unp['Features'] = unp.apply(parse_features, axis=1) unp = unp.explode('Features') unp[['type', 'start', 'end', 'name', 'proId']] = unp.apply(lambda row: row['Features'], axis=1, result_type="expand") ###Output _____no_output_____ ###Markdown Handle missing values ###Code unp.fillna('', inplace=True) unp.head(50) ###Output _____no_output_____ ###Markdown Cleave sequences into peptides ###Code def get_subsequence(row): if row['start'].isdigit() and row['end'].isdigit(): start = int(row['start']) end = int(row['end']) sequence = row['Sequence'] return sequence[start-1: end] else: return '' unp['sequence'] = unp.apply(lambda row: get_subsequence(row), axis=1) ###Output _____no_output_____ ###Markdown Set flag if protein chain is full length ###Code unp['fullLength'] = (unp['start'] == '1') & (unp['end'] == unp['Length']) unp['name'] = unp['name'].str.strip() def set_synonymes(row): if row['fullLength']: return row['synonymes'] else: return row['name'] ###Output _____no_output_____ ###Markdown Cleaved protein, should not inherit synonymes from the full length protein ###Code unp['synonymes'] = unp.apply(set_synonymes, axis=1) unp.head(50) unp.rename(columns={'Organism ID': 'taxonomyId','Entry': 'accession', 'Entry name': 'entryName'}, inplace=True) ###Output _____no_output_____ ###Markdown Assign unique identifiersmd5 hashcodes for the protein sequence and CURIEs for accession and taxonomyId ###Code unp['id'] = unp['sequence'].apply(lambda seq: 'md5:' + hashlib.md5(seq.encode()).hexdigest()) # disambiguate id by taxonomyId (same sequence for different organisms) unp['id'] = unp['id'] + '-' + unp['taxonomyId'] unp['accession'] = 'uniprot:' + unp['accession'] unp['taxonomyId'] = 'taxonomy:' + unp['taxonomyId'] unp.query("accession == 'uniprot:P01042'") ###Output _____no_output_____ ###Markdown Save proteins ###Code columns = ['id', 'name', 'synonymes', 'accession', 'entryName', 'proId', 'taxonomyId','sequence', 'start', 'end', 'fullLength', 'reviewed'] unp.to_csv(NEO4J_IMPORT / '01a-UniProtProtein.csv', columns=columns, index = False) unp.head() ###Output _____no_output_____
examples/water_boiler/base_case_no_control_rods/.ipynb_checkpoints/water_boiler-checkpoint.ipynb
###Markdown Water BoilerThis is a description of the Water Boiler reactor - a homogeneous solution of Uranyl(14.7) Sulfate Solution in a hollow stainless steel sphere with a Beryllium Oxide reflector. The reactor was used in an experiment at LANL during the Manhattan Project. The goal of the project was to determine the critical mass of U-235 in a homogeneous solution with various reflectors used. A goal of the notebook will be to make extensive use of the Nuclear Data interface of OpenMC for all of the required data. ###Code import openmc import numpy as np import matplotlib.pyplot as plt %matplotlib inline ###Output _____no_output_____ ###Markdown Material Parameters and Calculations ###Code # the mass density of UO2-SO4 solution in water is needed import scipy.interpolate def get_UranylSulfate_solution_density(pct_us=0.299,temp=303): ''' input: pct_us: float, weight percent UO2-SO4 in water temp: float, temperature in K output: rho_us: float, mass density (g/cc) of the solution This is derived from Table 5 of IEU-SOL-THERM-004 ''' temp = temp-273.; # convert to C y = [0.51, 0.399, 0.299]; x = [15.,20.,25.,30.,35.,40.,50.]; z = [[1.7959,1.7926,1.7891,1.7854,1.7816,1.777,1.7696], [1.5283,1.5257,1.5228,1.5199,1.5166,1.5133,1.5064], [1.3499,1.3479,1.3455,1.3430,1.3403,1.3376,1.3314]]; f = scipy.interpolate.interp2d(x,y,z); rho_us = np.float64(f(temp,pct_us)); return rho_us # the atomic weight of enriched uranium is needed def get_Aw_U(enrichment): assert (enrichment<=1.0), "enrichment should be entered as a percentage" # assumes a fixed ratio in the percentage of U234 and U235. # i.e. the enrichment process keeps these two isotopes in the # same relative abundance U234_to_U235_ratio = 0.0055/0.72; Aw_U235 = openmc.data.atomic_mass('U235'); Aw_U234 = openmc.data.atomic_mass('U234'); Aw_U238 = openmc.data.atomic_mass('U238'); frac_235 = enrichment; frac_234 = frac_235*U234_to_U235_ratio; frac_238 = 1. - frac_235 - frac_234; aw = 1./(frac_235/Aw_U235 + frac_238/Aw_U238 + frac_234/Aw_U234); weight_frac = {}; weight_frac['U234']=frac_234; weight_frac['U235']=frac_235; weight_frac['U238']=frac_238; return aw,weight_frac # calculate atom densities of UO2-SO4 + H2O solution as a function # of Uranium enrichment, water temperature and Urynal Sulfate concentration def BoilerAtomDensities(enrich=0.1467,temp=303,conc=0.299): ''' input: enrich: w/o U-235 temp: solution temperature in K; conc: w/o concentration of Uranyl Sulfate in the water output: dictionary with the atom densities (atoms/b-cm) of all elements and nuclides in the solution this results in a 'not great, not terrible' agreement with the benchmark. must re-visit to make corrections ''' assert (temp > 288) and (temp < 323), 'temperature not in correlation limits'; assert (conc >= 0.299) and (conc <= 0.51), 'solution concentration not in correlation limits'; Na = 0.60221; # Avagadro's number x10**-24 AtomDensities = {}; rho_uranyl_sulf_sol = get_UranylSulfate_solution_density(conc,temp); rho_water = rho_uranyl_sulf_sol*(1-conc); rho_uranyl = rho_uranyl_sulf_sol*conc; Aw_234 = openmc.data.atomic_mass('U234'); Aw_235 = openmc.data.atomic_mass('U235'); Aw_238 = openmc.data.atomic_mass('U238'); Aw_S = openmc.data.atomic_weight('S'); Aw_H = openmc.data.atomic_weight('H'); Aw_O = openmc.data.atomic_weight('O'); Aw_U,U_weight_fracs = get_Aw_U(enrich); Aw_uranyl_sulf = Aw_U + 2.*Aw_O + Aw_S + 4.*Aw_O; Aw_h2o = 2.*Aw_H + Aw_O; mol_density_uranyl_sulf = (rho_uranyl/Aw_uranyl_sulf)*Na; mol_density_h2o = (rho_water/Aw_h2o)*Na; AtomDensities['H']=mol_density_h2o*2.; AtomDensities['O']=mol_density_h2o*1.; AtomDensities['O']+=mol_density_uranyl_sulf*4.; AtomDensities['S']=mol_density_uranyl_sulf*1.; AtomDensities['U234']=(mol_density_uranyl_sulf)*U_weight_fracs['U234']; #wrong but better AtomDensities['U235']=(mol_density_uranyl_sulf)*U_weight_fracs['U235']; AtomDensities['U238']=(mol_density_uranyl_sulf)*U_weight_fracs['U238']; return AtomDensities ###Output _____no_output_____ ###Markdown Solution Material ###Code sol_temp = 303; # K, Uranyl Sulfate and water solution temperature sol_conc = 0.299; # w/o of Uranyl Sulfate in the solution U_enrch = 0.1467; # w/o enrichment of U235 in Uranyl Sulfate sol_atom_densities = BoilerAtomDensities(enrich=U_enrch,temp=sol_temp,conc=sol_conc); sol = openmc.Material(name='sol'); sol.add_element('H',sol_atom_densities['H'],percent_type='ao'); sol.add_element('O',sol_atom_densities['O'],percent_type='ao'); sol.add_element('S',sol_atom_densities['S'],percent_type='ao'); sol.add_nuclide('U234',sol_atom_densities['U234'],percent_type='ao'); sol.add_nuclide('U235',sol_atom_densities['U235'],percent_type='ao'); sol.add_nuclide('U238',sol_atom_densities['U238'],percent_type='ao'); sol.add_s_alpha_beta('c_H_in_H2O'); ad_tot = 0.; for key in sol_atom_densities: ad_tot+=sol_atom_densities[key]; sol.set_density('atom/b-cm',ad_tot); ###Output _____no_output_____ ###Markdown Shell MaterialI will just use the nuclide and density information from PNNL-15870 Rev. 1 for Steel, Stainless 347. The composition and atom density for the nominal 347 SS material reported in the benchmark closely match the PNNL data. ###Code shell = openmc.Material(name='shell'); shell.add_element('C',0.003659); shell.add_element('Si',0.019559); shell.add_element('P',0.000798); shell.add_element('S',0.000514); shell.add_element('Cr',0.179602); shell.add_element('Mn',0.019998); shell.add_element('Fe',0.669338); shell.add_element('Ni',0.102952); shell.add_element('Nb',0.002365); shell.add_element('Ta',0.001214); shell.set_density('g/cc',8.0); ###Output _____no_output_____ ###Markdown Beryllium Oxide ReflectorThe reported composition and density for the Beryllium Oxide blocks in the benchmark differ *significantly* from PNNL-15870. This is owing to the quick-and-dirty fabrication of the blocks (and associated reduction in material density) as well as the high impurity content. ###Code beryl_ref = openmc.Material(name='beryl_ref'); beryl_ref.add_element('O',6.6210e-2); beryl_ref.add_element('Be',6.6210e-2); beryl_ref.add_element('B',3.0637e-7); beryl_ref.add_element('Co',5.6202e-7); beryl_ref.add_element('Ag',3.0706e-8); beryl_ref.add_element('Cd',7.3662e-8); beryl_ref.add_element('In',1.4423e-8); beryl_ref.add_s_alpha_beta('c_Be_in_BeO'); beryl_ref.set_density('g/cc',2.75); ###Output _____no_output_____ ###Markdown Graphite BaseThe beryllium semi-sphere sits in a base of graphite. No information is given on it's composition. It probably has a trivial impact on the model result but I will just use standard data for graphite ###Code grph = openmc.Material(name='grph'); grph.add_element('C',0.999999); grph.add_element('B',0.000001); grph.set_density('g/cc',1.7); grph.add_s_alpha_beta('c_Graphite'); ###Output _____no_output_____ ###Markdown Air outside the reactorI don't really care about the air for its interactions with neutrons; I really just want to include it as a material so I can more fully visualize the geometry. ###Code air = openmc.Material(name='air'); air.add_element('C',0.000150); air.add_element('N',0.784431); air.add_element('O',0.210748); air.add_element('Ar',0.004671); materials = openmc.Materials([sol,shell,beryl_ref,grph,air]); materials.export_to_xml(); ###Output _____no_output_____ ###Markdown GeometryCreate the geometry and plot. Not too complicated. Surfaces ###Code rx_origin = [0.,76.3214,0.]; ref_sphere = openmc.Sphere(y0=rx_origin[1],r=47.4210); tank_o = openmc.Sphere(y0=rx_origin[1],r=15.3614); tank_i = openmc.Sphere(y0=rx_origin[1],r=15.282); graph_base_cyl = openmc.YCylinder(r=47.4210); fill_drain_cav = openmc.YCylinder(r=4.445/2.); fill_drain_o = openmc.YCylinder(r=2.06375); fill_drain_i = openmc.YCylinder(r=1.905); plate_plane = openmc.YPlane(y0=0.); base_plane = openmc.YPlane(y0=34.4114); sphere_center_plane = openmc.YPlane(y0=rx_origin[1]); upper_plane = openmc.YPlane(y0=118.2314); bbox = openmc.model.RightCircularCylinder([0.,-10.,0.],140.,60.,axis='y',boundary_type='vacuum'); ###Output _____no_output_____ ###Markdown Cells ###Code colors = {} colors[grph]='black'; colors[shell]='silver'; colors[sol]='cadetblue'; colors[beryl_ref]='olive'; colors[air]='lightskyblue'; core = openmc.Cell(); core.fill = sol; core.region = (-tank_i) | (-fill_drain_i) & -bbox root = openmc.Universe(); root.add_cell(core); root.plot(origin=rx_origin,width=[200., 200.],pixels=[800,800], color_by='material',colors=colors); steel_tank_and_pipe = openmc.Cell(); steel_tank_and_pipe.fill = shell; #steel_tank_and_pipe.region = (+tank_i & -tank_o & ~(-fill_drain_i)) | \ # (+fill_drain_i & -fill_drain_o & +tank_i) & -bbox steel_tank_and_pipe.region = (+tank_i & -tank_o & ~(-fill_drain_i)) | \ (+fill_drain_i & -fill_drain_o & +tank_i) & -bbox; root = openmc.Universe(); root.add_cell(steel_tank_and_pipe); root.plot(origin=[0.,76.3214+15.,0.],width=[10., 10.],pixels=[400,400], color_by='material',colors=colors); # moved the origin around so the plot can resolve all surface areas in question root = openmc.Universe(); root.add_cells([core,steel_tank_and_pipe]); root.plot(origin=[0.,76.3214+15.,0.],width=[10., 10.],pixels=[400,400], color_by='material',colors=colors); # moved the origin around so the plot can resolve all surface areas in question ref = openmc.Cell(); ref.fill = beryl_ref; ref.region = (+tank_o & +fill_drain_o) & -ref_sphere & +base_plane & -upper_plane; root = openmc.Universe(); root.add_cells([ref,core,steel_tank_and_pipe]); root.plot(origin=rx_origin,width=[100., 100.],pixels=[400,400], color_by='material',colors=colors); graph_base = openmc.Cell(); graph_base.fill = grph; graph_base.region = ((-graph_base_cyl & +plate_plane & -base_plane & +fill_drain_o) | (-graph_base_cyl & +ref_sphere & +base_plane & -sphere_center_plane)); root = openmc.Universe(); root.add_cells([graph_base,ref,core,steel_tank_and_pipe]); root.plot(origin=rx_origin,width=[150., 180.],pixels=[800,800], color_by='material',colors=colors); outside = openmc.Cell(); outside.fill = air; outside.region = -bbox & (+graph_base_cyl | (+ref_sphere & -upper_plane) | (+upper_plane & +fill_drain_o) ) root = openmc.Universe(); root.add_cells([graph_base,ref,core,steel_tank_and_pipe,outside]); root.plot(origin=rx_origin,width=[150., 200.],pixels=[800,800], color_by='material',colors=colors); geometry = openmc.Geometry(); geometry.root_universe = root; geometry.export_to_xml(); ###Output _____no_output_____ ###Markdown Tallies ###Code cell_filter = openmc.CellFilter(core); N = 1001; energy_bins = np.logspace(-3,7,num=N); energy_filter = openmc.EnergyFilter(values=energy_bins); abs_core = openmc.Tally(name='abs_core'); abs_core.scores = ['absorption']; abs_core.filters = [cell_filter,energy_filter]; fission = openmc.Tally(name='fission'); fission.scores = ['fission']; fission.filters = [cell_filter,energy_filter]; fission_by_nuclide = openmc.Tally(name='fission_by_nuclide'); fission_by_nuclide.scores = ['fission']; fission_by_nuclide.nuclides = ['U234','U235','U238']; fission_by_nuclide.filters = [cell_filter,energy_filter]; capture = openmc.Tally(name='capture'); capture.scores = ['(n,gamma)']; capture.filters = [cell_filter,energy_filter]; capture_by_nuclide = openmc.Tally(name='capture_by_nuclide'); capture_by_nuclide.scores = ['(n,gamma)']; capture_by_nuclide.nuclides = ['U234','U238','H1','O16','S32']; capture_by_nuclide.filters = [cell_filter,energy_filter]; flux = openmc.Tally(name='flux'); flux.scores = ['flux']; flux.filters = [cell_filter,energy_filter]; tallies = openmc.Tallies([abs_core, flux, fission, capture, fission_by_nuclide, capture_by_nuclide]); tallies.export_to_xml(); settings = openmc.Settings(); settings.batches = 800; settings.inactive = 100; settings.particles = 25000; R = 15.; y_org = 76.3214; bounds = [-R,-R+y_org,-R,R,R+y_org,R]; uniform_dist = openmc.stats.Box(bounds[:3],bounds[3:], only_fissionable=True); settings.source = openmc.source.Source(space=uniform_dist); #settings.temperature['method']='interpolation'; settings.export_to_xml(); openmc.run() sp = openmc.StatePoint('statepoint.800.h5'); sp.tallies flux = sp.get_tally(name='flux'); flux_df = flux.get_pandas_dataframe(); flux_vals = flux_df['mean'].to_numpy(); energy_x = 0.5*(energy_bins[0:-1] + energy_bins[1:]); plt.loglog(energy_x,flux_vals); plt.grid(); plt.xlabel('Energy [eV]'); plt.ylabel('flux [n/cm**2-s]'); ###Output _____no_output_____ ###Markdown Notice the sharp dip in flux at about 10-20 eV. Presumably this is a resonance absorption peak for something in the core; I'd guess U-238. The logical nuclide to suspect is U-238 but there is no good reason not to at least look at the other cross sections, so I will import and plot the capture cross sections for all of the isotopes. ###Code OMC_DATA = "/home/sblair/OMC_DATA/endfb71_hdf5" u238_path = OMC_DATA + "/U238.h5"; u238 = openmc.data.IncidentNeutron.from_hdf5(u238_path); u238_capture = u238[102]; s32_path = OMC_DATA + "/S32.h5"; s32 = openmc.data.IncidentNeutron.from_hdf5(s32_path); s32_capture = s32[102]; plt.rcParams['figure.figsize']=[12,8]; plt.loglog(energy_x,flux_vals,label='flux'); plt.loglog(u238_capture.xs['294K'].x,u238_capture.xs['294K'].y,label='U238'); plt.loglog(s32_capture.xs['294K'].x,s32_capture.xs['294K'].y,label='S32'); plt.grid(); plt.legend(); plt.xlabel('Energy [eV]'); ###Output _____no_output_____ ###Markdown Notice the alignment of the first 3 large resonance peaks of U-238 with the first 3 prominent "dips" in flux. I plotted S-32 just for reference; I wanted to see the energy at which its resonance region starts. In general, the resonance region for light isotopes begins at a higher energy than the resonance region for heavy isotopes. S-32 is the only other isotope besides the Uranium isotopes that has a reasonably high mass number and non-trivial atom density. We included U-234 in the model and that must be for a reason. Let's plot U-234 capture cross section along with U-238 and the flux to see if that might be a contributor. ###Code u234_path = OMC_DATA + "/U234.h5"; u234 = openmc.data.IncidentNeutron.from_hdf5(u234_path); u234_capture = u234[102]; plt.rcParams['figure.figsize']=[12,8]; plt.loglog(energy_x,flux_vals,label='flux'); plt.loglog(u238_capture.xs['294K'].x,u238_capture.xs['294K'].y,label='U-238'); plt.loglog(u234_capture.xs['294K'].x,u234_capture.xs['294K'].y,label='U-234'); plt.grid(); plt.legend(); plt.xlabel('Energy [eV]'); ###Output _____no_output_____ ###Markdown Ahh! So it turns out that U-234 has an even bigger and lower-lying capture resonance than U-238. Without a doubt this is why neutron transport models include this (small) isotope. ###Code capture_by_nuclide = sp.get_tally(name='capture_by_nuclide'); capture_by_nuclide_df = capture_by_nuclide.get_pandas_dataframe(); capture_U234 = capture_by_nuclide_df[capture_by_nuclide_df['nuclide']=='U234']['mean'].to_numpy(); capture_U238 = capture_by_nuclide_df[capture_by_nuclide_df['nuclide']=='U238']['mean'].to_numpy(); capture_H1 = capture_by_nuclide_df[capture_by_nuclide_df['nuclide']=='H1']['mean'].to_numpy(); capture_S32 = capture_by_nuclide_df[capture_by_nuclide_df['nuclide']=='S32']['mean'].to_numpy(); capture_O16 = capture_by_nuclide_df[capture_by_nuclide_df['nuclide']=='O16']['mean'].to_numpy(); plt.rcParams['figure.figsize']=[12,8]; plt.loglog(energy_x,flux_vals,label='flux'); plt.loglog(energy_x,capture_U234,label='U-234'); plt.loglog(energy_x,capture_U238,label='U-238'); plt.loglog(energy_x,capture_H1,label='H-1'); plt.loglog(energy_x,capture_S32,label='S-32'); plt.loglog(energy_x,capture_O16,label='O-16'); plt.grid(); plt.legend(); plt.xlabel('Energy [eV]'); ###Output _____no_output_____
notebooks/Test20170524.ipynb
###Markdown SETUP ###Code import time import numpy as np import matplotlib.pyplot as plt import pandas as pd %matplotlib inline ###Output _____no_output_____ ###Markdown Autosipper ###Code # config directory must have "__init__.py" file # from the 'config' directory, import the following classes: from config import Motor, ASI_Controller, Autosipper from config import utils as ut autosipper = Autosipper(Motor('config/motor.yaml'), ASI_Controller('config/asi_controller.yaml')) autosipper.coord_frames from config import gui gui.stage_control(autosipper.XY, autosipper.Z) # add/determine deck info autosipper.coord_frames.deck.position_table = ut.read_delim_pd('config/position_tables/deck') # check deck alignment # CLEAR DECK OF OBSTRUCTIONS!! autosipper.go_to('deck', ['name'],'align') # add plate from config import utils as ut platemap = ut.generate_position_table((8,8),(9,9),93.5) platemap[] ut.lookup(platemap) ###Output _____no_output_____ ###Markdown Manifold ###Code from config import Manifold manifold = Manifold('192.168.1.3', 'config/valvemaps/valvemap.csv', 512) manifold.valvemap[manifold.valvemap.name>0] def valve_states(): tmp = [] for i in [2,0,14,8]: status = 'x' if manifold.read_valve(i): status = 'o' tmp.append([status, manifold.valvemap.name.iloc[i]]) return pd.DataFrame(tmp) tmp = [] for i in range(16): status = 'x' if manifold.read_valve(i): status = 'o' name = manifold.valvemap.name.iloc[i] tmp.append([status, name]) pd.DataFrame(tmp).replace(np.nan, '') name = 'inlet_in' v = manifold.valvemap['valve'][manifold.valvemap.name==name] v=14 manifold.depressurize(v) manifold.pressurize(v) manifold.exit() ###Output _____no_output_____ ###Markdown Micromanager ###Code # !!!! Also must have MM folder on system PATH # mm_version = 'C:\Micro-Manager-1.4' # cfg = 'C:\Micro-Manager-1.4\SetupNumber2_05102016.cfg' mm_version = 'C:\Program Files\Micro-Manager-2.0beta' cfg = 'C:\Program Files\Micro-Manager-2.0beta\Setup2_20170413.cfg' import sys sys.path.insert(0, mm_version) # make it so python can find MMCorePy import MMCorePy from PIL import Image core = MMCorePy.CMMCore() core.loadSystemConfiguration(cfg) core.setProperty("Spectra", "White_Enable", "1") core.waitForDevice("Spectra") core.setProperty("Cam Andor_Zyla4.2", "Sensitivity/DynamicRange", "16-bit (low noise & high well capacity)") # NEED TO SET CAMERA TO 16 BIT (ceiling 12 BIT = 4096) core.setProperty("Spectra", "White_Enable", "0") ###Output _____no_output_____ ###Markdown Preset: 1_PBP ConfigGroup,Channel,1_PBP,TIFilterBlock1,Label,1-PBPPreset: 2_BF ConfigGroup,Channel,2_BF,TIFilterBlock1,Label,2-BFPreset: 3_DAPI ConfigGroup,Channel,3_DAPI,TIFilterBlock1,Label,3-DAPIPreset: 4_eGFP ConfigGroup,Channel,4_eGFP,TIFilterBlock1,Label,4-GFPPreset: 5_Cy5 ConfigGroup,Channel,5_Cy5,TIFilterBlock1,Label,5-Cy5Preset: 6_AttoPhos ConfigGroup,Channel,6_AttoPhos,TIFilterBlock1,Label,6-AttoPhos TEST 4.5 psi, 25 psi valves ###Code log = [] autosipper.Z.move(93.5) manifold.depressurize(2) manifold.depressurize(0) log.append([time.ctime(time.time()), 'open inlet_in, inlet_out']) valve_states() text = 'fluorescence observed' log.append([time.ctime(time.time()), text]) text = 'CLOSE inlet_out' manifold.pressurize(0) log.append([time.ctime(time.time()), text]) text = 'OPEN chip_in, chip_out' manifold.depressurize(14) manifold.depressurize(8) log.append([time.ctime(time.time()), text]) valve_states() text = 'fill' log.append([time.ctime(time.time()), text]) manifold.pressurize(8) #closed all autosipper.Z.move(93.5) manifold.depressurize(2) manifold.depressurize(0) log.append([time.ctime(time.time()), 'open inlet_in, inlet_out']) valve_states() text = 'fluorescence removed' log.append([time.ctime(time.time()), text]) text = 'CLOSE inlet_out' manifold.pressurize(0) log.append([time.ctime(time.time()), text]) text = 'OPEN chip_in, chip_out' manifold.depressurize(14) manifold.depressurize(8) log.append([time.ctime(time.time()), text]) valve_states() text = 'flush' log.append([time.ctime(time.time()), text]) manifold.pressurize(8) for i in [2,0,14,8]: manifold.pressurize(i) ###Output _____no_output_____ ###Markdown ACQUISITION ###Code log core.setConfig('Channel','2_BF') core.setProperty(core.getCameraDevice(), "Exposure", 20) core.snapImage() img = core.getImage() plt.imshow(img,cmap='gray') image = Image.fromarray(img) # image.save('TESTIMAGE.tif') import config.utils as ut position_list = ut.load_mm_positionlist("C:/Users/fordycelab/Desktop/D1_cjm.pos") position_list def acquire(): for i in xrange(len(position_list)): si = str(i) x,y = position_list[['x','y']].iloc[i] core.setXYPosition(x,y) core.waitForDevice(core.getXYStageDevice()) logadd(core, log, 'moved '+si) core.snapImage() # core.waitForDevice(core.getCameraDevice()) logadd(core, log, 'snapped '+si) img = core.getImage() logadd(core, log, 'got image '+si) image = Image.fromarray(img) image.save('images/images_{}.tif'.format(i)) logadd(core, log, 'saved image '+si) x,y = position_list[['x','y']].iloc[0] core.setXYPosition(x,y) core.waitForDevice(core.getXYStageDevice()) logadd(core, log, 'moved '+ str(0)) def logadd(core,log,st): log.append([time.ctime(time.time()), st]) core.logMessage(st) print log[-1] # Trial 1: returning stage to home at end of acquire log = [] for i in xrange(15): sleep = (10*i)*60 logadd(log, 'STRT SLEEP '+ str(sleep/60) + ' min') time.sleep(sleep) logadd(log, 'ACQ STARTED '+str(i)) acquire() core.stopSecondaryLogFile(l2) # Trial 2: returning stage to home at end of acquire # added mm logs # core.setPrimaryLogFile('20170524_log_prim2.txt') # core.enableDebugLog(True) # core.enableStderrLog(True) l2 = core.startSecondaryLogFile('20170524_log_sec3.txt', True, False, True) log = [] for i in xrange(15): sleep = (10*i)*60 logadd(core, log, 'STRT SLEEP '+ str(sleep/60) + ' min') time.sleep(sleep) logadd(core, log, 'ACQ STARTED '+str(i)) acquire() core.stopSecondaryLogFile(l2) # Trial 3: returning stage to home at end of acquire # added mm logs # core.setPrimaryLogFile('20170524_log_prim2.txt') # core.enableDebugLog(True) # core.enableStderrLog(True) l2 = core.startSecondaryLogFile('20170524_log_sec3.txt', True, False, True) log = [] for i in xrange(15): sleep = (10*i)*60 logadd(core, log, 'STRT SLEEP '+ str(sleep/60) + ' min') time.sleep(sleep) logadd(core, log, 'ACQ STARTED '+str(i)) acquire() core.stopSecondaryLogFile(l2) # Trial 4: returning stage to home at end of acquire # added mm logs # after USB fix # core.setPrimaryLogFile('20170524_log_prim2.txt') # core.enableDebugLog(True) # core.enableStderrLog(True) l2 = core.startSecondaryLogFile('20170526_log_sec4.txt', True, False, True) log = [] for i in xrange(15): sleep = (5*i)*60 logadd(core, log, 'STRT SLEEP '+ str(sleep/60) + ' min') time.sleep(sleep) logadd(core, log, 'ACQ STARTED '+str(i)) acquire() core.stopSecondaryLogFile(l2) # Trial 5: returning stage to home at end of acquire # second one after USB fix # core.setPrimaryLogFile('20170524_log_prim2.txt') # core.enableDebugLog(True) # core.enableStderrLog(True) l2 = core.startSecondaryLogFile('20170526_log_sec5.txt', True, False, True) log = [] for i in xrange(15): sleep = (10*i)*60 logadd(core, log, 'STRT SLEEP '+ str(sleep/60) + ' min') time.sleep(sleep) logadd(core, log, 'ACQ STARTED '+str(i)) acquire() core.stopSecondaryLogFile(l2) # Auto core.setAutoShutter(True) # default core.snapImage() # Manual core.setAutoShutter(False) # disable auto shutter core.setProperty("Shutter", "State", "1") core.waitForDevice("Shutter") core.snapImage() core.setProperty("Shutter", "State", "0") ###Output _____no_output_____ ###Markdown MM Get info ###Code core.getFocusDevice() core.getCameraDevice() core.XYStageDevice() core.getDevicePropertyNames(core.getCameraDevice()) ###Output _____no_output_____ ###Markdown Video ###Code import cv2 from IPython import display import numpy as np from ipywidgets import widgets import time # core.initializeCircularBuffer() # core.setCircularBufferMemoryFootprint(4096) # MiB cv2.WND # video with button (CV2) live = widgets.Button(description='Live') close = widgets.Button(description='Close') display.display(widgets.HBox([live, close])) def on_live_clicked(b): display.clear_output(wait=True) print 'LIVE' core.startContinuousSequenceAcquisition(1000) # time overridden by exposure time.sleep(.2) cv2.namedWindow('Video', cv2.WINDOW_NORMAL) cv2.setWindowProperty('Video', cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) cv2.resizeWindow('Video', 500,500) img = np.zeros((500,500)) print 'To stop, click window + press ESC' while(1): time.sleep(.015) if core.getRemainingImageCount() > 0: img = core.getLastImage() cv2.imshow('Video',img) k = cv2.waitKey(30) if k==27: # ESC key; may need 255 mask? break print 'STOPPED' core.stopSequenceAcquisition() def on_close_clicked(b): if core.isSequenceRunning(): core.stopSequenceAcquisition() cv2.destroyWindow('Video') live.on_click(on_live_clicked) close.on_click(on_close_clicked) # video with button (CV2) # serial snap image live = widgets.Button(description='Live') close = widgets.Button(description='Close') display.display(widgets.HBox([live, close])) def on_live_clicked(b): display.clear_output(wait=True) print 'LIVE' cv2.namedWindow('Video', cv2.WINDOW_NORMAL) cv2.setWindowProperty('Video', cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) cv2.resizeWindow('Video', 500,500) img = np.zeros((500,500)) print 'To stop, click window + press ESC' while(1): core.snapImage() time.sleep(.05) img = core.getImage() cv2.imshow('Video',img) k = cv2.waitKey(30) if k==27: # ESC key; may need 255 mask? break print 'STOPPED' def on_close_clicked(b): if core.isSequenceRunning(): core.stopSequenceAcquisition() cv2.destroyWindow('Video') live.on_click(on_live_clicked) close.on_click(on_close_clicked) cv2.destroyAllWindows() ###Output _____no_output_____ ###Markdown SNAP CV2 ###Code # snap (CV2) snap = widgets.Button(description='Snap') close2 = widgets.Button(description='Close') display.display(widgets.HBox([snap, close2])) def on_snap_clicked(b): cv2.destroyWindow('Snap') cv2.namedWindow('Snap',cv2.WINDOW_NORMAL) cv2.resizeWindow('Snap', 500,500) cv2.setWindowProperty('Snap', cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) core.snapImage() time.sleep(.1) img = core.getImage() cv2.imshow('Snap',img) k = cv2.waitKey(30) def on_close2_clicked(b): cv2.destroyWindow('Snap') snap.on_click(on_snap_clicked) close2.on_click(on_close2_clicked) ###Output _____no_output_____ ###Markdown EXIT ###Code autosipper.exit() manifold.exit() core.unloadAllDevices() core.reset() print 'closed' import config.gui as gui core. gui.video(core) gui.snap(core, 'mpl') gui.manifold_control(manifold) ###Output _____no_output_____
Paper_code/Ensemble_FullData.ipynb
###Markdown Ensemble decoder on full dataset User Options ###Code # dataset='s1' # dataset='m1' dataset='hc' #What folder to save the ensemble results to #Note that the data we are loading are in this same folder (since they are the results from the other decoders) save_folder='' # save_folder='/home/jglaser/Files/Neural_Decoding/Results/' ###Output _____no_output_____ ###Markdown Import packages ###Code import numpy as np import matplotlib.pyplot as plt %matplotlib inline from scipy import io from scipy import stats import pickle import sys #Add the main folder to the path, so we have access to the files there. #Note that if your working directory is not the Paper_code folder, you may need to manually specify the path to the main folder. For example: sys.path.append('/home/jglaser/GitProj/Neural_Decoding') sys.path.append('..') #Import metrics from metrics import get_R2 from decoders import DenseNNDecoder from bayes_opt import BayesianOptimization #Turn off deprecation warnings import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) ###Output _____no_output_____ ###Markdown Load results from other decodersNote we do not use the Kalman filter results in our ensemble due to slightly different formatting ###Code with open(save_folder+dataset+'_ground_truth.pickle','rb') as f: [y_test_all,y_train_all,y_valid_all]=pickle.load(f) with open(save_folder+dataset+'_results_wf2.pickle','rb') as f: [mean_r2_wf,y_pred_wf_all,y_train_pred_wf_all,y_valid_pred_wf_all]=pickle.load(f) with open(save_folder+dataset+'_results_wc2.pickle','rb') as f: [mean_r2_wc,y_pred_wc_all,y_train_pred_wc_all,y_valid_pred_wc_all]=pickle.load(f) with open(save_folder+dataset+'_results_xgb2.pickle','rb') as f: [mean_r2_xgb,y_pred_xgb_all,y_train_pred_xgb_all,y_valid_pred_xgb_all,time_elapsed]=pickle.load(f) with open(save_folder+dataset+'_results_svr2.pickle','rb') as f: [mean_r2_svr,y_pred_svr_all,y_train_pred_svr_all,y_valid_pred_svr_all,time_elapsed]=pickle.load(f) with open(save_folder+dataset+'_results_dnn2.pickle','rb') as f: [mean_r2_dnn,y_pred_dnn_all,y_train_pred_dnn_all,y_valid_pred_dnn_all,time_elapsed]=pickle.load(f) with open(save_folder+dataset+'_results_rnn2.pickle','rb') as f: [mean_r2_rnn,y_pred_rnn_all,y_train_pred_rnn_all,y_valid_pred_rnn_all,time_elapsed]=pickle.load(f) with open(save_folder+dataset+'_results_gru2.pickle','rb') as f: [mean_r2_gru,y_pred_gru_all,y_train_pred_gru_all,y_valid_pred_gru_all,time_elapsed]=pickle.load(f) with open(save_folder+dataset+'_results_lstm2.pickle','rb') as f: [mean_r2_lstm,y_pred_lstm_all,y_train_pred_lstm_all,y_valid_pred_lstm_all,time_elapsed]=pickle.load(f) ###Output _____no_output_____ ###Markdown Run ensemble method1. We loop through each CV fold and both out (x and y position/velocities).2. We create the matrix of covariates (the predictions from the other methods)3. We optimize the hyperparameters for the fully connected (dense) neural network we are using, based on validation set R2 values4. We fit the neural net on training data w/ the optimal hyperparameters5. We make test set predictions and get test set R2 values ###Code ##Initialize y_pred_ensemble_all=[] #List where test set predictions are put (for saving and plotting) mean_r2_dnn=np.empty([10,2]) #Where the R2 values are saved (matrix of 10 CV folds x 2 outputs) for i in range(10): #Loop through the cross validation folds for j in range(2): #Loop through the 2 output predictions (x and y positions/velocities) ###CREATE COVARIATES### #Make matrix of covariates, where each feature is the predictions from one of the other decoders #Do this for training, validation, and testing data X_train=np.concatenate((y_train_pred_wf_all[i][:,j:j+1], y_train_pred_wc_all[i][:,j:j+1], y_train_pred_svr_all[i][:,j:j+1],y_train_pred_xgb_all[i][:,j:j+1], y_train_pred_dnn_all[i][:,j:j+1], y_train_pred_rnn_all[i][:,j:j+1], y_train_pred_gru_all[i][:,j:j+1], y_train_pred_lstm_all[i][:,j:j+1]),axis=1) X_valid=np.concatenate((y_valid_pred_wf_all[i][:,j:j+1], y_valid_pred_wc_all[i][:,j:j+1], y_valid_pred_svr_all[i][:,j:j+1],y_valid_pred_xgb_all[i][:,j:j+1], y_valid_pred_dnn_all[i][:,j:j+1], y_valid_pred_rnn_all[i][:,j:j+1], y_valid_pred_gru_all[i][:,j:j+1], y_valid_pred_lstm_all[i][:,j:j+1]),axis=1) X_test=np.concatenate((y_pred_wf_all[i][:,j:j+1], y_pred_wc_all[i][:,j:j+1], y_pred_svr_all[i][:,j:j+1],y_pred_xgb_all[i][:,j:j+1], y_pred_dnn_all[i][:,j:j+1], y_pred_rnn_all[i][:,j:j+1], y_pred_gru_all[i][:,j:j+1], y_pred_lstm_all[i][:,j:j+1]),axis=1) #Get outputs (training/validation/testing) for this CV fold and output y_train=y_train_all[i][:,j:j+1] y_valid=y_valid_all[i][:,j:j+1] y_test=y_test_all[i][:,j:j+1] ###HYPERPARAMETER OPTIMIZATION### #Define a function that returns the metric we are trying to optimize (R2 value of the validation set) #as a function of the hyperparameter we are fitting (num_units, frac_dropout, n_epochs) def dnn_evaluate(num_units,frac_dropout,n_epochs): num_units=int(num_units) #Put in proper format (Bayesian optimization uses floats, and we just want to test the integer) frac_dropout=float(frac_dropout) #Put in proper format n_epochs=int(n_epochs) #Put in proper format model_dnn=DenseNNDecoder(units=[num_units,num_units],dropout=frac_dropout,num_epochs=n_epochs) #Define model model_dnn.fit(X_train,y_train) #Fit model y_valid_predicted_dnn=model_dnn.predict(X_valid) #Get validation set predictions return np.mean(get_R2(y_valid,y_valid_predicted_dnn)) #Return mean validation set R2 #Do bayesian optimization dnnBO = BayesianOptimization(dnn_evaluate, {'num_units': (3, 50), 'frac_dropout': (0,.5), 'n_epochs': (2,10)}, verbose=0) #Define Bayesian optimization, and set limits of hyperparameters #Set number of initial runs and subsequent tests, and do the optimization. Also, we set kappa=10 (greater than the default) so there is more exploration when there are more hyperparameters dnnBO.maximize(init_points=10, n_iter=15, kappa=10) best_params=dnnBO.res['max']['max_params'] #Get the hyperparameters that give rise to the best fit num_units=np.int(best_params['num_units']) #We want the integer value associated with the best "num_units" parameter (which is what the xgb_evaluate function does above) frac_dropout=float(best_params['frac_dropout']) n_epochs=np.int(best_params['n_epochs']) # Run model w/ above hyperparameters model_dnn=DenseNNDecoder(units=[num_units,num_units],dropout=frac_dropout,num_epochs=n_epochs) #Declare model w/ fit hyperparameters model_dnn.fit(X_train,y_train) #Fit model y_test_predicted_dnn=model_dnn.predict(X_test) #Get test set predictions mean_r2_dnn[i,j]=np.mean(get_R2(y_test,y_test_predicted_dnn)) #Get test set R2 #Print R2 values R2s_dnn=get_R2(y_test,y_test_predicted_dnn) print('R2s:', R2s_dnn) y_pred_ensemble_all.append(y_test_predicted_dnn) # #Add test set predictions to list (for saving) mean_r2_ensemble=np.mean(mean_r2_dnn,axis=1) #Get mean R2 value for each fold (across x and y predictions) #Save data with open(save_folder+dataset+'_results_ensemble_dnn2.pickle','wb') as f: pickle.dump([mean_r2_ensemble,y_pred_ensemble_all],f) ###Output /opt/anaconda/anaconda2/lib/python2.7/site-packages/keras/models.py:826: UserWarning: The `nb_epoch` argument in `fit` has been renamed `epochs`. warnings.warn('The `nb_epoch` argument in `fit` '
src/jupyterNotebook.ipynb
###Markdown Welcome to a simple jupyter lab tutorial fileThis cell is rendered in markdown ###Code # This cell is in python code ###Output _____no_output_____ ###Markdown Interactive EnvironmentJupyter Lab is great for development and data science because output appears immediately below the code block: ###Code # lets output some random numbers! import numpy as np rng = np.random.default_rng(seed=42) array = rng.random((100, 1)) array[:20] ###Output _____no_output_____ ###Markdown PlottingWe can also display plots in the notebook without calling external windows/plotters ###Code import matplotlib.pyplot as plt # data to be plotted x = np.arange(1, 101) y = array # plotting plt.title("Random Sampling") plt.xlabel("sample") plt.ylabel("value") plt.plot(x, y, color ="red") plt.show() ###Output _____no_output_____
week2/vishwajeet/Q3 - Q/Attempt1_filesubmission_Vishwajeet_search_based_planning_package.ipynb
###Markdown We are going to use networkx package to construct the graph and find the shortest paths. Refer to the [NetworkX documentation](https://networkx.github.io/documentation/stable/). ###Code #type in the edges and edgecost as a list of 3-tuples edges = [(0,1,2),(0,2, 1.5),(0,3, 2.5),(1,4, 1.5),(2,5, 0.5),(4,8, 1), (2,6, 2.5),(3,7, 2),(7,9, 1.25),(5,10, 2.75),(6,10, 3.25), (9,10, 1.5),(8,10, 3.5)] #Define an empty graph G = nx.Graph() #populate the edges and the cost in graph G G.add_weighted_edges_from(edges,weight='cost') list(G.nodes) #Find the shortest path from Node 0 to Node 10 print(nx.shortest_path(G,0,10,'cost')) #Find the cost of the shortest path from Node 0 to Node 10 print(nx.shortest_path_length(G,0,10,'cost')) ###Output [0, 2, 5, 10] 4.75 ###Markdown Let us now move onto a grid which represents the robot's operating environment. First convert the grid to a graph. Then we will use Astar from networkX to find the shortest path ###Code # write the Euclidean function that takes in the # node x, y and compute the distance def euclidean(node1, node2): x1, y1 = node1 x2, y2 = node2 return np.sqrt((x1-x2)**2+(y1-y2)**2) # use np.load to load a grid of 1s and 0s # 1 - occupied 0- free grid = np.load("astar_grid.npy") print(grid) # you can define your own start/ end start = (0, 0) goal = (0, 19) # visualize the start/ end and the robot's environment fig, ax = plt.subplots(figsize=(12,12)) ax.imshow(grid, cmap=plt.cm.Dark2) ax.scatter(start[1],start[0], marker = "+", color = "yellow", s = 200) ax.scatter(goal[1],goal[0], marker = "+", color = "red", s = 200) plt.show() ###Output _____no_output_____ ###Markdown Convert this grid array into a graph. You have to follow these steps1. Find the dimensions of grid. Use grid_2d_graph() to initialize a grid graph of corresponding dimensions2. Use remove_node() to remove nodes and edges of all cells that are occupied ###Code #initialize graph grid_size=grid.shape G=nx.grid_2d_graph(*grid_size) deleted_nodes = 0 # counter to keep track of deleted nodes #loop to remove nodes for i in range(grid_size[0]): for j in range(grid_size[1]): if grid[i,j]==1: G.remove_node((i,j)) deleted_nodes+=1 print(f"removed {deleted_nodes} nodes") print(f"number of occupied cells in grid {np.sum(grid)}") ###Output _____no_output_____ ###Markdown Visualize the resulting graph using nx.draw(). Note that pos argument for nx.draw() has been given below. The graph is too dense. Try changing the node_size and node_color. You can correlate this graph with the grid's occupied cells ###Code pos = {(x,y):(y,-x) for x,y in G.nodes()} nx.draw(G, pos=pos, node_color='red', node_size=10) ###Output _____no_output_____ ###Markdown We are 2 more steps away from finding the path!1. Set edge attribute. Use set_edge_attributes(). Remember we have to provide a dictionary input: Edge is the key and cost is the value. We can set every move to a neighbor to have unit cost.2. Use astar_path() to find the path. Set heuristic to be euclidean distance. weight to be the attribute you assigned in step 1 ###Code nx.set_edge_attributes(G, {e: 1 for e in G.edges()}, "cost") astar_path = nx.astar_path(G, start, goal, heuristic=euclidean, weight="cost") astar_path ###Output _____no_output_____ ###Markdown Visualize the path you have computed! ###Code fig, ax = plt.subplots(figsize=(12,12)) ax.imshow(grid, cmap=plt.cm.Dark2) ax.scatter(start[1],start[0], marker = "+", color = "yellow", s = 200) ax.scatter(goal[1],goal[0], marker = "+", color = "red", s = 200) for s in astar_path[1:]: ax.plot(s[1], s[0],'r+') ###Output _____no_output_____ ###Markdown Cool! Now you can read arbitrary evironments and find the shortest path between 2 robot positions. Pick a game environment from here and repeat: {https://www.movingai.com/benchmarks/dao/index.html} ###Code from PIL import Image import numpy img= Image.open("combat.png") np_img = numpy.array(img) print(np_img.shape) np_img ###Output _____no_output_____